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.
- warlockcode_wartools_ai/__init__.py +21 -0
- warlockcode_wartools_ai/_generated/__init__.py +1 -0
- warlockcode_wartools_ai/_generated/shared_data.py +5 -0
- warlockcode_wartools_ai/_lib/__init__.py +0 -0
- warlockcode_wartools_ai/_lib/canonical.py +96 -0
- warlockcode_wartools_ai/_lib/common.py +54 -0
- warlockcode_wartools_ai/_lib/errors.py +9 -0
- warlockcode_wartools_ai/_lib/html.py +32 -0
- warlockcode_wartools_ai/_lib/net.py +132 -0
- warlockcode_wartools_ai/_lib/patchapply.py +144 -0
- warlockcode_wartools_ai/_lib/sandbox.py +42 -0
- warlockcode_wartools_ai/_lib/textkit.py +59 -0
- warlockcode_wartools_ai/_lib/timekit.py +59 -0
- warlockcode_wartools_ai/_lib/udiff.py +117 -0
- warlockcode_wartools_ai/_lib/unicode.py +93 -0
- warlockcode_wartools_ai/handlers/__init__.py +43 -0
- warlockcode_wartools_ai/handlers/catalog.py +27 -0
- warlockcode_wartools_ai/handlers/context.py +35 -0
- warlockcode_wartools_ai/handlers/crypto.py +61 -0
- warlockcode_wartools_ai/handlers/csv.py +132 -0
- warlockcode_wartools_ai/handlers/doc.py +77 -0
- warlockcode_wartools_ai/handlers/doc_detect.py +55 -0
- warlockcode_wartools_ai/handlers/encoding.py +57 -0
- warlockcode_wartools_ai/handlers/fs.py +110 -0
- warlockcode_wartools_ai/handlers/json.py +220 -0
- warlockcode_wartools_ai/handlers/kv.py +103 -0
- warlockcode_wartools_ai/handlers/math.py +223 -0
- warlockcode_wartools_ai/handlers/scratchpad.py +82 -0
- warlockcode_wartools_ai/handlers/security.py +50 -0
- warlockcode_wartools_ai/handlers/state.py +40 -0
- warlockcode_wartools_ai/handlers/text.py +183 -0
- warlockcode_wartools_ai/handlers/text_patch.py +24 -0
- warlockcode_wartools_ai/handlers/text_rerank.py +50 -0
- warlockcode_wartools_ai/handlers/time.py +103 -0
- warlockcode_wartools_ai/handlers/time_business.py +109 -0
- warlockcode_wartools_ai/handlers/trace.py +33 -0
- warlockcode_wartools_ai/handlers/validate.py +58 -0
- warlockcode_wartools_ai/handlers/web.py +81 -0
- warlockcode_wartools_ai/mcp.py +106 -0
- warlockcode_wartools_ai/models.py +118 -0
- warlockcode_wartools_ai/py.typed +0 -0
- warlockcode_wartools_ai/registry.py +196 -0
- warlockcode_wartools_ai/runtime/__init__.py +4 -0
- warlockcode_wartools_ai/runtime/pipeline.py +149 -0
- warlockcode_wartools_ai/runtime/policy_store.py +63 -0
- warlockcode_wartools_ai/stores.py +267 -0
- warlockcode_wartools_ai/tools.py +66 -0
- warlockcode_wartools_ai-0.1.1.dist-info/METADATA +34 -0
- warlockcode_wartools_ai-0.1.1.dist-info/RECORD +52 -0
- warlockcode_wartools_ai-0.1.1.dist-info/WHEEL +5 -0
- warlockcode_wartools_ai-0.1.1.dist-info/entry_points.txt +2 -0
- warlockcode_wartools_ai-0.1.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
from typing import Any, Dict, List, Optional
|
|
5
|
+
|
|
6
|
+
from .._lib.common import clean_number
|
|
7
|
+
from .._lib.errors import ToolExecutionError
|
|
8
|
+
from .context import Handler, ToolContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def evaluate_math_ast(expression: str) -> float:
|
|
12
|
+
src = expression.strip()
|
|
13
|
+
if not src:
|
|
14
|
+
raise ToolExecutionError("EXPRESSION_ERROR", "Expression cannot be empty.")
|
|
15
|
+
pos = 0
|
|
16
|
+
|
|
17
|
+
def skip_ws() -> None:
|
|
18
|
+
nonlocal pos
|
|
19
|
+
while pos < len(src) and src[pos].isspace():
|
|
20
|
+
pos += 1
|
|
21
|
+
|
|
22
|
+
def peek() -> Optional[str]:
|
|
23
|
+
skip_ws()
|
|
24
|
+
return src[pos] if pos < len(src) else None
|
|
25
|
+
|
|
26
|
+
def parse_expression() -> float:
|
|
27
|
+
return parse_add_sub()
|
|
28
|
+
|
|
29
|
+
def parse_add_sub() -> float:
|
|
30
|
+
left = parse_mul_div()
|
|
31
|
+
while True:
|
|
32
|
+
ch = peek()
|
|
33
|
+
if ch == "+":
|
|
34
|
+
nonlocal pos
|
|
35
|
+
pos += 1
|
|
36
|
+
left += parse_mul_div()
|
|
37
|
+
elif ch == "-":
|
|
38
|
+
pos += 1
|
|
39
|
+
left -= parse_mul_div()
|
|
40
|
+
else:
|
|
41
|
+
break
|
|
42
|
+
return left
|
|
43
|
+
|
|
44
|
+
def parse_mul_div() -> float:
|
|
45
|
+
nonlocal pos
|
|
46
|
+
left = parse_power()
|
|
47
|
+
while True:
|
|
48
|
+
ch = peek()
|
|
49
|
+
if ch == "*":
|
|
50
|
+
pos += 1
|
|
51
|
+
left *= parse_power()
|
|
52
|
+
elif ch == "/":
|
|
53
|
+
pos += 1
|
|
54
|
+
d = parse_power()
|
|
55
|
+
if d == 0:
|
|
56
|
+
raise ToolExecutionError("DIVISION_BY_ZERO", "Division by zero.")
|
|
57
|
+
left /= d
|
|
58
|
+
elif ch == "%":
|
|
59
|
+
pos += 1
|
|
60
|
+
d = parse_power()
|
|
61
|
+
if d == 0:
|
|
62
|
+
raise ToolExecutionError("DIVISION_BY_ZERO", "Modulo by zero.")
|
|
63
|
+
left %= d
|
|
64
|
+
else:
|
|
65
|
+
break
|
|
66
|
+
return left
|
|
67
|
+
|
|
68
|
+
def parse_power() -> float:
|
|
69
|
+
nonlocal pos
|
|
70
|
+
base = parse_unary()
|
|
71
|
+
if peek() == "^":
|
|
72
|
+
pos += 1
|
|
73
|
+
return math.pow(base, parse_power())
|
|
74
|
+
return base
|
|
75
|
+
|
|
76
|
+
def parse_unary() -> float:
|
|
77
|
+
nonlocal pos
|
|
78
|
+
ch = peek()
|
|
79
|
+
if ch == "-":
|
|
80
|
+
pos += 1
|
|
81
|
+
return -parse_unary()
|
|
82
|
+
if ch == "+":
|
|
83
|
+
pos += 1
|
|
84
|
+
return parse_unary()
|
|
85
|
+
return parse_primary()
|
|
86
|
+
|
|
87
|
+
def parse_primary() -> float:
|
|
88
|
+
nonlocal pos
|
|
89
|
+
ch = peek()
|
|
90
|
+
if ch == "(":
|
|
91
|
+
pos += 1
|
|
92
|
+
val = parse_expression()
|
|
93
|
+
if peek() != ")":
|
|
94
|
+
raise ToolExecutionError("EXPRESSION_ERROR", "Missing closing parenthesis.")
|
|
95
|
+
pos += 1
|
|
96
|
+
return val
|
|
97
|
+
if ch is not None and (ch.isdigit() or ch == "."):
|
|
98
|
+
start = pos
|
|
99
|
+
while pos < len(src) and (src[pos].isdigit() or src[pos] == "."):
|
|
100
|
+
pos += 1
|
|
101
|
+
try:
|
|
102
|
+
return float(src[start:pos])
|
|
103
|
+
except ValueError:
|
|
104
|
+
raise ToolExecutionError("EXPRESSION_ERROR", "Invalid number literal.")
|
|
105
|
+
if ch is not None and (ch.isalpha() or ch == "_"):
|
|
106
|
+
start = pos
|
|
107
|
+
while pos < len(src) and (src[pos].isalnum() or src[pos] == "_"):
|
|
108
|
+
pos += 1
|
|
109
|
+
ident = src[start:pos].lower()
|
|
110
|
+
if ident == "pi":
|
|
111
|
+
return math.pi
|
|
112
|
+
if ident == "e":
|
|
113
|
+
return math.e
|
|
114
|
+
if peek() != "(":
|
|
115
|
+
raise ToolExecutionError("EXPRESSION_ERROR", f'Unknown identifier "{ident}".')
|
|
116
|
+
pos += 1
|
|
117
|
+
args: List[float] = []
|
|
118
|
+
if peek() != ")":
|
|
119
|
+
while True:
|
|
120
|
+
args.append(parse_expression())
|
|
121
|
+
if peek() == ",":
|
|
122
|
+
pos += 1
|
|
123
|
+
else:
|
|
124
|
+
break
|
|
125
|
+
if peek() != ")":
|
|
126
|
+
raise ToolExecutionError("EXPRESSION_ERROR", f'Expected ")" after {ident}.')
|
|
127
|
+
pos += 1
|
|
128
|
+
if ident == "round":
|
|
129
|
+
digits = int(args[1]) if len(args) > 1 else 0
|
|
130
|
+
return round(args[0], digits)
|
|
131
|
+
if ident == "ceil":
|
|
132
|
+
return float(math.ceil(args[0]))
|
|
133
|
+
if ident == "floor":
|
|
134
|
+
return float(math.floor(args[0]))
|
|
135
|
+
if ident == "sqrt":
|
|
136
|
+
if args[0] < 0:
|
|
137
|
+
raise ToolExecutionError("EXPRESSION_ERROR", "sqrt input must be non-negative.")
|
|
138
|
+
return math.sqrt(args[0])
|
|
139
|
+
if ident == "abs":
|
|
140
|
+
return abs(args[0])
|
|
141
|
+
if ident == "min":
|
|
142
|
+
return min(args)
|
|
143
|
+
if ident == "max":
|
|
144
|
+
return max(args)
|
|
145
|
+
raise ToolExecutionError("EXPRESSION_ERROR", f'Unsupported function "{ident}".')
|
|
146
|
+
raise ToolExecutionError("EXPRESSION_ERROR", f'Unexpected character "{ch or "EOF"}".')
|
|
147
|
+
|
|
148
|
+
res = parse_expression()
|
|
149
|
+
skip_ws()
|
|
150
|
+
if pos < len(src):
|
|
151
|
+
raise ToolExecutionError("EXPRESSION_ERROR", f'Unexpected token "{src[pos:]}".')
|
|
152
|
+
return res
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def math_eval(ctx: ToolContext) -> Any:
|
|
156
|
+
inp = ctx.input
|
|
157
|
+
val = evaluate_math_ast(str(inp.get("expression") or ""))
|
|
158
|
+
prec_raw = inp.get("precision")
|
|
159
|
+
if isinstance(prec_raw, (int, float)):
|
|
160
|
+
prec = max(0, min(int(prec_raw), 12))
|
|
161
|
+
numeric = clean_number(round(val, prec))
|
|
162
|
+
return {"result": f"{val:.{prec}f}", "numeric": numeric}
|
|
163
|
+
cleaned = clean_number(val)
|
|
164
|
+
return {"result": str(cleaned), "numeric": cleaned}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def math_stats(ctx: ToolContext) -> Any:
|
|
168
|
+
inp = ctx.input
|
|
169
|
+
raw_vals = inp.get("values")
|
|
170
|
+
if not isinstance(raw_vals, list) or not raw_vals:
|
|
171
|
+
raise ToolExecutionError("INVALID_INPUT", "values must be a non-empty number array.")
|
|
172
|
+
nums = sorted(float(v) for v in raw_vals)
|
|
173
|
+
count = len(nums)
|
|
174
|
+
total = sum(nums)
|
|
175
|
+
mean = total / count
|
|
176
|
+
mid = count // 2
|
|
177
|
+
median = (nums[mid - 1] + nums[mid]) / 2.0 if count % 2 == 0 else nums[mid]
|
|
178
|
+
variance = sum((v - mean) ** 2 for v in nums) / count
|
|
179
|
+
p95_idx = min(count - 1, math.ceil(0.95 * count) - 1)
|
|
180
|
+
return {
|
|
181
|
+
"count": count,
|
|
182
|
+
"sum": clean_number(round(total, 6)),
|
|
183
|
+
"mean": clean_number(round(mean, 6)),
|
|
184
|
+
"median": clean_number(median),
|
|
185
|
+
"min": clean_number(nums[0]),
|
|
186
|
+
"max": clean_number(nums[-1]),
|
|
187
|
+
"stdDev": clean_number(round(math.sqrt(variance), 6)),
|
|
188
|
+
"p95": clean_number(nums[p95_idx]),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def math_convert_unit(ctx: ToolContext) -> Any:
|
|
193
|
+
inp = ctx.input
|
|
194
|
+
try:
|
|
195
|
+
value = float(inp.get("value")) # type: ignore[arg-type]
|
|
196
|
+
except Exception:
|
|
197
|
+
raise ToolExecutionError("INVALID_INPUT", "value, fromUnit, and toUnit are required.")
|
|
198
|
+
from_unit = str(inp.get("fromUnit") or "")
|
|
199
|
+
to_unit = str(inp.get("toUnit") or "")
|
|
200
|
+
if not from_unit or not to_unit:
|
|
201
|
+
raise ToolExecutionError("INVALID_INPUT", "value, fromUnit, and toUnit are required.")
|
|
202
|
+
if from_unit.upper() in {"C", "F", "K"} and to_unit.upper() in {"C", "F", "K"}:
|
|
203
|
+
f, t = from_unit.upper(), to_unit.upper()
|
|
204
|
+
c = value if f == "C" else (value - 32.0) * 5.0 / 9.0 if f == "F" else value - 273.15
|
|
205
|
+
out = c if t == "C" else (c * 9.0 / 5.0) + 32.0 if t == "F" else c + 273.15
|
|
206
|
+
return {"value": clean_number(round(out, 6)), "unit": to_unit}
|
|
207
|
+
tables = [
|
|
208
|
+
{"m": 1.0, "km": 1000.0, "cm": 0.01, "mm": 0.001, "mi": 1609.344, "ft": 0.3048, "in": 0.0254},
|
|
209
|
+
{"kg": 1.0, "g": 0.001, "mg": 1e-6, "lb": 0.45359237, "oz": 0.028349523125},
|
|
210
|
+
{"s": 1.0, "ms": 0.001, "min": 60.0, "h": 3600.0, "d": 86400.0},
|
|
211
|
+
{"B": 1.0, "KB": 1000.0, "MB": 1e6, "GB": 1e9, "TB": 1e12, "KiB": 1024.0, "MiB": float(1024**2), "GiB": float(1024**3), "TiB": float(1024**4)},
|
|
212
|
+
]
|
|
213
|
+
group = next((tbl for tbl in tables if from_unit in tbl and to_unit in tbl), None)
|
|
214
|
+
if not group:
|
|
215
|
+
raise ToolExecutionError("UNSUPPORTED_UNIT", f'Cannot convert "{from_unit}" to "{to_unit}".')
|
|
216
|
+
return {"value": clean_number(round((value * group[from_unit]) / group[to_unit], 6)), "unit": to_unit}
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
HANDLERS: Dict[str, Handler] = {
|
|
220
|
+
"math.eval": math_eval,
|
|
221
|
+
"math.stats": math_stats,
|
|
222
|
+
"math.convert_unit": math_convert_unit,
|
|
223
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Dict
|
|
5
|
+
|
|
6
|
+
from .._lib.errors import ToolExecutionError
|
|
7
|
+
from .context import Handler, ToolContext
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def scratchpad_set_plan(ctx: ToolContext) -> Any:
|
|
11
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
12
|
+
goal = str(inp.get("goal") or "")
|
|
13
|
+
raw_steps = inp.get("steps") if isinstance(inp.get("steps"), list) else []
|
|
14
|
+
if not goal or not raw_steps:
|
|
15
|
+
raise ToolExecutionError("INVALID_INPUT", "goal and non-empty steps array are required.")
|
|
16
|
+
sp = store.get_scratchpad(session_id)
|
|
17
|
+
steps = [
|
|
18
|
+
{"id": str(s.get("id") or f"step_{i+1}"), "title": str(s.get("title") or f"Step {i+1}"), "status": "pending"}
|
|
19
|
+
for i, s in enumerate(raw_steps)
|
|
20
|
+
if isinstance(s, dict)
|
|
21
|
+
]
|
|
22
|
+
store.save_scratchpad(session_id, {"goal": goal, "steps": steps, "notes": sp["notes"]})
|
|
23
|
+
return {"goal": goal, "steps": steps}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def scratchpad_update_step(ctx: ToolContext) -> Any:
|
|
27
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
28
|
+
step_id = str(inp.get("stepId") or "")
|
|
29
|
+
status = str(inp.get("status") or "")
|
|
30
|
+
if not step_id or status not in {"pending", "in_progress", "completed", "blocked", "skipped"}:
|
|
31
|
+
raise ToolExecutionError("INVALID_INPUT", "Valid stepId and status are required.")
|
|
32
|
+
sp = store.get_scratchpad(session_id)
|
|
33
|
+
target = next((s for s in sp["steps"] if s["id"] == step_id), None)
|
|
34
|
+
if not target:
|
|
35
|
+
raise ToolExecutionError("STEP_NOT_FOUND", f'Step "{step_id}" not found.')
|
|
36
|
+
target["status"] = status
|
|
37
|
+
if isinstance(inp.get("resultSummary"), str):
|
|
38
|
+
target["resultSummary"] = inp["resultSummary"]
|
|
39
|
+
store.save_scratchpad(session_id, sp)
|
|
40
|
+
total = len(sp["steps"]) or 1
|
|
41
|
+
done = sum(1 for s in sp["steps"] if s["status"] in ("completed", "skipped"))
|
|
42
|
+
nxt = next((s for s in sp["steps"] if s["status"] == "pending"), None)
|
|
43
|
+
return {"updated": True, "progressPercent": round((done / total) * 100), "nextPendingStep": nxt}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def scratchpad_add_note(ctx: ToolContext) -> Any:
|
|
47
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
48
|
+
content = str(inp.get("content") or "")
|
|
49
|
+
if not content:
|
|
50
|
+
raise ToolExecutionError("INVALID_INPUT", "content is required.")
|
|
51
|
+
sp = store.get_scratchpad(session_id)
|
|
52
|
+
note = {
|
|
53
|
+
"noteId": f"note_{len(sp['notes']) + 1}",
|
|
54
|
+
"tag": str(inp.get("tag") or "general"),
|
|
55
|
+
"content": content,
|
|
56
|
+
"createdAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
57
|
+
}
|
|
58
|
+
sp["notes"].append(note)
|
|
59
|
+
store.save_scratchpad(session_id, sp)
|
|
60
|
+
return {"noteId": note["noteId"], "totalNotes": len(sp["notes"])}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def scratchpad_get_workspace(ctx: ToolContext) -> Any:
|
|
64
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
65
|
+
include_notes = inp.get("includeNotes") is not False
|
|
66
|
+
sp = store.get_scratchpad(session_id)
|
|
67
|
+
total = len(sp["steps"])
|
|
68
|
+
done = sum(1 for s in sp["steps"] if s["status"] in ("completed", "skipped"))
|
|
69
|
+
return {
|
|
70
|
+
"goal": sp["goal"],
|
|
71
|
+
"steps": sp["steps"],
|
|
72
|
+
"notes": sp["notes"] if include_notes else [],
|
|
73
|
+
"progressPercent": round((done / total) * 100) if total > 0 else 0,
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
HANDLERS: Dict[str, Handler] = {
|
|
78
|
+
"scratchpad.set_plan": scratchpad_set_plan,
|
|
79
|
+
"scratchpad.update_step": scratchpad_update_step,
|
|
80
|
+
"scratchpad.add_note": scratchpad_add_note,
|
|
81
|
+
"scratchpad.get_workspace": scratchpad_get_workspace,
|
|
82
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import urllib.parse
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from .._lib.net import is_private_ip
|
|
8
|
+
from .context import Handler, ToolContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def security_scan_prompt_injection(ctx: ToolContext) -> Any:
|
|
12
|
+
inp = ctx.input
|
|
13
|
+
text = str(inp.get("text") or "")
|
|
14
|
+
flags: List[str] = []
|
|
15
|
+
if re.search(r"ignore (?:all |previous |prior )+instructions", text, re.IGNORECASE):
|
|
16
|
+
flags.append("instruction_override_phrase")
|
|
17
|
+
if re.search(r"(?:reveal|print|dump|leak).{0,24}(?:system prompt|secret|api key)", text, re.IGNORECASE):
|
|
18
|
+
flags.append("secret_or_prompt_exfiltration")
|
|
19
|
+
if re.search(r"(?:^|\n)\s*(?:system|developer|assistant)\s*:", text, re.IGNORECASE) or re.search(r"<\|im_start\|>", text, re.IGNORECASE):
|
|
20
|
+
flags.append("role_impersonation_marker")
|
|
21
|
+
if re.search(r"[\u200B-\u200F\u202A-\u202E\uFEFF]", text):
|
|
22
|
+
flags.append("hidden_unicode_control_chars")
|
|
23
|
+
risk = "high" if len(flags) >= 2 else "medium" if len(flags) == 1 else "low"
|
|
24
|
+
sanitized = re.sub(r"[\u200B-\u200F\u202A-\u202E\uFEFF]", "", text)
|
|
25
|
+
return {"riskLevel": risk, "flags": flags, "sanitizedText": sanitized}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def security_url_inspect(ctx: ToolContext) -> Any:
|
|
29
|
+
inp = ctx.input
|
|
30
|
+
raw_url = str(inp.get("url") or "")
|
|
31
|
+
p = urllib.parse.urlparse(raw_url)
|
|
32
|
+
if not p.scheme or not p.netloc:
|
|
33
|
+
return {"valid": False, "protocol": "", "host": "", "isPrivateNetwork": False, "isPunycode": False, "queryParams": {}}
|
|
34
|
+
host = (p.hostname or "").lower()
|
|
35
|
+
is_local = host == "localhost" or host.endswith(".local") or host.endswith(".internal") or is_private_ip(host)
|
|
36
|
+
query_params = {k: v[0] if v else "" for k, v in urllib.parse.parse_qs(p.query, keep_blank_values=True).items()}
|
|
37
|
+
return {
|
|
38
|
+
"valid": True,
|
|
39
|
+
"protocol": p.scheme,
|
|
40
|
+
"host": host,
|
|
41
|
+
"isPrivateNetwork": is_local,
|
|
42
|
+
"isPunycode": "xn--" in host,
|
|
43
|
+
"queryParams": query_params,
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
HANDLERS: Dict[str, Handler] = {
|
|
48
|
+
"security.scan_prompt_injection": security_scan_prompt_injection,
|
|
49
|
+
"security.url_inspect": security_url_inspect,
|
|
50
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timezone
|
|
4
|
+
from typing import Any, Dict
|
|
5
|
+
|
|
6
|
+
from .._lib.errors import ToolExecutionError
|
|
7
|
+
from .context import Handler, ToolContext
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def state_checkpoint(ctx: ToolContext) -> Any:
|
|
11
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
12
|
+
action = str(inp.get("action") or "list")
|
|
13
|
+
cp_name = str(inp.get("checkpointName") or "default")
|
|
14
|
+
now_iso = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
15
|
+
if action == "save":
|
|
16
|
+
store.save_checkpoint(
|
|
17
|
+
session_id,
|
|
18
|
+
{
|
|
19
|
+
"name": cp_name,
|
|
20
|
+
"timestamp": now_iso,
|
|
21
|
+
"kv": store.list_all_session_kv(session_id),
|
|
22
|
+
"scratchpad": store.get_scratchpad(session_id),
|
|
23
|
+
},
|
|
24
|
+
)
|
|
25
|
+
elif action == "restore":
|
|
26
|
+
cp = store.load_checkpoint(session_id, cp_name)
|
|
27
|
+
if not cp:
|
|
28
|
+
raise ToolExecutionError("CHECKPOINT_NOT_FOUND", f'Checkpoint "{cp_name}" does not exist.')
|
|
29
|
+
store.replace_session_kv(session_id, cp["kv"])
|
|
30
|
+
store.save_scratchpad(session_id, cp["scratchpad"])
|
|
31
|
+
return {
|
|
32
|
+
"checkpointName": cp_name,
|
|
33
|
+
"timestamp": now_iso,
|
|
34
|
+
"availableCheckpoints": [c["name"] for c in store.list_checkpoints(session_id)],
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
HANDLERS: Dict[str, Handler] = {
|
|
39
|
+
"state.checkpoint": state_checkpoint,
|
|
40
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Callable, Dict, List
|
|
6
|
+
|
|
7
|
+
from .._lib.errors import ToolExecutionError
|
|
8
|
+
from .._lib.udiff import build_unified_diff
|
|
9
|
+
from .context import Handler, ToolContext
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def luhn_valid(digits: str) -> bool:
|
|
13
|
+
total = 0
|
|
14
|
+
alt = False
|
|
15
|
+
for ch in reversed(digits):
|
|
16
|
+
n = int(ch)
|
|
17
|
+
if alt:
|
|
18
|
+
n *= 2
|
|
19
|
+
if n > 9:
|
|
20
|
+
n -= 9
|
|
21
|
+
total += n
|
|
22
|
+
alt = not alt
|
|
23
|
+
return total % 10 == 0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def text_chunk(ctx: ToolContext) -> Any:
|
|
27
|
+
inp = ctx.input
|
|
28
|
+
text = str(inp.get("text") or "")
|
|
29
|
+
max_chars = max(20, int(inp.get("maxChars") or 500))
|
|
30
|
+
overlap = max(0, min(int(inp.get("overlapChars") or 0), max_chars // 2))
|
|
31
|
+
strategy = str(inp.get("strategy") or "paragraph")
|
|
32
|
+
if strategy == "markdown":
|
|
33
|
+
units = [u for u in re.split(r"(?=^#{1,6}\s)", text, flags=re.MULTILINE) if u]
|
|
34
|
+
elif strategy == "sentence":
|
|
35
|
+
units = [u for u in re.split(r"(?<=[.!?])\s+", text) if u]
|
|
36
|
+
else:
|
|
37
|
+
units = [u for u in re.split(r"\n{2,}", text) if u]
|
|
38
|
+
chunks: List[Dict[str, Any]] = []
|
|
39
|
+
buf = ""
|
|
40
|
+
for u in units:
|
|
41
|
+
if len(buf) + len(u) + 1 <= max_chars:
|
|
42
|
+
buf = f"{buf}\n{u}" if buf else u
|
|
43
|
+
else:
|
|
44
|
+
if buf:
|
|
45
|
+
chunks.append({"index": len(chunks), "text": buf, "charCount": len(buf)})
|
|
46
|
+
tail = buf[-overlap:] if overlap > 0 and buf else ""
|
|
47
|
+
buf = (f"{tail}\n{u}" if tail else u)[:max_chars]
|
|
48
|
+
if buf:
|
|
49
|
+
chunks.append({"index": len(chunks), "text": buf, "charCount": len(buf)})
|
|
50
|
+
return {"chunks": chunks, "totalChunks": len(chunks)}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def text_regex_extract(ctx: ToolContext) -> Any:
|
|
54
|
+
inp = ctx.input
|
|
55
|
+
text = str(inp.get("text") or "")[:100000]
|
|
56
|
+
pattern = str(inp.get("pattern") or "")
|
|
57
|
+
if not pattern:
|
|
58
|
+
raise ToolExecutionError("INVALID_INPUT", "pattern is required.")
|
|
59
|
+
raw_flags = str(inp.get("flags") or "g")
|
|
60
|
+
py_flags = 0
|
|
61
|
+
if "i" in raw_flags:
|
|
62
|
+
py_flags |= re.IGNORECASE
|
|
63
|
+
if "m" in raw_flags:
|
|
64
|
+
py_flags |= re.MULTILINE
|
|
65
|
+
if "s" in raw_flags:
|
|
66
|
+
py_flags |= re.DOTALL
|
|
67
|
+
try:
|
|
68
|
+
compiled = re.compile(pattern, py_flags)
|
|
69
|
+
except re.error:
|
|
70
|
+
raise ToolExecutionError("INVALID_REGEX", "Invalid regular expression pattern.")
|
|
71
|
+
max_matches = min(int(inp.get("maxMatches") or 50), 200)
|
|
72
|
+
matches = []
|
|
73
|
+
for m in compiled.finditer(text):
|
|
74
|
+
if len(matches) >= max_matches:
|
|
75
|
+
break
|
|
76
|
+
matches.append({"fullMatch": m.group(0), "groups": [g or "" for g in m.groups()], "index": m.start()})
|
|
77
|
+
return {"matches": matches, "count": len(matches)}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def text_count_tokens_approx(ctx: ToolContext) -> Any:
|
|
81
|
+
inp = ctx.input
|
|
82
|
+
if not isinstance(inp.get("text"), str):
|
|
83
|
+
raise ToolExecutionError("INVALID_INPUT", "text must be a string.")
|
|
84
|
+
text = inp["text"]
|
|
85
|
+
chars = len(text)
|
|
86
|
+
words = len(text.strip().split()) if text.strip() else 0
|
|
87
|
+
lines = len(text.splitlines()) if text else 0
|
|
88
|
+
return {"approxTokens": max(1 if words > 0 else 0, math.ceil(chars / 4)), "words": words, "lines": lines, "chars": chars}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def text_diff(ctx: ToolContext) -> Any:
|
|
92
|
+
inp = ctx.input
|
|
93
|
+
if not isinstance(inp.get("original"), str) or not isinstance(inp.get("updated"), str):
|
|
94
|
+
raise ToolExecutionError("INVALID_INPUT", "original and updated must be strings.")
|
|
95
|
+
ctx = 3
|
|
96
|
+
raw_ctx = inp.get("contextLines")
|
|
97
|
+
if raw_ctx is not None:
|
|
98
|
+
if isinstance(raw_ctx, bool) or not isinstance(raw_ctx, (int, float)):
|
|
99
|
+
raise ToolExecutionError("INVALID_INPUT", "contextLines must be a number.")
|
|
100
|
+
ctx = raw_ctx
|
|
101
|
+
result = build_unified_diff(inp["original"], inp["updated"], ctx)
|
|
102
|
+
if result is None:
|
|
103
|
+
raise ToolExecutionError("INPUT_TOO_LARGE", "Inputs differ in too many lines to diff.")
|
|
104
|
+
return result
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def text_redact_pii(ctx: ToolContext) -> Any:
|
|
108
|
+
inp = ctx.input
|
|
109
|
+
if not isinstance(inp.get("text"), str):
|
|
110
|
+
raise ToolExecutionError("INVALID_INPUT", "text must be a string.")
|
|
111
|
+
text = inp["text"]
|
|
112
|
+
types = inp.get("types")
|
|
113
|
+
allowed = set(types) if isinstance(types, list) and types else {"email", "phone", "card", "ip", "secret"}
|
|
114
|
+
detected: List[str] = []
|
|
115
|
+
findings = 0
|
|
116
|
+
|
|
117
|
+
def mark(kind: str, replacement: str) -> Callable[[re.Match[str]], str]:
|
|
118
|
+
def _sub(_: re.Match[str]) -> str:
|
|
119
|
+
nonlocal findings
|
|
120
|
+
if kind not in detected:
|
|
121
|
+
detected.append(kind)
|
|
122
|
+
findings += 1
|
|
123
|
+
return replacement
|
|
124
|
+
return _sub
|
|
125
|
+
|
|
126
|
+
if "email" in allowed:
|
|
127
|
+
text = re.sub(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", mark("email", "[REDACTED_EMAIL]"), text)
|
|
128
|
+
if "secret" in allowed:
|
|
129
|
+
text = re.sub(r"\b(?:sk_(?:live|test)_[A-Za-z0-9]{10,}|ghp_[A-Za-z0-9]{16,}|AIza[0-9A-Za-z_-]{16,})\b", mark("secret", "[REDACTED_SECRET]"), text)
|
|
130
|
+
if "card" in allowed:
|
|
131
|
+
def _card_sub(m: re.Match[str]) -> str:
|
|
132
|
+
nonlocal findings
|
|
133
|
+
digits = re.sub(r"\D", "", m.group(0))
|
|
134
|
+
if 13 <= len(digits) <= 19 and luhn_valid(digits):
|
|
135
|
+
if "card" not in detected:
|
|
136
|
+
detected.append("card")
|
|
137
|
+
findings += 1
|
|
138
|
+
return "[REDACTED_CARD]"
|
|
139
|
+
return m.group(0)
|
|
140
|
+
text = re.sub(r"\b(?:\d[ -]*?){13,19}\b", _card_sub, text)
|
|
141
|
+
if "ip" in allowed:
|
|
142
|
+
def _ip_sub(m: re.Match[str]) -> str:
|
|
143
|
+
nonlocal findings
|
|
144
|
+
if all(int(part) <= 255 for part in m.group(0).split(".")):
|
|
145
|
+
if "ip" not in detected:
|
|
146
|
+
detected.append("ip")
|
|
147
|
+
findings += 1
|
|
148
|
+
return "[REDACTED_IP]"
|
|
149
|
+
return m.group(0)
|
|
150
|
+
text = re.sub(r"\b(?:\d{1,3}\.){3}\d{1,3}\b", _ip_sub, text)
|
|
151
|
+
if "phone" in allowed:
|
|
152
|
+
text = re.sub(r"(?:\+?\d{1,3}[\s.-]?)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}", mark("phone", "[REDACTED_PHONE]"), text)
|
|
153
|
+
return {"redactedText": text, "findingsCount": findings, "typesDetected": detected}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def text_template_render(ctx: ToolContext) -> Any:
|
|
157
|
+
inp = ctx.input
|
|
158
|
+
template = str(inp.get("template") or "")
|
|
159
|
+
variables = inp.get("variables") if isinstance(inp.get("variables"), dict) else {}
|
|
160
|
+
strict = bool(inp.get("strict"))
|
|
161
|
+
missing: List[str] = []
|
|
162
|
+
|
|
163
|
+
def _rep(m: re.Match[str]) -> str:
|
|
164
|
+
key = m.group(1)
|
|
165
|
+
if key in variables and variables[key] is not None:
|
|
166
|
+
return str(variables[key])
|
|
167
|
+
missing.append(key)
|
|
168
|
+
return ""
|
|
169
|
+
|
|
170
|
+
rendered = re.sub(r"\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}", _rep, template)
|
|
171
|
+
if strict and missing:
|
|
172
|
+
raise ToolExecutionError("MISSING_TEMPLATE_VARIABLES", f"Missing template variables: {', '.join(missing)}")
|
|
173
|
+
return {"rendered": rendered, "missingVariables": missing}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
HANDLERS: Dict[str, Handler] = {
|
|
177
|
+
"text.chunk": text_chunk,
|
|
178
|
+
"text.regex_extract": text_regex_extract,
|
|
179
|
+
"text.count_tokens_approx": text_count_tokens_approx,
|
|
180
|
+
"text.diff": text_diff,
|
|
181
|
+
"text.redact_pii": text_redact_pii,
|
|
182
|
+
"text.template_render": text_template_render,
|
|
183
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .._lib.errors import ToolExecutionError
|
|
4
|
+
from .._lib.patchapply import PatchError, apply_patch, parse_patch
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _apply_patch(ctx):
|
|
8
|
+
inp = ctx.input
|
|
9
|
+
original = inp.get("original")
|
|
10
|
+
patch = inp.get("patch")
|
|
11
|
+
if not isinstance(original, str):
|
|
12
|
+
raise ToolExecutionError("INVALID_INPUT", '"original" must be a string.')
|
|
13
|
+
if not isinstance(patch, str):
|
|
14
|
+
raise ToolExecutionError("INVALID_INPUT", '"patch" must be a string.')
|
|
15
|
+
try:
|
|
16
|
+
hunks = parse_patch(patch)
|
|
17
|
+
patched, additions, deletions = apply_patch(original, hunks)
|
|
18
|
+
except PatchError as err:
|
|
19
|
+
code = "PATCH_CONFLICT" if err.kind == "conflict" else "INVALID_INPUT"
|
|
20
|
+
raise ToolExecutionError(code, str(err))
|
|
21
|
+
return {"patched": patched, "hunksApplied": len(hunks), "additions": additions, "deletions": deletions}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
HANDLERS = {"text.apply_patch": _apply_patch}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, List, Optional
|
|
4
|
+
|
|
5
|
+
from .._lib.errors import ToolExecutionError
|
|
6
|
+
from .._lib.textkit import bm25_scores, round4, tokenize
|
|
7
|
+
|
|
8
|
+
MAX_CHUNKS = 1000
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def rerank_chunks(ctx: Any) -> Any:
|
|
12
|
+
inp = ctx.input
|
|
13
|
+
query = inp.get("query")
|
|
14
|
+
if not isinstance(query, str) or query.strip() == "":
|
|
15
|
+
raise ToolExecutionError("INVALID_INPUT", "query must be a non-empty string.")
|
|
16
|
+
chunks = inp.get("chunks")
|
|
17
|
+
if not isinstance(chunks, list) or len(chunks) == 0 or len(chunks) > MAX_CHUNKS:
|
|
18
|
+
raise ToolExecutionError("INVALID_INPUT", f"chunks must be a non-empty array (max {MAX_CHUNKS}).")
|
|
19
|
+
texts: List[str] = []
|
|
20
|
+
ids: List[Optional[str]] = []
|
|
21
|
+
for c in chunks:
|
|
22
|
+
if isinstance(c, str):
|
|
23
|
+
texts.append(c)
|
|
24
|
+
ids.append(None)
|
|
25
|
+
elif isinstance(c, dict) and isinstance(c.get("text"), str):
|
|
26
|
+
texts.append(c["text"])
|
|
27
|
+
cid = c.get("id")
|
|
28
|
+
ids.append(cid if isinstance(cid, str) else None)
|
|
29
|
+
else:
|
|
30
|
+
raise ToolExecutionError("INVALID_INPUT", "Each chunk must be a string or an object with a string text.")
|
|
31
|
+
top_k = len(texts)
|
|
32
|
+
if "topK" in inp and inp["topK"] is not None:
|
|
33
|
+
tk = inp["topK"]
|
|
34
|
+
if isinstance(tk, bool) or not isinstance(tk, (int, float)) or int(tk) != tk or tk < 1:
|
|
35
|
+
raise ToolExecutionError("INVALID_INPUT", "topK must be an integer >= 1.")
|
|
36
|
+
top_k = min(int(tk), len(texts))
|
|
37
|
+
scores = bm25_scores(tokenize(query), [tokenize(t) for t in texts])
|
|
38
|
+
order = sorted(range(len(texts)), key=lambda i: (-scores[i], i))
|
|
39
|
+
ranked: List[Dict[str, Any]] = []
|
|
40
|
+
for i in order[:top_k]:
|
|
41
|
+
item: Dict[str, Any] = {"index": i}
|
|
42
|
+
if ids[i] is not None:
|
|
43
|
+
item["id"] = ids[i]
|
|
44
|
+
item["score"] = round4(scores[i])
|
|
45
|
+
item["text"] = texts[i]
|
|
46
|
+
ranked.append(item)
|
|
47
|
+
return {"ranked": ranked, "totalChunks": len(texts)}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
HANDLERS = {"text.rerank_chunks": rerank_chunks}
|