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,196 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Dict, List, Optional, Set
|
|
7
|
+
|
|
8
|
+
from .models import SecurityConfig, WarToolEnvelope, WarToolError, WarToolMeta, coerce_security_config
|
|
9
|
+
from .stores import KvStore, MemoryKvStore, MemoryTraceSink, TraceSink
|
|
10
|
+
from .runtime.pipeline import APPROVAL_HINT, ApprovalGate, with_approval_id_schema
|
|
11
|
+
from .tools import ToolExecutionError, dispatch_tool
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def load_manifest() -> Dict[str, Any]:
|
|
15
|
+
here = Path(__file__).resolve().parent
|
|
16
|
+
candidates = [
|
|
17
|
+
here / "registry-manifest.json",
|
|
18
|
+
here.parent.parent.parent.parent / "spec" / "registry-manifest.json",
|
|
19
|
+
Path.cwd() / "spec" / "registry-manifest.json",
|
|
20
|
+
]
|
|
21
|
+
for c in candidates:
|
|
22
|
+
if c.exists():
|
|
23
|
+
return json.loads(c.read_text(encoding="utf-8"))
|
|
24
|
+
raise FileNotFoundError("Could not locate spec/registry-manifest.json")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def resolve_selectors(
|
|
28
|
+
catalog: List[Dict[str, Any]],
|
|
29
|
+
presets: List[Dict[str, Any]],
|
|
30
|
+
preset: str,
|
|
31
|
+
explicit_enable: List[str],
|
|
32
|
+
) -> Set[str]:
|
|
33
|
+
preset_obj = next((p for p in presets if p["name"] == preset), None)
|
|
34
|
+
known_names = {t["name"] for t in catalog}
|
|
35
|
+
# Presets are frozen explicit tool-name lists: exact names only, never glob-expanded.
|
|
36
|
+
active: Set[str] = {n for n in (preset_obj["selectors"] if preset_obj else []) if n in known_names}
|
|
37
|
+
selectors = [s.strip() for s in explicit_enable if s and s.strip()]
|
|
38
|
+
for sel in selectors:
|
|
39
|
+
if sel == "*":
|
|
40
|
+
active.update(known_names)
|
|
41
|
+
elif sel.endswith(".*"):
|
|
42
|
+
dom = sel[:-2]
|
|
43
|
+
for t in catalog:
|
|
44
|
+
if t["domain"] == dom:
|
|
45
|
+
active.add(t["name"])
|
|
46
|
+
elif sel in known_names:
|
|
47
|
+
active.add(sel)
|
|
48
|
+
return active
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class WarTools:
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
preset: str = "none",
|
|
55
|
+
enable: Optional[List[str]] = None,
|
|
56
|
+
security: Optional[Any] = None,
|
|
57
|
+
store: Optional[KvStore] = None,
|
|
58
|
+
trace_sink: Optional[TraceSink] = None,
|
|
59
|
+
runtime: Optional[Dict[str, Any]] = None,
|
|
60
|
+
) -> None:
|
|
61
|
+
manifest = load_manifest()
|
|
62
|
+
self.catalog: List[Dict[str, Any]] = manifest["tools"]
|
|
63
|
+
self.presets: List[Dict[str, Any]] = manifest["presets"]
|
|
64
|
+
self.preset = preset
|
|
65
|
+
self.enable = list(enable or [])
|
|
66
|
+
self.security: SecurityConfig = coerce_security_config(security)
|
|
67
|
+
self.store: KvStore = store or MemoryKvStore()
|
|
68
|
+
self.trace_sink: TraceSink = trace_sink or MemoryTraceSink()
|
|
69
|
+
self.active_tools = resolve_selectors(self.catalog, self.presets, self.preset, self.enable)
|
|
70
|
+
self._gate = ApprovalGate(runtime)
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def create(
|
|
74
|
+
cls,
|
|
75
|
+
preset: str = "none",
|
|
76
|
+
enable: Optional[List[str]] = None,
|
|
77
|
+
security: Optional[Any] = None,
|
|
78
|
+
store: Optional[KvStore] = None,
|
|
79
|
+
trace_sink: Optional[TraceSink] = None,
|
|
80
|
+
runtime: Optional[Dict[str, Any]] = None,
|
|
81
|
+
) -> "WarTools":
|
|
82
|
+
return cls(preset=preset, enable=enable, security=security, store=store, trace_sink=trace_sink, runtime=runtime)
|
|
83
|
+
|
|
84
|
+
def get_active_tool_names(self) -> List[str]:
|
|
85
|
+
return sorted(self.active_tools)
|
|
86
|
+
|
|
87
|
+
def is_enabled(self, tool_name: str) -> bool:
|
|
88
|
+
return tool_name in self.active_tools
|
|
89
|
+
|
|
90
|
+
def get_tool_definitions(self) -> List[Dict[str, Any]]:
|
|
91
|
+
out: List[Dict[str, Any]] = []
|
|
92
|
+
for t in self.catalog:
|
|
93
|
+
if t["name"] not in self.active_tools:
|
|
94
|
+
continue
|
|
95
|
+
gated = t.get("requiresApproval") is True and self._gate.enabled
|
|
96
|
+
out.append(
|
|
97
|
+
{
|
|
98
|
+
"name": t["name"],
|
|
99
|
+
"description": t["summary"] + APPROVAL_HINT if gated else t["summary"],
|
|
100
|
+
"inputSchema": with_approval_id_schema(t["inputSchema"]) if gated else t["inputSchema"],
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
return out
|
|
104
|
+
|
|
105
|
+
def export_traces(self, session_id: str = "default") -> List[Dict[str, Any]]:
|
|
106
|
+
return self.trace_sink.export(session_id)
|
|
107
|
+
|
|
108
|
+
def approve(self, approval_id: str) -> bool:
|
|
109
|
+
"""Host-side approval of a pending approvalId. Never exposed as an LLM tool."""
|
|
110
|
+
return isinstance(approval_id, str) and self._gate.approve(approval_id)
|
|
111
|
+
|
|
112
|
+
def deny(self, approval_id: str) -> bool:
|
|
113
|
+
return isinstance(approval_id, str) and self._gate.deny(approval_id)
|
|
114
|
+
|
|
115
|
+
def execute(self, tool_name: str, input_data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
116
|
+
start = time.perf_counter()
|
|
117
|
+
inp = dict(input_data or {})
|
|
118
|
+
descriptor = next((t for t in self.catalog if t["name"] == tool_name), None)
|
|
119
|
+
if not descriptor:
|
|
120
|
+
env = WarToolEnvelope(
|
|
121
|
+
ok=False,
|
|
122
|
+
tool=tool_name,
|
|
123
|
+
data=None,
|
|
124
|
+
error=WarToolError(
|
|
125
|
+
code="TOOL_NOT_FOUND",
|
|
126
|
+
message=f'Tool "{tool_name}" is not registered in the WarToolsAI catalog.',
|
|
127
|
+
recoverable=False,
|
|
128
|
+
),
|
|
129
|
+
meta=WarToolMeta(duration_ms=max(1, int((time.perf_counter() - start) * 1000)), truncated=False),
|
|
130
|
+
)
|
|
131
|
+
return env.model_dump(by_alias=True)
|
|
132
|
+
|
|
133
|
+
if tool_name not in self.active_tools:
|
|
134
|
+
env = WarToolEnvelope(
|
|
135
|
+
ok=False,
|
|
136
|
+
tool=tool_name,
|
|
137
|
+
data=None,
|
|
138
|
+
error=WarToolError(
|
|
139
|
+
code="TOOL_DISABLED",
|
|
140
|
+
message=f'Tool "{tool_name}" is disabled under the active Default-Off policy.',
|
|
141
|
+
recoverable=True,
|
|
142
|
+
),
|
|
143
|
+
meta=WarToolMeta(duration_ms=max(1, int((time.perf_counter() - start) * 1000)), truncated=False),
|
|
144
|
+
)
|
|
145
|
+
return env.model_dump(by_alias=True)
|
|
146
|
+
|
|
147
|
+
try:
|
|
148
|
+
sid = inp.get("sessionId")
|
|
149
|
+
sid = sid if isinstance(sid, str) and sid else "default"
|
|
150
|
+
gate = self._gate.check(tool_name, inp, sid, descriptor.get("requiresApproval") is True)
|
|
151
|
+
if not gate["ok"]:
|
|
152
|
+
gm = gate.get("meta") or {}
|
|
153
|
+
gerr = gate["error"]
|
|
154
|
+
env = WarToolEnvelope(
|
|
155
|
+
ok=False,
|
|
156
|
+
tool=tool_name,
|
|
157
|
+
data=None,
|
|
158
|
+
error=WarToolError(code=gerr["code"], message=gerr["message"], recoverable=gerr["recoverable"]),
|
|
159
|
+
meta=WarToolMeta(
|
|
160
|
+
duration_ms=max(1, int((time.perf_counter() - start) * 1000)),
|
|
161
|
+
truncated=False,
|
|
162
|
+
approval_id=gm.get("approvalId"),
|
|
163
|
+
approval_expires_at=gm.get("approvalExpiresAt"),
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
return env.model_dump(by_alias=True)
|
|
167
|
+
inp = gate["input"]
|
|
168
|
+
data = dispatch_tool(tool_name, inp, self.security, self.store, self.trace_sink, self.catalog, self.active_tools)
|
|
169
|
+
serialized = json.dumps(data)
|
|
170
|
+
truncated = len(serialized) > self.security.max_output_chars
|
|
171
|
+
env = WarToolEnvelope(
|
|
172
|
+
ok=True,
|
|
173
|
+
tool=tool_name,
|
|
174
|
+
data=data,
|
|
175
|
+
error=None,
|
|
176
|
+
meta=WarToolMeta(duration_ms=max(1, int((time.perf_counter() - start) * 1000)), truncated=truncated),
|
|
177
|
+
)
|
|
178
|
+
return env.model_dump(by_alias=True)
|
|
179
|
+
except ToolExecutionError as err:
|
|
180
|
+
env = WarToolEnvelope(
|
|
181
|
+
ok=False,
|
|
182
|
+
tool=tool_name,
|
|
183
|
+
data=None,
|
|
184
|
+
error=WarToolError(code=err.code, message=err.message, recoverable=err.recoverable),
|
|
185
|
+
meta=WarToolMeta(duration_ms=max(1, int((time.perf_counter() - start) * 1000)), truncated=False),
|
|
186
|
+
)
|
|
187
|
+
return env.model_dump(by_alias=True)
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
env = WarToolEnvelope(
|
|
190
|
+
ok=False,
|
|
191
|
+
tool=tool_name,
|
|
192
|
+
data=None,
|
|
193
|
+
error=WarToolError(code="EXECUTION_ERROR", message=str(exc), recoverable=True),
|
|
194
|
+
meta=WarToolMeta(duration_ms=max(1, int((time.perf_counter() - start) * 1000)), truncated=False),
|
|
195
|
+
)
|
|
196
|
+
return env.model_dump(by_alias=True)
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import time
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from typing import Any, Dict, Optional
|
|
8
|
+
|
|
9
|
+
from .._lib.canonical import args_hash
|
|
10
|
+
from .policy_store import MemoryPolicyStateStore
|
|
11
|
+
|
|
12
|
+
DEFAULT_TTL_MS = 300_000
|
|
13
|
+
GRACE_MS = 60_000
|
|
14
|
+
|
|
15
|
+
# Appended to the tool description in tools/list when the gate applies (identical text in Node).
|
|
16
|
+
APPROVAL_HINT = (
|
|
17
|
+
" Requires host approval: the first call fails with APPROVAL_REQUIRED and returns meta.approvalId;"
|
|
18
|
+
" once a human approves it out of band, repeat the call with identical arguments plus approvalId (single use)."
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
APPROVAL_ID_SCHEMA = {
|
|
22
|
+
"type": "string",
|
|
23
|
+
"description": (
|
|
24
|
+
"Single-use id from meta.approvalId of an APPROVAL_REQUIRED response; "
|
|
25
|
+
"only valid after host approval and only for identical arguments."
|
|
26
|
+
),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def with_approval_id_schema(schema: Dict[str, Any]) -> Dict[str, Any]:
|
|
31
|
+
props = dict(schema.get("properties") or {})
|
|
32
|
+
props["approvalId"] = dict(APPROVAL_ID_SCHEMA)
|
|
33
|
+
return {**schema, "properties": props}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _fail(code: str, message: str, recoverable: bool = True, meta: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
|
37
|
+
return {"ok": False, "error": {"code": code, "message": message, "recoverable": recoverable}, "meta": meta or {}}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _iso(ms: int) -> str:
|
|
41
|
+
return datetime.fromtimestamp(ms / 1000, tz=timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _strip(inp: Dict[str, Any]) -> Dict[str, Any]:
|
|
45
|
+
out = dict(inp)
|
|
46
|
+
out.pop("approvalId", None)
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ApprovalGate:
|
|
51
|
+
"""Approval stage: resolve -> enabled -> approval -> dispatch.
|
|
52
|
+
|
|
53
|
+
runtime = {"approval": {"mode": "required"|"off", "ttlMs": int, "onRequest": callable}, "policyStore", "policyScope", "now"}
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(self, runtime: Optional[Dict[str, Any]] = None) -> None:
|
|
57
|
+
rt = runtime or {}
|
|
58
|
+
ap = rt.get("approval") or {}
|
|
59
|
+
mode = ap.get("mode", "required")
|
|
60
|
+
if mode not in ("required", "off"):
|
|
61
|
+
raise ValueError(f"Invalid approval mode: {mode!r}")
|
|
62
|
+
self._mode = mode
|
|
63
|
+
ttl = ap.get("ttlMs", DEFAULT_TTL_MS)
|
|
64
|
+
self._ttl = int(ttl) if isinstance(ttl, (int, float)) and not isinstance(ttl, bool) and ttl > 0 else DEFAULT_TTL_MS
|
|
65
|
+
self._on_request = ap.get("onRequest")
|
|
66
|
+
self._now = rt.get("now") or (lambda: int(time.time() * 1000))
|
|
67
|
+
self._store = rt.get("policyStore") or MemoryPolicyStateStore(self._now)
|
|
68
|
+
self._scope = rt.get("policyScope") or str(uuid.uuid4())
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def enabled(self) -> bool:
|
|
72
|
+
"""True when calls to requiresApproval tools are gated."""
|
|
73
|
+
return self._mode != "off"
|
|
74
|
+
|
|
75
|
+
@staticmethod
|
|
76
|
+
def _key(approval_id: str) -> str:
|
|
77
|
+
return f"approval:{approval_id}"
|
|
78
|
+
|
|
79
|
+
def check(self, tool: str, inp: Dict[str, Any], session_id: str, requires: bool) -> Dict[str, Any]:
|
|
80
|
+
if not requires or self._mode == "off":
|
|
81
|
+
return {"ok": True, "input": inp}
|
|
82
|
+
try:
|
|
83
|
+
h = args_hash(inp)
|
|
84
|
+
except Exception:
|
|
85
|
+
return _fail("INVALID_INPUT", "Arguments cannot be canonicalized.", False)
|
|
86
|
+
raw = inp.get("approvalId")
|
|
87
|
+
aid = raw if isinstance(raw, str) and raw else ""
|
|
88
|
+
|
|
89
|
+
if aid:
|
|
90
|
+
rec = self._store.get(self._scope, self._key(aid))
|
|
91
|
+
if not rec or rec["sessionId"] != session_id:
|
|
92
|
+
return _fail("APPROVAL_INVALID", "Approval id is unknown or already used.", False)
|
|
93
|
+
if self._now() >= rec["expiresAtMs"]:
|
|
94
|
+
self._store.delete(self._scope, self._key(aid))
|
|
95
|
+
return _fail("APPROVAL_EXPIRED", "Approval expired.", True)
|
|
96
|
+
if rec["tool"] != tool or rec["argsHash"] != h:
|
|
97
|
+
return _fail("APPROVAL_MISMATCH", "Approval does not match this tool call.", False)
|
|
98
|
+
if rec["status"] == "pending":
|
|
99
|
+
return _fail(
|
|
100
|
+
"APPROVAL_PENDING", "Approval is still pending.", True,
|
|
101
|
+
{"approvalId": aid, "approvalExpiresAt": _iso(rec["expiresAtMs"])},
|
|
102
|
+
)
|
|
103
|
+
if rec["status"] == "denied":
|
|
104
|
+
self._store.delete(self._scope, self._key(aid))
|
|
105
|
+
return _fail("APPROVAL_DENIED", "Approval was denied.", False)
|
|
106
|
+
if not self._store.take(self._scope, self._key(aid)):
|
|
107
|
+
return _fail("APPROVAL_INVALID", "Approval id is unknown or already used.", False)
|
|
108
|
+
return {"ok": True, "input": _strip(inp)}
|
|
109
|
+
|
|
110
|
+
approval_id = "apr_" + secrets.token_hex(16)
|
|
111
|
+
expires = self._now() + self._ttl
|
|
112
|
+
|
|
113
|
+
if self._on_request is not None:
|
|
114
|
+
try:
|
|
115
|
+
allowed = self._on_request(
|
|
116
|
+
{"approvalId": approval_id, "tool": tool, "argsHash": h, "expiresAt": _iso(expires)}
|
|
117
|
+
) is True
|
|
118
|
+
except Exception:
|
|
119
|
+
allowed = False
|
|
120
|
+
if not allowed:
|
|
121
|
+
return _fail("APPROVAL_DENIED", "Approval was denied.", False)
|
|
122
|
+
return {"ok": True, "input": _strip(inp)}
|
|
123
|
+
|
|
124
|
+
self._store.set(
|
|
125
|
+
self._scope, self._key(approval_id),
|
|
126
|
+
{"tool": tool, "argsHash": h, "sessionId": session_id, "status": "pending", "expiresAtMs": expires},
|
|
127
|
+
self._ttl + GRACE_MS,
|
|
128
|
+
)
|
|
129
|
+
return _fail(
|
|
130
|
+
"APPROVAL_REQUIRED", "This tool requires out-of-band approval before it can run.", True,
|
|
131
|
+
{"approvalId": approval_id, "approvalExpiresAt": _iso(expires)},
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
def approve(self, approval_id: str) -> bool:
|
|
135
|
+
return self._transition(approval_id, "approved")
|
|
136
|
+
|
|
137
|
+
def deny(self, approval_id: str) -> bool:
|
|
138
|
+
return self._transition(approval_id, "denied")
|
|
139
|
+
|
|
140
|
+
def _transition(self, approval_id: str, status: str) -> bool:
|
|
141
|
+
key = self._key(approval_id)
|
|
142
|
+
rec = self._store.get(self._scope, key)
|
|
143
|
+
if not rec or rec["status"] != "pending":
|
|
144
|
+
return False
|
|
145
|
+
now = self._now()
|
|
146
|
+
if now >= rec["expiresAtMs"]:
|
|
147
|
+
return False
|
|
148
|
+
self._store.set(self._scope, key, {**rec, "status": status}, rec["expiresAtMs"] - now + GRACE_MS)
|
|
149
|
+
return True
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from typing import Any, Callable, Dict, Optional, Tuple
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class PolicyStateStore:
|
|
9
|
+
"""Policy state (approvals, later budget/cache). Separate from KvStore: never in snapshots/checkpoints/traces."""
|
|
10
|
+
|
|
11
|
+
def get(self, scope: str, key: str) -> Any:
|
|
12
|
+
raise NotImplementedError
|
|
13
|
+
|
|
14
|
+
def set(self, scope: str, key: str, value: Any, ttl_ms: Optional[float] = None) -> None:
|
|
15
|
+
raise NotImplementedError
|
|
16
|
+
|
|
17
|
+
def delete(self, scope: str, key: str) -> bool:
|
|
18
|
+
raise NotImplementedError
|
|
19
|
+
|
|
20
|
+
def take(self, scope: str, key: str) -> Any:
|
|
21
|
+
raise NotImplementedError
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MemoryPolicyStateStore(PolicyStateStore):
|
|
25
|
+
def __init__(self, now: Optional[Callable[[], int]] = None) -> None:
|
|
26
|
+
self._now = now or (lambda: int(time.time() * 1000))
|
|
27
|
+
self._map: Dict[Tuple[str, str], Tuple[Any, Optional[int]]] = {}
|
|
28
|
+
self._lock = threading.Lock()
|
|
29
|
+
|
|
30
|
+
def _purge(self) -> None:
|
|
31
|
+
t = self._now()
|
|
32
|
+
for k in [k for k, (_, exp) in self._map.items() if exp is not None and exp <= t]:
|
|
33
|
+
del self._map[k]
|
|
34
|
+
|
|
35
|
+
def _get_locked(self, scope: str, key: str) -> Any:
|
|
36
|
+
entry = self._map.get((scope, key))
|
|
37
|
+
if entry is None:
|
|
38
|
+
return None
|
|
39
|
+
if entry[1] is not None and entry[1] <= self._now():
|
|
40
|
+
del self._map[(scope, key)]
|
|
41
|
+
return None
|
|
42
|
+
return entry[0]
|
|
43
|
+
|
|
44
|
+
def get(self, scope: str, key: str) -> Any:
|
|
45
|
+
with self._lock:
|
|
46
|
+
return self._get_locked(scope, key)
|
|
47
|
+
|
|
48
|
+
def set(self, scope: str, key: str, value: Any, ttl_ms: Optional[float] = None) -> None:
|
|
49
|
+
with self._lock:
|
|
50
|
+
self._purge()
|
|
51
|
+
exp = self._now() + int(ttl_ms) if isinstance(ttl_ms, (int, float)) and ttl_ms > 0 else None
|
|
52
|
+
self._map[(scope, key)] = (value, exp)
|
|
53
|
+
|
|
54
|
+
def delete(self, scope: str, key: str) -> bool:
|
|
55
|
+
with self._lock:
|
|
56
|
+
return self._map.pop((scope, key), None) is not None
|
|
57
|
+
|
|
58
|
+
def take(self, scope: str, key: str) -> Any:
|
|
59
|
+
with self._lock:
|
|
60
|
+
v = self._get_locked(scope, key)
|
|
61
|
+
if v is not None:
|
|
62
|
+
del self._map[(scope, key)]
|
|
63
|
+
return v
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import time
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class KvStore(ABC):
|
|
13
|
+
@abstractmethod
|
|
14
|
+
def get(self, session_id: str, namespace: str, key: str) -> Optional[Dict[str, Any]]: ...
|
|
15
|
+
|
|
16
|
+
@abstractmethod
|
|
17
|
+
def set(self, session_id: str, namespace: str, key: str, record: Dict[str, Any]) -> None: ...
|
|
18
|
+
|
|
19
|
+
@abstractmethod
|
|
20
|
+
def delete(self, session_id: str, namespace: str, key: str) -> bool: ...
|
|
21
|
+
|
|
22
|
+
@abstractmethod
|
|
23
|
+
def list(self, session_id: str, namespace: str, prefix: str = "") -> List[str]: ...
|
|
24
|
+
|
|
25
|
+
@abstractmethod
|
|
26
|
+
def list_all_session_kv(self, session_id: str) -> List[Dict[str, Any]]: ...
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def replace_session_kv(self, session_id: str, entries: List[Dict[str, Any]]) -> None: ...
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def get_scratchpad(self, session_id: str) -> Dict[str, Any]: ...
|
|
33
|
+
|
|
34
|
+
@abstractmethod
|
|
35
|
+
def save_scratchpad(self, session_id: str, state: Dict[str, Any]) -> None: ...
|
|
36
|
+
|
|
37
|
+
@abstractmethod
|
|
38
|
+
def save_checkpoint(self, session_id: str, checkpoint: Dict[str, Any]) -> None: ...
|
|
39
|
+
|
|
40
|
+
@abstractmethod
|
|
41
|
+
def load_checkpoint(self, session_id: str, name: str) -> Optional[Dict[str, Any]]: ...
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def list_checkpoints(self, session_id: str) -> List[Dict[str, Any]]: ...
|
|
45
|
+
|
|
46
|
+
@abstractmethod
|
|
47
|
+
def clear_session(self, session_id: str) -> None: ...
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _now_ms() -> int:
|
|
51
|
+
return int(time.time() * 1000)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _empty_scratchpad() -> Dict[str, Any]:
|
|
55
|
+
return {"goal": "", "steps": [], "notes": []}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class MemoryKvStore(KvStore):
|
|
59
|
+
def __init__(self) -> None:
|
|
60
|
+
self.data: Dict[str, Any] = {"kv": {}, "scratchpad": {}, "checkpoints": {}}
|
|
61
|
+
|
|
62
|
+
def get(self, session_id: str, namespace: str, key: str) -> Optional[Dict[str, Any]]:
|
|
63
|
+
rec = self.data["kv"].get(session_id, {}).get(namespace, {}).get(key)
|
|
64
|
+
if not rec:
|
|
65
|
+
return None
|
|
66
|
+
exp = rec.get("expiresAtMs")
|
|
67
|
+
if exp is not None and exp <= _now_ms():
|
|
68
|
+
del self.data["kv"][session_id][namespace][key]
|
|
69
|
+
return None
|
|
70
|
+
return rec
|
|
71
|
+
|
|
72
|
+
def set(self, session_id: str, namespace: str, key: str, record: Dict[str, Any]) -> None:
|
|
73
|
+
self.data["kv"].setdefault(session_id, {}).setdefault(namespace, {})[key] = copy.deepcopy(record)
|
|
74
|
+
|
|
75
|
+
def delete(self, session_id: str, namespace: str, key: str) -> bool:
|
|
76
|
+
ns = self.data["kv"].get(session_id, {}).get(namespace)
|
|
77
|
+
if not ns or key not in ns:
|
|
78
|
+
return False
|
|
79
|
+
del ns[key]
|
|
80
|
+
return True
|
|
81
|
+
|
|
82
|
+
def list(self, session_id: str, namespace: str, prefix: str = "") -> List[str]:
|
|
83
|
+
ns = self.data["kv"].get(session_id, {}).get(namespace)
|
|
84
|
+
if not ns:
|
|
85
|
+
return []
|
|
86
|
+
now = _now_ms()
|
|
87
|
+
out: List[str] = []
|
|
88
|
+
for k in list(ns.keys()):
|
|
89
|
+
rec = ns[k]
|
|
90
|
+
exp = rec.get("expiresAtMs")
|
|
91
|
+
if exp is not None and exp <= now:
|
|
92
|
+
del ns[k]
|
|
93
|
+
continue
|
|
94
|
+
if not prefix or k.startswith(prefix):
|
|
95
|
+
out.append(k)
|
|
96
|
+
return out
|
|
97
|
+
|
|
98
|
+
def list_all_session_kv(self, session_id: str) -> List[Dict[str, Any]]:
|
|
99
|
+
sess = self.data["kv"].get(session_id, {})
|
|
100
|
+
now = _now_ms()
|
|
101
|
+
out: List[Dict[str, Any]] = []
|
|
102
|
+
for namespace, ns in sess.items():
|
|
103
|
+
for key in list(ns.keys()):
|
|
104
|
+
entry = ns[key]
|
|
105
|
+
exp = entry.get("expiresAtMs")
|
|
106
|
+
if exp is not None and exp <= now:
|
|
107
|
+
del ns[key]
|
|
108
|
+
continue
|
|
109
|
+
out.append({"namespace": namespace, "key": key, "entry": copy.deepcopy(entry)})
|
|
110
|
+
return out
|
|
111
|
+
|
|
112
|
+
def replace_session_kv(self, session_id: str, entries: List[Dict[str, Any]]) -> None:
|
|
113
|
+
self.data["kv"][session_id] = {}
|
|
114
|
+
for item in entries:
|
|
115
|
+
self.set(session_id, item["namespace"], item["key"], item["entry"])
|
|
116
|
+
|
|
117
|
+
def get_scratchpad(self, session_id: str) -> Dict[str, Any]:
|
|
118
|
+
sp = self.data["scratchpad"].get(session_id)
|
|
119
|
+
return copy.deepcopy(sp) if sp else _empty_scratchpad()
|
|
120
|
+
|
|
121
|
+
def save_scratchpad(self, session_id: str, state: Dict[str, Any]) -> None:
|
|
122
|
+
self.data["scratchpad"][session_id] = copy.deepcopy(state)
|
|
123
|
+
|
|
124
|
+
def save_checkpoint(self, session_id: str, checkpoint: Dict[str, Any]) -> None:
|
|
125
|
+
self.data["checkpoints"].setdefault(session_id, {})[checkpoint["name"]] = copy.deepcopy(checkpoint)
|
|
126
|
+
|
|
127
|
+
def load_checkpoint(self, session_id: str, name: str) -> Optional[Dict[str, Any]]:
|
|
128
|
+
cp = self.data["checkpoints"].get(session_id, {}).get(name)
|
|
129
|
+
return copy.deepcopy(cp) if cp else None
|
|
130
|
+
|
|
131
|
+
def list_checkpoints(self, session_id: str) -> List[Dict[str, Any]]:
|
|
132
|
+
cps = self.data["checkpoints"].get(session_id, {})
|
|
133
|
+
return [{"name": c["name"], "timestamp": c["timestamp"]} for c in cps.values()]
|
|
134
|
+
|
|
135
|
+
def clear_session(self, session_id: str) -> None:
|
|
136
|
+
self.data["kv"].pop(session_id, None)
|
|
137
|
+
self.data["scratchpad"].pop(session_id, None)
|
|
138
|
+
self.data["checkpoints"].pop(session_id, None)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class JsonFileKvStore(KvStore):
|
|
142
|
+
def __init__(self, file_path: str) -> None:
|
|
143
|
+
self.file_path = Path(file_path).resolve()
|
|
144
|
+
self.mem = MemoryKvStore()
|
|
145
|
+
self._reload()
|
|
146
|
+
|
|
147
|
+
def _reload(self) -> None:
|
|
148
|
+
if not self.file_path.exists():
|
|
149
|
+
return
|
|
150
|
+
try:
|
|
151
|
+
raw = json.loads(self.file_path.read_text(encoding="utf-8"))
|
|
152
|
+
fresh = MemoryKvStore()
|
|
153
|
+
for sid, namespaces in (raw.get("kv") or {}).items():
|
|
154
|
+
entries = []
|
|
155
|
+
for ns, keys in namespaces.items():
|
|
156
|
+
for k, rec in keys.items():
|
|
157
|
+
entries.append({"namespace": ns, "key": k, "entry": rec})
|
|
158
|
+
fresh.replace_session_kv(sid, entries)
|
|
159
|
+
for sid, sp in (raw.get("scratchpad") or {}).items():
|
|
160
|
+
fresh.save_scratchpad(sid, sp)
|
|
161
|
+
for sid, cps in (raw.get("checkpoints") or {}).items():
|
|
162
|
+
for cp in cps.values():
|
|
163
|
+
fresh.save_checkpoint(sid, cp)
|
|
164
|
+
self.mem = fresh
|
|
165
|
+
except Exception:
|
|
166
|
+
self.mem = MemoryKvStore()
|
|
167
|
+
|
|
168
|
+
def _persist(self) -> None:
|
|
169
|
+
self.file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
170
|
+
self.file_path.write_text(json.dumps(self.mem.data, indent=2), encoding="utf-8")
|
|
171
|
+
|
|
172
|
+
def get(self, session_id: str, namespace: str, key: str) -> Optional[Dict[str, Any]]:
|
|
173
|
+
return self.mem.get(session_id, namespace, key)
|
|
174
|
+
|
|
175
|
+
def set(self, session_id: str, namespace: str, key: str, record: Dict[str, Any]) -> None:
|
|
176
|
+
self.mem.set(session_id, namespace, key, record)
|
|
177
|
+
self._persist()
|
|
178
|
+
|
|
179
|
+
def delete(self, session_id: str, namespace: str, key: str) -> bool:
|
|
180
|
+
ok = self.mem.delete(session_id, namespace, key)
|
|
181
|
+
if ok:
|
|
182
|
+
self._persist()
|
|
183
|
+
return ok
|
|
184
|
+
|
|
185
|
+
def list(self, session_id: str, namespace: str, prefix: str = "") -> List[str]:
|
|
186
|
+
return self.mem.list(session_id, namespace, prefix)
|
|
187
|
+
|
|
188
|
+
def list_all_session_kv(self, session_id: str) -> List[Dict[str, Any]]:
|
|
189
|
+
return self.mem.list_all_session_kv(session_id)
|
|
190
|
+
|
|
191
|
+
def replace_session_kv(self, session_id: str, entries: List[Dict[str, Any]]) -> None:
|
|
192
|
+
self.mem.replace_session_kv(session_id, entries)
|
|
193
|
+
self._persist()
|
|
194
|
+
|
|
195
|
+
def get_scratchpad(self, session_id: str) -> Dict[str, Any]:
|
|
196
|
+
return self.mem.get_scratchpad(session_id)
|
|
197
|
+
|
|
198
|
+
def save_scratchpad(self, session_id: str, state: Dict[str, Any]) -> None:
|
|
199
|
+
self.mem.save_scratchpad(session_id, state)
|
|
200
|
+
self._persist()
|
|
201
|
+
|
|
202
|
+
def save_checkpoint(self, session_id: str, checkpoint: Dict[str, Any]) -> None:
|
|
203
|
+
self.mem.save_checkpoint(session_id, checkpoint)
|
|
204
|
+
self._persist()
|
|
205
|
+
|
|
206
|
+
def load_checkpoint(self, session_id: str, name: str) -> Optional[Dict[str, Any]]:
|
|
207
|
+
return self.mem.load_checkpoint(session_id, name)
|
|
208
|
+
|
|
209
|
+
def list_checkpoints(self, session_id: str) -> List[Dict[str, Any]]:
|
|
210
|
+
return self.mem.list_checkpoints(session_id)
|
|
211
|
+
|
|
212
|
+
def clear_session(self, session_id: str) -> None:
|
|
213
|
+
self.mem.clear_session(session_id)
|
|
214
|
+
self._persist()
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class TraceSink(ABC):
|
|
218
|
+
@abstractmethod
|
|
219
|
+
def record(self, session_id: str, event: Dict[str, Any]) -> int: ...
|
|
220
|
+
|
|
221
|
+
@abstractmethod
|
|
222
|
+
def export(self, session_id: str) -> List[Dict[str, Any]]: ...
|
|
223
|
+
|
|
224
|
+
@abstractmethod
|
|
225
|
+
def clear(self, session_id: str) -> None: ...
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class MemoryTraceSink(TraceSink):
|
|
229
|
+
def __init__(self) -> None:
|
|
230
|
+
self._events: Dict[str, List[Dict[str, Any]]] = {}
|
|
231
|
+
|
|
232
|
+
def record(self, session_id: str, event: Dict[str, Any]) -> int:
|
|
233
|
+
bucket = self._events.setdefault(session_id, [])
|
|
234
|
+
bucket.append(event)
|
|
235
|
+
return len(bucket)
|
|
236
|
+
|
|
237
|
+
def export(self, session_id: str) -> List[Dict[str, Any]]:
|
|
238
|
+
return list(self._events.get(session_id, []))
|
|
239
|
+
|
|
240
|
+
def clear(self, session_id: str) -> None:
|
|
241
|
+
self._events.pop(session_id, None)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class FileTraceSink(TraceSink):
|
|
245
|
+
def __init__(
|
|
246
|
+
self,
|
|
247
|
+
file_path: str,
|
|
248
|
+
on_event: Optional[Callable[[str, Dict[str, Any]], None]] = None,
|
|
249
|
+
) -> None:
|
|
250
|
+
self.file_path = Path(file_path).resolve()
|
|
251
|
+
self._inner = MemoryTraceSink()
|
|
252
|
+
self._on_event = on_event
|
|
253
|
+
|
|
254
|
+
def record(self, session_id: str, event: Dict[str, Any]) -> int:
|
|
255
|
+
count = self._inner.record(session_id, event)
|
|
256
|
+
self.file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
257
|
+
with open(self.file_path, "a", encoding="utf-8") as fh:
|
|
258
|
+
fh.write(json.dumps({"sessionId": session_id, **event}) + os.linesep)
|
|
259
|
+
if self._on_event:
|
|
260
|
+
self._on_event(session_id, event)
|
|
261
|
+
return count
|
|
262
|
+
|
|
263
|
+
def export(self, session_id: str) -> List[Dict[str, Any]]:
|
|
264
|
+
return self._inner.export(session_id)
|
|
265
|
+
|
|
266
|
+
def clear(self, session_id: str) -> None:
|
|
267
|
+
self._inner.clear(session_id)
|