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,57 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Any, Dict
|
|
8
|
+
|
|
9
|
+
from .._lib.errors import ToolExecutionError
|
|
10
|
+
from .context import Handler, ToolContext
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def encoding_base64(ctx: ToolContext) -> Any:
|
|
14
|
+
inp = ctx.input
|
|
15
|
+
raw = str(inp.get("input") or "")
|
|
16
|
+
action = str(inp.get("action") or "encode")
|
|
17
|
+
url_safe = bool(inp.get("urlSafe"))
|
|
18
|
+
if action == "encode":
|
|
19
|
+
b = raw.encode("utf-8")
|
|
20
|
+
encoded = base64.urlsafe_b64encode(b).decode("ascii").rstrip("=") if url_safe else base64.b64encode(b).decode("ascii")
|
|
21
|
+
return {"output": encoded}
|
|
22
|
+
if action == "decode":
|
|
23
|
+
if url_safe:
|
|
24
|
+
padded = raw + "=" * (-len(raw) % 4)
|
|
25
|
+
return {"output": base64.urlsafe_b64decode(padded).decode("utf-8")}
|
|
26
|
+
return {"output": base64.b64decode(raw).decode("utf-8")}
|
|
27
|
+
raise ToolExecutionError("INVALID_INPUT", "action must be encode or decode.")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def encoding_jwt_inspect(ctx: ToolContext) -> Any:
|
|
31
|
+
inp = ctx.input
|
|
32
|
+
parts = str(inp.get("token") or "").split(".")
|
|
33
|
+
if len(parts) < 2:
|
|
34
|
+
raise ToolExecutionError("INVALID_JWT", "Token must contain header and payload.")
|
|
35
|
+
try:
|
|
36
|
+
def _b64url_json(seg: str) -> Any:
|
|
37
|
+
padded = seg + "=" * (-len(seg) % 4)
|
|
38
|
+
return json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
|
|
39
|
+
|
|
40
|
+
header = _b64url_json(parts[0])
|
|
41
|
+
payload = _b64url_json(parts[1])
|
|
42
|
+
exp = payload.get("exp")
|
|
43
|
+
exp_ms = exp * 1000 if isinstance(exp, (int, float)) else None
|
|
44
|
+
return {
|
|
45
|
+
"header": header,
|
|
46
|
+
"payload": payload,
|
|
47
|
+
"isExpired": int(time.time() * 1000) >= exp_ms if exp_ms is not None else False,
|
|
48
|
+
"expiresAt": datetime.fromtimestamp(exp_ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z") if exp_ms is not None else None,
|
|
49
|
+
}
|
|
50
|
+
except Exception:
|
|
51
|
+
raise ToolExecutionError("INVALID_JWT", "Could not decode JWT header or payload.")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
HANDLERS: Dict[str, Handler] = {
|
|
55
|
+
"encoding.base64": encoding_base64,
|
|
56
|
+
"encoding.jwt_inspect": encoding_jwt_inspect,
|
|
57
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from .._lib.errors import ToolExecutionError
|
|
8
|
+
from .._lib.sandbox import resolve_sandbox_path
|
|
9
|
+
from .context import Handler, ToolContext
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def fs_list_dir(ctx: ToolContext) -> Any:
|
|
13
|
+
inp, security = ctx.input, ctx.security
|
|
14
|
+
_, target, rel = resolve_sandbox_path(security.fs_root, str(inp.get("relativePath") or "."))
|
|
15
|
+
recursive = bool(inp.get("recursive"))
|
|
16
|
+
max_depth = max(1, min(int(inp.get("maxDepth") or 2), 5))
|
|
17
|
+
entries: List[Dict[str, Any]] = []
|
|
18
|
+
|
|
19
|
+
def walk(d: str, prefix: str, depth: int) -> None:
|
|
20
|
+
for item in sorted(os.scandir(d), key=lambda e: e.name):
|
|
21
|
+
display = f"{prefix}/{item.name}" if prefix else item.name
|
|
22
|
+
if item.is_dir(follow_symlinks=False):
|
|
23
|
+
entries.append({"name": display, "type": "dir", "sizeBytes": 0})
|
|
24
|
+
if recursive and depth < max_depth:
|
|
25
|
+
walk(item.path, display, depth + 1)
|
|
26
|
+
elif item.is_file(follow_symlinks=False):
|
|
27
|
+
entries.append({"name": display, "type": "file", "sizeBytes": item.stat().st_size})
|
|
28
|
+
|
|
29
|
+
walk(target, "", 1)
|
|
30
|
+
return {"path": rel, "entries": entries}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def fs_read_file(ctx: ToolContext) -> Any:
|
|
34
|
+
inp, security = ctx.input, ctx.security
|
|
35
|
+
rel_inp = str(inp.get("relativePath") or "")
|
|
36
|
+
if not rel_inp:
|
|
37
|
+
raise ToolExecutionError("INVALID_INPUT", "relativePath is required.")
|
|
38
|
+
_, target, rel = resolve_sandbox_path(security.fs_root, rel_inp)
|
|
39
|
+
if not os.path.isfile(target):
|
|
40
|
+
raise ToolExecutionError("FILE_NOT_FOUND", f'File "{rel}" does not exist in sandbox.')
|
|
41
|
+
content = Path(target).read_text(encoding="utf-8")
|
|
42
|
+
all_lines = content.split("\n")
|
|
43
|
+
start_line = max(1, int(inp.get("startLine") or 1))
|
|
44
|
+
end_line = min(len(all_lines), int(inp.get("endLine") or len(all_lines)))
|
|
45
|
+
max_chars = min(int(inp.get("maxChars") or security.max_output_chars or 16000), 32000)
|
|
46
|
+
sliced = "\n".join(all_lines[start_line - 1 : end_line])
|
|
47
|
+
truncated = len(sliced) > max_chars or end_line < len(all_lines)
|
|
48
|
+
return {"path": rel, "content": sliced[:max_chars], "totalLines": len(all_lines), "truncated": truncated}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def fs_write_file(ctx: ToolContext) -> Any:
|
|
52
|
+
inp, security = ctx.input, ctx.security
|
|
53
|
+
rel_inp = str(inp.get("relativePath") or "")
|
|
54
|
+
content = inp.get("content")
|
|
55
|
+
if not isinstance(content, str):
|
|
56
|
+
raise ToolExecutionError("INVALID_INPUT", "content is required and must be a string.")
|
|
57
|
+
if not rel_inp:
|
|
58
|
+
raise ToolExecutionError("INVALID_INPUT", "relativePath is required.")
|
|
59
|
+
_, target, rel = resolve_sandbox_path(security.fs_root, rel_inp, for_write=True)
|
|
60
|
+
overwrite = inp.get("overwrite") is not False
|
|
61
|
+
existed = os.path.exists(target)
|
|
62
|
+
if existed and not overwrite:
|
|
63
|
+
raise ToolExecutionError("FILE_EXISTS", f'File "{rel}" already exists.')
|
|
64
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
65
|
+
Path(target).write_text(content, encoding="utf-8")
|
|
66
|
+
return {"path": rel, "bytesWritten": len(content.encode("utf-8")), "created": not existed}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def fs_search_text(ctx: ToolContext) -> Any:
|
|
70
|
+
inp, security = ctx.input, ctx.security
|
|
71
|
+
query = str(inp.get("query") or "")
|
|
72
|
+
if not query:
|
|
73
|
+
raise ToolExecutionError("INVALID_INPUT", "query is required.")
|
|
74
|
+
real_root, target, _ = resolve_sandbox_path(security.fs_root, str(inp.get("relativePath") or "."))
|
|
75
|
+
max_results = min(int(inp.get("maxResults") or 50), 200)
|
|
76
|
+
matches: List[Dict[str, Any]] = []
|
|
77
|
+
|
|
78
|
+
def scan(d: str) -> None:
|
|
79
|
+
for item in sorted(os.scandir(d), key=lambda e: e.name):
|
|
80
|
+
if len(matches) >= max_results:
|
|
81
|
+
return
|
|
82
|
+
if item.is_dir(follow_symlinks=False):
|
|
83
|
+
scan(item.path)
|
|
84
|
+
elif item.is_file(follow_symlinks=False):
|
|
85
|
+
try:
|
|
86
|
+
txt = Path(item.path).read_text(encoding="utf-8")
|
|
87
|
+
except Exception:
|
|
88
|
+
continue
|
|
89
|
+
for idx, line in enumerate(txt.split("\n"), start=1):
|
|
90
|
+
if len(matches) >= max_results:
|
|
91
|
+
return
|
|
92
|
+
if query in line:
|
|
93
|
+
matches.append(
|
|
94
|
+
{
|
|
95
|
+
"file": os.path.relpath(item.path, real_root).replace("\\", "/"),
|
|
96
|
+
"line": idx,
|
|
97
|
+
"snippet": line.strip()[:160],
|
|
98
|
+
}
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
scan(target)
|
|
102
|
+
return {"matches": matches, "totalMatches": len(matches)}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
HANDLERS: Dict[str, Handler] = {
|
|
106
|
+
"fs.list_dir": fs_list_dir,
|
|
107
|
+
"fs.read_file": fs_read_file,
|
|
108
|
+
"fs.write_file": fs_write_file,
|
|
109
|
+
"fs.search_text": fs_search_text,
|
|
110
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any, Dict, List
|
|
6
|
+
|
|
7
|
+
from .._lib.errors import ToolExecutionError
|
|
8
|
+
from .context import Handler, ToolContext
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_json_schema_simple(data: Any, schema: Dict[str, Any], cur_path: str = "$") -> List[Dict[str, str]]:
|
|
12
|
+
errors: List[Dict[str, str]] = []
|
|
13
|
+
expected_type = schema.get("type")
|
|
14
|
+
if expected_type:
|
|
15
|
+
if data is None:
|
|
16
|
+
actual = "null"
|
|
17
|
+
elif isinstance(data, bool):
|
|
18
|
+
actual = "boolean"
|
|
19
|
+
elif isinstance(data, (int, float)):
|
|
20
|
+
actual = "number"
|
|
21
|
+
elif isinstance(data, str):
|
|
22
|
+
actual = "string"
|
|
23
|
+
elif isinstance(data, list):
|
|
24
|
+
actual = "array"
|
|
25
|
+
elif isinstance(data, dict):
|
|
26
|
+
actual = "object"
|
|
27
|
+
else:
|
|
28
|
+
actual = type(data).__name__
|
|
29
|
+
expected = "number" if expected_type == "integer" else expected_type
|
|
30
|
+
if actual != expected:
|
|
31
|
+
errors.append({"path": cur_path, "message": f"Expected {expected_type}, got {actual}"})
|
|
32
|
+
return errors
|
|
33
|
+
|
|
34
|
+
if isinstance(data, (int, float)) and not isinstance(data, bool):
|
|
35
|
+
if "minimum" in schema and data < schema["minimum"]:
|
|
36
|
+
errors.append({"path": cur_path, "message": f"Value {data} is less than minimum {schema['minimum']}"})
|
|
37
|
+
if "maximum" in schema and data > schema["maximum"]:
|
|
38
|
+
errors.append({"path": cur_path, "message": f"Value {data} exceeds maximum {schema['maximum']}"})
|
|
39
|
+
if isinstance(data, str):
|
|
40
|
+
if "minLength" in schema and len(data) < schema["minLength"]:
|
|
41
|
+
errors.append({"path": cur_path, "message": f"Length must be >= {schema['minLength']}"})
|
|
42
|
+
if "maxLength" in schema and len(data) > schema["maxLength"]:
|
|
43
|
+
errors.append({"path": cur_path, "message": f"Length must be <= {schema['maxLength']}"})
|
|
44
|
+
if isinstance(schema.get("enum"), list) and data not in schema["enum"]:
|
|
45
|
+
errors.append({"path": cur_path, "message": f"Value must be one of: {', '.join(map(str, schema['enum']))}"})
|
|
46
|
+
if isinstance(data, dict):
|
|
47
|
+
for req_key in schema.get("required") or []:
|
|
48
|
+
if req_key not in data or data[req_key] is None:
|
|
49
|
+
errors.append({"path": f"{cur_path}.{req_key}", "message": "Required field is missing"})
|
|
50
|
+
for k, prop_schema in (schema.get("properties") or {}).items():
|
|
51
|
+
if k in data and isinstance(prop_schema, dict):
|
|
52
|
+
errors.extend(validate_json_schema_simple(data[k], prop_schema, f"{cur_path}.{k}"))
|
|
53
|
+
return errors
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def query_json_path(root: Any, expr: str) -> List[Any]:
|
|
57
|
+
clean = re.sub(r"^\$\.?", "", expr.strip())
|
|
58
|
+
if not clean:
|
|
59
|
+
return [root]
|
|
60
|
+
tokens = [t for t in re.sub(r"\[(\d+|\*)\]", r".\1", clean).split(".") if t]
|
|
61
|
+
current: List[Any] = [root]
|
|
62
|
+
for tok in tokens:
|
|
63
|
+
nxt: List[Any] = []
|
|
64
|
+
for item in current:
|
|
65
|
+
if tok == "*":
|
|
66
|
+
if isinstance(item, list):
|
|
67
|
+
nxt.extend(item)
|
|
68
|
+
elif isinstance(item, dict):
|
|
69
|
+
nxt.extend(item.values())
|
|
70
|
+
elif tok.isdigit() and isinstance(item, list):
|
|
71
|
+
idx = int(tok)
|
|
72
|
+
if idx < len(item):
|
|
73
|
+
nxt.append(item[idx])
|
|
74
|
+
elif isinstance(item, dict) and tok in item:
|
|
75
|
+
nxt.append(item[tok])
|
|
76
|
+
current = nxt
|
|
77
|
+
return current
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def json_query(ctx: ToolContext) -> Any:
|
|
81
|
+
inp = ctx.input
|
|
82
|
+
parsed = inp.get("data")
|
|
83
|
+
if isinstance(parsed, str):
|
|
84
|
+
try:
|
|
85
|
+
parsed = json.loads(parsed)
|
|
86
|
+
except Exception:
|
|
87
|
+
raise ToolExecutionError("INVALID_INPUT", "data string is not valid JSON.")
|
|
88
|
+
matches = query_json_path(parsed, str(inp.get("expression") or "$"))
|
|
89
|
+
return {"matches": matches, "count": len(matches)}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _escape_newlines_in_strings(raw: str) -> str:
|
|
93
|
+
out: List[str] = []
|
|
94
|
+
in_str = False
|
|
95
|
+
esc = False
|
|
96
|
+
for ch in raw:
|
|
97
|
+
if in_str:
|
|
98
|
+
if esc:
|
|
99
|
+
esc = False
|
|
100
|
+
out.append(ch)
|
|
101
|
+
elif ch == "\\":
|
|
102
|
+
esc = True
|
|
103
|
+
out.append(ch)
|
|
104
|
+
elif ch == '"':
|
|
105
|
+
in_str = False
|
|
106
|
+
out.append(ch)
|
|
107
|
+
elif ch == "\n":
|
|
108
|
+
out.append("\\n")
|
|
109
|
+
elif ch == "\r":
|
|
110
|
+
out.append("\\r")
|
|
111
|
+
else:
|
|
112
|
+
out.append(ch)
|
|
113
|
+
else:
|
|
114
|
+
if ch == '"':
|
|
115
|
+
in_str = True
|
|
116
|
+
out.append(ch)
|
|
117
|
+
return "".join(out)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def json_repair(ctx: ToolContext) -> Any:
|
|
121
|
+
inp = ctx.input
|
|
122
|
+
raw = str(inp.get("rawText") or "")
|
|
123
|
+
fixes: List[str] = []
|
|
124
|
+
fenced = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", raw, re.IGNORECASE)
|
|
125
|
+
if fenced:
|
|
126
|
+
raw = fenced.group(1)
|
|
127
|
+
fixes.append("stripped_markdown_fence")
|
|
128
|
+
raw = raw.strip()
|
|
129
|
+
if re.search(r",\s*[}\]]", raw):
|
|
130
|
+
raw = re.sub(r",\s*([}\]])", r"\1", raw)
|
|
131
|
+
fixes.append("removed_trailing_commas")
|
|
132
|
+
if "'" in raw and '"' not in raw:
|
|
133
|
+
raw = raw.replace("'", '"')
|
|
134
|
+
fixes.append("normalized_single_quotes")
|
|
135
|
+
escaped = _escape_newlines_in_strings(raw)
|
|
136
|
+
if escaped != raw:
|
|
137
|
+
raw = escaped
|
|
138
|
+
fixes.append("escaped_newlines_in_strings")
|
|
139
|
+
open_braces = raw.count("{") - raw.count("}")
|
|
140
|
+
if open_braces > 0:
|
|
141
|
+
raw += "}" * open_braces
|
|
142
|
+
fixes.append("closed_missing_braces")
|
|
143
|
+
open_brackets = raw.count("[") - raw.count("]")
|
|
144
|
+
if open_brackets > 0:
|
|
145
|
+
raw += "]" * open_brackets
|
|
146
|
+
fixes.append("closed_missing_brackets")
|
|
147
|
+
try:
|
|
148
|
+
return {"repaired": True, "data": json.loads(raw), "fixesApplied": fixes, "repairsApplied": list(fixes)}
|
|
149
|
+
except Exception:
|
|
150
|
+
raise ToolExecutionError("REPAIR_FAILED", "Could not repair malformed JSON input.")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def json_validate(ctx: ToolContext) -> Any:
|
|
154
|
+
inp = ctx.input
|
|
155
|
+
schema = inp.get("schema")
|
|
156
|
+
if not isinstance(schema, dict):
|
|
157
|
+
raise ToolExecutionError("INVALID_INPUT", "schema object is required.")
|
|
158
|
+
errs = validate_json_schema_simple(inp.get("data"), schema)
|
|
159
|
+
return {"valid": len(errs) == 0, "errors": errs}
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def json_diff(ctx: ToolContext) -> Any:
|
|
163
|
+
inp = ctx.input
|
|
164
|
+
if not isinstance(inp.get("before"), dict) or not isinstance(inp.get("after"), dict):
|
|
165
|
+
raise ToolExecutionError("INVALID_INPUT", "before and after must be JSON objects.")
|
|
166
|
+
before = inp["before"]
|
|
167
|
+
after = inp["after"]
|
|
168
|
+
added: Dict[str, Any] = {}
|
|
169
|
+
removed: Dict[str, Any] = {}
|
|
170
|
+
modified: Dict[str, Any] = {}
|
|
171
|
+
for k, v in after.items():
|
|
172
|
+
if k not in before:
|
|
173
|
+
added[k] = v
|
|
174
|
+
elif json.dumps(before[k], sort_keys=True) != json.dumps(v, sort_keys=True):
|
|
175
|
+
modified[k] = {"before": before[k], "after": v}
|
|
176
|
+
for k, v in before.items():
|
|
177
|
+
if k not in after:
|
|
178
|
+
removed[k] = v
|
|
179
|
+
return {"hasChanges": bool(added or removed or modified), "added": added, "removed": removed, "modified": modified}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def json_flatten(ctx: ToolContext) -> Any:
|
|
183
|
+
inp = ctx.input
|
|
184
|
+
data = inp.get("data")
|
|
185
|
+
if not isinstance(data, dict):
|
|
186
|
+
raise ToolExecutionError("INVALID_INPUT", "data must be a JSON object.")
|
|
187
|
+
mode = "unflatten" if inp.get("mode") == "unflatten" else "flatten"
|
|
188
|
+
sep = str(inp.get("separator") or ".")
|
|
189
|
+
if mode == "flatten":
|
|
190
|
+
out: Dict[str, Any] = {}
|
|
191
|
+
|
|
192
|
+
def walk(obj: Dict[str, Any], prefix: str = "") -> None:
|
|
193
|
+
for k, v in obj.items():
|
|
194
|
+
key = f"{prefix}{sep}{k}" if prefix else k
|
|
195
|
+
if isinstance(v, dict):
|
|
196
|
+
walk(v, key)
|
|
197
|
+
else:
|
|
198
|
+
out[key] = v
|
|
199
|
+
|
|
200
|
+
walk(data)
|
|
201
|
+
return {"result": out}
|
|
202
|
+
out_unflat: Dict[str, Any] = {}
|
|
203
|
+
for flat_k, val in data.items():
|
|
204
|
+
parts = flat_k.split(sep)
|
|
205
|
+
cur = out_unflat
|
|
206
|
+
for p in parts[:-1]:
|
|
207
|
+
if p not in cur or not isinstance(cur[p], dict):
|
|
208
|
+
cur[p] = {}
|
|
209
|
+
cur = cur[p]
|
|
210
|
+
cur[parts[-1]] = val
|
|
211
|
+
return {"result": out_unflat}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
HANDLERS: Dict[str, Handler] = {
|
|
215
|
+
"json.query": json_query,
|
|
216
|
+
"json.repair": json_repair,
|
|
217
|
+
"json.validate": json_validate,
|
|
218
|
+
"json.diff": json_diff,
|
|
219
|
+
"json.flatten": json_flatten,
|
|
220
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from datetime import datetime, timezone
|
|
5
|
+
from typing import Any, Dict
|
|
6
|
+
|
|
7
|
+
from .._lib.common import clean_number
|
|
8
|
+
from .._lib.errors import ToolExecutionError
|
|
9
|
+
from .context import Handler, ToolContext
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def kv_set(ctx: ToolContext) -> Any:
|
|
13
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
14
|
+
key = str(inp.get("key") or "")
|
|
15
|
+
if not key:
|
|
16
|
+
raise ToolExecutionError("INVALID_INPUT", "key is required.")
|
|
17
|
+
namespace = str(inp.get("namespace") or "default")
|
|
18
|
+
ttl = inp.get("ttlSeconds")
|
|
19
|
+
expires_at_ms = int(time.time() * 1000 + float(ttl) * 1000) if isinstance(ttl, (int, float)) and ttl > 0 else None
|
|
20
|
+
store.set(
|
|
21
|
+
session_id,
|
|
22
|
+
namespace,
|
|
23
|
+
key,
|
|
24
|
+
{
|
|
25
|
+
"value": inp.get("value"),
|
|
26
|
+
"updatedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
27
|
+
"expiresAtMs": expires_at_ms,
|
|
28
|
+
},
|
|
29
|
+
)
|
|
30
|
+
expires_iso = (
|
|
31
|
+
datetime.fromtimestamp(expires_at_ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
|
|
32
|
+
if expires_at_ms is not None
|
|
33
|
+
else None
|
|
34
|
+
)
|
|
35
|
+
return {"key": key, "namespace": namespace, "expiresAt": expires_iso, "stored": True}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def kv_get(ctx: ToolContext) -> Any:
|
|
39
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
40
|
+
key = str(inp.get("key") or "")
|
|
41
|
+
if not key:
|
|
42
|
+
raise ToolExecutionError("INVALID_INPUT", "key is required.")
|
|
43
|
+
namespace = str(inp.get("namespace") or "default")
|
|
44
|
+
entry = store.get(session_id, namespace, key)
|
|
45
|
+
if not entry:
|
|
46
|
+
return {"found": False, "key": key, "value": None, "updatedAt": None}
|
|
47
|
+
return {"found": True, "key": key, "value": entry["value"], "updatedAt": entry["updatedAt"]}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def kv_delete(ctx: ToolContext) -> Any:
|
|
51
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
52
|
+
key = str(inp.get("key") or "")
|
|
53
|
+
if not key:
|
|
54
|
+
raise ToolExecutionError("INVALID_INPUT", "key is required.")
|
|
55
|
+
namespace = str(inp.get("namespace") or "default")
|
|
56
|
+
return {"deleted": store.delete(session_id, namespace, key), "key": key}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def kv_list(ctx: ToolContext) -> Any:
|
|
60
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
61
|
+
if (
|
|
62
|
+
(inp.get("limit") is not None and (isinstance(inp["limit"], bool) or not isinstance(inp["limit"], (int, float))))
|
|
63
|
+
or (inp.get("namespace") is not None and not isinstance(inp["namespace"], str))
|
|
64
|
+
or (inp.get("prefix") is not None and not isinstance(inp["prefix"], str))
|
|
65
|
+
):
|
|
66
|
+
raise ToolExecutionError("INVALID_INPUT", "namespace and prefix must be strings and limit a number.")
|
|
67
|
+
namespace = str(inp.get("namespace") or "default")
|
|
68
|
+
prefix = str(inp.get("prefix") or "")
|
|
69
|
+
limit = max(1, min(int(inp.get("limit") or 100), 500))
|
|
70
|
+
keys = store.list(session_id, namespace, prefix)[:limit]
|
|
71
|
+
return {"keys": keys, "count": len(keys)}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def kv_incr(ctx: ToolContext) -> Any:
|
|
75
|
+
inp, store, session_id = ctx.input, ctx.store, ctx.session_id
|
|
76
|
+
key = str(inp.get("key") or "")
|
|
77
|
+
if not key:
|
|
78
|
+
raise ToolExecutionError("INVALID_INPUT", "key is required.")
|
|
79
|
+
delta = inp.get("delta") if isinstance(inp.get("delta"), (int, float)) else 1
|
|
80
|
+
namespace = str(inp.get("namespace") or "default")
|
|
81
|
+
existing = store.get(session_id, namespace, key)
|
|
82
|
+
current_num = existing["value"] if existing and isinstance(existing.get("value"), (int, float)) and not isinstance(existing.get("value"), bool) else 0
|
|
83
|
+
next_num = clean_number(current_num + delta)
|
|
84
|
+
store.set(
|
|
85
|
+
session_id,
|
|
86
|
+
namespace,
|
|
87
|
+
key,
|
|
88
|
+
{
|
|
89
|
+
"value": next_num,
|
|
90
|
+
"updatedAt": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
|
91
|
+
"expiresAtMs": existing.get("expiresAtMs") if existing else None,
|
|
92
|
+
},
|
|
93
|
+
)
|
|
94
|
+
return {"key": key, "value": next_num}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
HANDLERS: Dict[str, Handler] = {
|
|
98
|
+
"kv.set": kv_set,
|
|
99
|
+
"kv.get": kv_get,
|
|
100
|
+
"kv.delete": kv_delete,
|
|
101
|
+
"kv.list": kv_list,
|
|
102
|
+
"kv.incr": kv_incr,
|
|
103
|
+
}
|