amiril 0.0.0.dev0__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.
- amiril/__init__.py +51 -0
- amiril/_adapters.py +399 -0
- amiril/_engine/__init__.py +1 -0
- amiril/_engine/engine.py +113 -0
- amiril/_engine/expr.py +653 -0
- amiril/_engine/numbers.py +111 -0
- amiril/_engine/regex.py +262 -0
- amiril/_engine/rules.py +192 -0
- amiril/_engine/sentence.py +251 -0
- amiril/_engine/timeparse.py +72 -0
- amiril/_engine/validate.py +863 -0
- amiril/_engine/values.py +273 -0
- amiril/_kernel/__init__.py +1 -0
- amiril/_kernel/bundle.py +245 -0
- amiril/_kernel/coerce.py +103 -0
- amiril/_kernel/events.py +87 -0
- amiril/_kernel/guard.py +1196 -0
- amiril/_kernel/ids.py +66 -0
- amiril/_kernel/messages.py +30 -0
- amiril/_kernel/normalise.py +165 -0
- amiril/_kernel/records.py +131 -0
- amiril/_kernel/store.py +661 -0
- amiril/_runtime.py +617 -0
- amiril/adk.py +577 -0
- amiril/control/__init__.py +25 -0
- amiril/control/_delivery.py +567 -0
- amiril/control/_disk.py +418 -0
- amiril/control/_holds.py +252 -0
- amiril/control/_jsonschema.py +265 -0
- amiril/control/_pathc.py +85 -0
- amiril/control/_records.py +293 -0
- amiril/control/_redact.py +79 -0
- amiril/control/_transport.py +184 -0
- amiril/control/_wire.py +73 -0
- amiril/control/client.py +1313 -0
- amiril/control/config.py +204 -0
- amiril/control/schemas/bundle.response.schema.json +22 -0
- amiril/control/schemas/common.schema.json +593 -0
- amiril/control/schemas/decisions.request.schema.json +558 -0
- amiril/control/schemas/decisions.response.schema.json +23 -0
- amiril/control/schemas/error.response.schema.json +54 -0
- amiril/control/schemas/heartbeat.request.schema.json +305 -0
- amiril/control/schemas/heartbeat.response.schema.json +34 -0
- amiril/control/schemas/hold-create.request.schema.json +138 -0
- amiril/control/schemas/hold.response.schema.json +226 -0
- amiril/control/schemas/installation-register.request.schema.json +492 -0
- amiril/control/schemas/installation-register.response.schema.json +85 -0
- amiril/core.py +89 -0
- amiril/docs/README.md +14 -0
- amiril/docs/durability/langgraph.md +292 -0
- amiril/docs/frameworks/adk.md +141 -0
- amiril/docs/frameworks/langgraph.md +154 -0
- amiril/docs/frameworks/no-framework.md +238 -0
- amiril/docs/frameworks/write-an-adapter.md +203 -0
- amiril/durable.py +342 -0
- amiril/langgraph.py +746 -0
- amiril/plain.py +454 -0
- amiril/py.typed +0 -0
- amiril/seams.py +357 -0
- amiril/testing.py +21 -0
- amiril-0.0.0.dev0.dist-info/METADATA +114 -0
- amiril-0.0.0.dev0.dist-info/RECORD +64 -0
- amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
- amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
amiril/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Amiril SDK: check an agent's tool calls against rules before they run.
|
|
2
|
+
|
|
3
|
+
import amiril
|
|
4
|
+
amiril.init(rules_file="rules.json")
|
|
5
|
+
amiril.instrument(app) # an ADK App or Runner, a LangGraph graph
|
|
6
|
+
agent = amiril.plain.Agent("name") # or no framework at all
|
|
7
|
+
|
|
8
|
+
`amiril.init()` and `amiril.instrument()` are the entry points. The core
|
|
9
|
+
(`amiril.core`) is the rule engine and the kernel every framework adapter
|
|
10
|
+
builds on; `amiril.seams` names the interfaces between the kernel, the
|
|
11
|
+
adapters and the control-plane client. The adapters are `amiril.adk` and
|
|
12
|
+
`amiril.langgraph` (extras `amiril[adk]`, `amiril[langgraph]`), imported only
|
|
13
|
+
when used, so importing `amiril` never imports a framework. `amiril.plain`
|
|
14
|
+
is the same checks for an agent written by hand.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import importlib
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
__version__ = "0.0.0.dev0"
|
|
23
|
+
|
|
24
|
+
from ._adapters import AmirilInstallError, HookOrderError, NotInitialisedError # noqa: E402
|
|
25
|
+
from ._runtime import Amiril, init, instrument # noqa: E402
|
|
26
|
+
from .core import CallRecord, Decision, DocumentError, Guard, Outcome, RunContext # noqa: E402
|
|
27
|
+
|
|
28
|
+
_ADAPTERS = ("adk", "langgraph", "plain")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def __getattr__(name: str) -> Any:
|
|
32
|
+
if name in _ADAPTERS:
|
|
33
|
+
return importlib.import_module(f"{__name__}.{name}")
|
|
34
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"Amiril",
|
|
39
|
+
"AmirilInstallError",
|
|
40
|
+
"CallRecord",
|
|
41
|
+
"Decision",
|
|
42
|
+
"DocumentError",
|
|
43
|
+
"Guard",
|
|
44
|
+
"HookOrderError",
|
|
45
|
+
"NotInitialisedError",
|
|
46
|
+
"Outcome",
|
|
47
|
+
"RunContext",
|
|
48
|
+
"__version__",
|
|
49
|
+
"init",
|
|
50
|
+
"instrument",
|
|
51
|
+
]
|
amiril/_adapters.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
"""What every framework adapter shares: the parent-call link for nested runs
|
|
2
|
+
(spec/kernel.md 11), fault reporting that never raises (kernel.md 10), the
|
|
3
|
+
stored results a re-executed call is answered with (kernel.md 5), argument
|
|
4
|
+
coercion (kernel.md 12.1) and the coverage report entries (protocol.md 4.3).
|
|
5
|
+
|
|
6
|
+
Nothing here imports a framework.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextvars
|
|
12
|
+
import threading
|
|
13
|
+
from collections import OrderedDict
|
|
14
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from importlib import metadata
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .core import Guard, Outcome, RunContext, coerce_args
|
|
20
|
+
|
|
21
|
+
# ---------------------------------------------------------------- errors
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AmirilInstallError(RuntimeError):
|
|
25
|
+
"""An adapter could not be installed the way the spec requires."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class HookOrderError(AmirilInstallError):
|
|
29
|
+
"""Another hook would see a tool call before Amiril's (build plan, install-order check).
|
|
30
|
+
|
|
31
|
+
Raised, never warned: a hook ahead of Amiril's can answer or rewrite a call
|
|
32
|
+
Amiril never sees."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class NotInitialisedError(RuntimeError):
|
|
36
|
+
"""An adapter was asked for its guard before `amiril.init()` ran."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# ---------------------------------------------------------------- parent link (kernel.md 11)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class ParentCall:
|
|
44
|
+
"""The call whose tool is running in this context: an agent started inside
|
|
45
|
+
it is a nested run of `ctx.root_run_id` with this call as its parent."""
|
|
46
|
+
|
|
47
|
+
ctx: RunContext
|
|
48
|
+
call_id: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_PARENT: contextvars.ContextVar[ParentCall | None] = contextvars.ContextVar("amiril_parent_call", default=None)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def current_parent() -> ParentCall | None:
|
|
55
|
+
return _PARENT.get()
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def enter_call(ctx: RunContext, call_id: str) -> contextvars.Token:
|
|
59
|
+
return _PARENT.set(ParentCall(ctx, call_id))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def exit_call(token: contextvars.Token | None) -> None:
|
|
63
|
+
if token is None:
|
|
64
|
+
return
|
|
65
|
+
try:
|
|
66
|
+
_PARENT.reset(token)
|
|
67
|
+
except (ValueError, RuntimeError): # created in another context or already used: nothing to undo here
|
|
68
|
+
pass
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def nested_context(ctx: RunContext, parent: ParentCall | None, *, session_from_parent: bool) -> RunContext:
|
|
72
|
+
"""`ctx` placed under `parent` when one is active: the outer root run and the
|
|
73
|
+
outer call as parent (kernel.md 11). `session_from_parent` carries the outer
|
|
74
|
+
session, for frameworks that give an inner agent a session of its own."""
|
|
75
|
+
if parent is None:
|
|
76
|
+
return ctx
|
|
77
|
+
session_id = parent.ctx.session_id if session_from_parent else ctx.session_id
|
|
78
|
+
return RunContext(
|
|
79
|
+
run_id=ctx.run_id,
|
|
80
|
+
agent_id=ctx.agent_id,
|
|
81
|
+
session_id=session_id,
|
|
82
|
+
agent_version=ctx.agent_version,
|
|
83
|
+
env=ctx.env,
|
|
84
|
+
now=ctx.now,
|
|
85
|
+
root_run_id=parent.ctx.root_run_id,
|
|
86
|
+
parent_call_id=parent.call_id,
|
|
87
|
+
root_agent_id=parent.ctx.root_agent_id,
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# ---------------------------------------------------------------- settings an adapter reads from the handle
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class AdapterSettings:
|
|
96
|
+
"""Run-context values the adapters fill in that the framework does not
|
|
97
|
+
carry: the agent version, customer `env` tags, and the clock (kernel.md
|
|
98
|
+
2.2)."""
|
|
99
|
+
|
|
100
|
+
agent_version: str | None = None
|
|
101
|
+
env: dict[str, Any] = field(default_factory=dict)
|
|
102
|
+
clock: Callable[[], float] | None = None
|
|
103
|
+
|
|
104
|
+
def agent_id(self, framework_name: str | None) -> str:
|
|
105
|
+
"""The kernel's `agent_id`: the framework's own name, never renamed;
|
|
106
|
+
`agent` for an agent with no name (kernel.md 2.2)."""
|
|
107
|
+
return framework_name or "agent"
|
|
108
|
+
|
|
109
|
+
def now(self) -> float | None:
|
|
110
|
+
return self.clock() if self.clock is not None else None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
# ---------------------------------------------------------------- the handle an adapter answers to
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class HandleRef:
|
|
117
|
+
"""The handle an adapter uses. An adapter built without an explicit handle
|
|
118
|
+
follows the active one, so after a second `amiril.init()` it answers with
|
|
119
|
+
the new rules and sinks instead of the retired handle's."""
|
|
120
|
+
|
|
121
|
+
def __init__(self, handle: Any = None) -> None:
|
|
122
|
+
from ._runtime import active_handle
|
|
123
|
+
|
|
124
|
+
self._follow = handle is None
|
|
125
|
+
self._handle = handle if handle is not None else active_handle()
|
|
126
|
+
|
|
127
|
+
def get(self) -> Any:
|
|
128
|
+
if self._follow or self._handle.closed:
|
|
129
|
+
from . import _runtime
|
|
130
|
+
|
|
131
|
+
current = _runtime._active
|
|
132
|
+
if current is not None and current is not self._handle:
|
|
133
|
+
self._handle = current
|
|
134
|
+
return self._handle
|
|
135
|
+
|
|
136
|
+
def rebind(self, handle: Any) -> None:
|
|
137
|
+
"""`instrument()` under another handle: answer to that one from now on."""
|
|
138
|
+
self._handle = handle
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
class BoundedMap:
|
|
142
|
+
"""A dict that keeps at most `limit` entries, dropping the oldest and
|
|
143
|
+
telling `on_evict`: per-run adapter state for runs that never end (a
|
|
144
|
+
cancelled invocation fires no run-end callback) cannot pile up."""
|
|
145
|
+
|
|
146
|
+
def __init__(self, limit: int, on_evict: Callable[[Any, Any], None] | None = None) -> None:
|
|
147
|
+
self._limit = limit
|
|
148
|
+
self._on_evict = on_evict
|
|
149
|
+
self._lock = threading.Lock()
|
|
150
|
+
self._items: OrderedDict = OrderedDict()
|
|
151
|
+
|
|
152
|
+
def __setitem__(self, key: Any, value: Any) -> None:
|
|
153
|
+
evicted = []
|
|
154
|
+
with self._lock:
|
|
155
|
+
self._items[key] = value
|
|
156
|
+
self._items.move_to_end(key)
|
|
157
|
+
while len(self._items) > self._limit:
|
|
158
|
+
evicted.append(self._items.popitem(last=False))
|
|
159
|
+
if self._on_evict is not None:
|
|
160
|
+
for k, v in evicted:
|
|
161
|
+
self._on_evict(k, v)
|
|
162
|
+
|
|
163
|
+
def get(self, key: Any, default: Any = None) -> Any:
|
|
164
|
+
with self._lock:
|
|
165
|
+
return self._items.get(key, default)
|
|
166
|
+
|
|
167
|
+
def pop(self, key: Any, default: Any = None) -> Any:
|
|
168
|
+
with self._lock:
|
|
169
|
+
return self._items.pop(key, default)
|
|
170
|
+
|
|
171
|
+
def items(self) -> list:
|
|
172
|
+
with self._lock:
|
|
173
|
+
return list(self._items.items())
|
|
174
|
+
|
|
175
|
+
def __len__(self) -> int:
|
|
176
|
+
return len(self._items)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
# ---------------------------------------------------------------- private seams and version gates
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
@dataclass(frozen=True)
|
|
183
|
+
class PrivateSeam:
|
|
184
|
+
"""A framework internal an adapter relies on (build plan, adapters: any
|
|
185
|
+
private seam is a tested, version-gated shim with a named owner and a
|
|
186
|
+
review date). It is used only while `distribution` is inside
|
|
187
|
+
[`low`, `high`), the releases the framework conformance ran against;
|
|
188
|
+
outside, the adapter does without it and its coverage report says so."""
|
|
189
|
+
|
|
190
|
+
name: str
|
|
191
|
+
distribution: str
|
|
192
|
+
low: str
|
|
193
|
+
high: str
|
|
194
|
+
owner: str
|
|
195
|
+
review_by: str
|
|
196
|
+
without: str
|
|
197
|
+
|
|
198
|
+
def version(self) -> str | None:
|
|
199
|
+
return package_version(self.distribution)
|
|
200
|
+
|
|
201
|
+
def enabled(self) -> bool:
|
|
202
|
+
return version_in(self.version(), self.low, self.high)
|
|
203
|
+
|
|
204
|
+
def uncovered(self, agent: str | None) -> dict:
|
|
205
|
+
return uncovered_entry(
|
|
206
|
+
"agent", agent or "agent", None, "private_seam_off",
|
|
207
|
+
f"{self.distribution} {self.version() or 'unknown'} is outside the tested {self.low} to below "
|
|
208
|
+
f"{self.high}, so {self.name} is not used: {self.without}")
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
SEAM_OWNER = "Amiril SDK maintainers"
|
|
212
|
+
SEAM_REVIEW_BY = "2027-01-31"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _parts(v: str) -> tuple[int, ...]:
|
|
216
|
+
out = []
|
|
217
|
+
for piece in v.split(".")[:3]:
|
|
218
|
+
digits = "".join(ch for ch in piece if ch.isdigit())
|
|
219
|
+
if not digits:
|
|
220
|
+
break
|
|
221
|
+
out.append(int(digits))
|
|
222
|
+
if not piece.isdigit():
|
|
223
|
+
break
|
|
224
|
+
return tuple(out)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def version_in(version: str | None, low: str, high: str) -> bool:
|
|
228
|
+
if not version:
|
|
229
|
+
return False
|
|
230
|
+
v = _parts(version)
|
|
231
|
+
return _parts(low) <= v < _parts(high)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def framework_range_entry(agent: str | None, distribution: str, low: str, high: str) -> dict | None:
|
|
235
|
+
"""A coverage entry when the installed framework is outside the tested range."""
|
|
236
|
+
version = package_version(distribution)
|
|
237
|
+
if version_in(version, low, high):
|
|
238
|
+
return None
|
|
239
|
+
return uncovered_entry(
|
|
240
|
+
"agent", agent or "agent", None, "untested_framework_version",
|
|
241
|
+
f"{distribution} {version or 'unknown'} is outside the releases this adapter was tested against "
|
|
242
|
+
f"({low} to below {high}); its hooks are used as documented but not verified there.")
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# ---------------------------------------------------------------- faults (kernel.md 10)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def report_fault(guard: Guard, exc: BaseException, ctx: RunContext | None, call_id: str | None,
|
|
249
|
+
tool_name: str | None, *, phase: str = "pre", agent_id: str = "unknown") -> None:
|
|
250
|
+
"""Write the adapter's own failure as a fault line. Never raises."""
|
|
251
|
+
try:
|
|
252
|
+
if ctx is None:
|
|
253
|
+
ctx = RunContext(run_id="unknown", agent_id=agent_id)
|
|
254
|
+
guard.record_fault(ctx, exc, call_id=call_id, tool_name=tool_name, phase=phase)
|
|
255
|
+
except Exception: # noqa: BLE001 - the fault path must not raise into the framework either
|
|
256
|
+
pass
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
# ---------------------------------------------------------------- the answer for a call that did not run (kernel.md 13)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def blocked_result(outcome: Outcome) -> dict:
|
|
263
|
+
"""What the model sees instead of the tool's result: the kernel's message,
|
|
264
|
+
recognisable in events and spans by `blocked_by`."""
|
|
265
|
+
return {"status": "blocked", "blocked_by": "amiril", "message": outcome.message}
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
# ---------------------------------------------------------------- re-execution answers (kernel.md 5)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class ResultCache:
|
|
272
|
+
"""The framework's own result for each call that completed, so a re-fired
|
|
273
|
+
call id (a framework re-running a node after a resume) is answered without
|
|
274
|
+
running the tool again. Bounded; entries go with their run."""
|
|
275
|
+
|
|
276
|
+
def __init__(self, limit: int = 10_000) -> None:
|
|
277
|
+
self._limit = limit
|
|
278
|
+
self._lock = threading.Lock()
|
|
279
|
+
self._items: OrderedDict[str, tuple[str, Any]] = OrderedDict()
|
|
280
|
+
|
|
281
|
+
def put(self, root_run_id: str, call_id: str, result: Any) -> None:
|
|
282
|
+
with self._lock:
|
|
283
|
+
self._items[call_id] = (root_run_id, result)
|
|
284
|
+
self._items.move_to_end(call_id)
|
|
285
|
+
while len(self._items) > self._limit:
|
|
286
|
+
self._items.popitem(last=False)
|
|
287
|
+
|
|
288
|
+
def get(self, call_id: str) -> tuple[bool, Any]:
|
|
289
|
+
with self._lock:
|
|
290
|
+
item = self._items.get(call_id)
|
|
291
|
+
return (False, None) if item is None else (True, item[1])
|
|
292
|
+
|
|
293
|
+
def end_run(self, root_run_id: str) -> None:
|
|
294
|
+
with self._lock:
|
|
295
|
+
for key in [k for k, (root, _) in self._items.items() if root == root_run_id]:
|
|
296
|
+
del self._items[key]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
class AttemptTracker:
|
|
300
|
+
"""The attempt last handled per call id: a firing that comes back with the
|
|
301
|
+
same attempt is a re-execution, a higher one a retry (kernel.md 5)."""
|
|
302
|
+
|
|
303
|
+
def __init__(self, limit: int = 100_000) -> None:
|
|
304
|
+
self._limit = limit
|
|
305
|
+
self._lock = threading.Lock()
|
|
306
|
+
self._seen: OrderedDict[str, int] = OrderedDict()
|
|
307
|
+
|
|
308
|
+
def observe(self, call_id: str, attempt: int) -> bool:
|
|
309
|
+
"""Record `attempt` for `call_id`; True when it was already seen (re-execution)."""
|
|
310
|
+
with self._lock:
|
|
311
|
+
again = self._seen.get(call_id) == attempt
|
|
312
|
+
self._seen[call_id] = attempt
|
|
313
|
+
self._seen.move_to_end(call_id)
|
|
314
|
+
while len(self._seen) > self._limit:
|
|
315
|
+
self._seen.popitem(last=False)
|
|
316
|
+
return again
|
|
317
|
+
|
|
318
|
+
def forget(self, call_ids: Iterable[str]) -> None:
|
|
319
|
+
"""Drop what is kept for these call ids, at the end of their run."""
|
|
320
|
+
with self._lock:
|
|
321
|
+
for call_id in call_ids:
|
|
322
|
+
self._seen.pop(call_id, None)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
# ---------------------------------------------------------------- coercion (kernel.md 12.1)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def coerce(raw: Mapping[str, Any] | None, schema: dict | None, injected: Iterable[str] = ()) -> tuple[Any, dict]:
|
|
329
|
+
"""The kernel's `coerce_args` with only the meta keys that say something.
|
|
330
|
+
A failure here hands the kernel the raw arguments, which records the fault."""
|
|
331
|
+
try:
|
|
332
|
+
args, meta = coerce_args(dict(raw or {}), schema, injected=injected)
|
|
333
|
+
except Exception as exc: # noqa: BLE001 - kernel.md 10: the kernel records it on the call
|
|
334
|
+
return dict(raw or {}), {"coerce_fault": f"{type(exc).__name__}: {exc}"}
|
|
335
|
+
return args, {k: v for k, v in meta.items() if v}
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# ---------------------------------------------------------------- coverage entries (protocol.md 4.3)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def tool_entry(name: str, agent: str | None, description: Any, schema: dict | None,
|
|
342
|
+
declared_id: str | None = None) -> dict:
|
|
343
|
+
entry: dict[str, Any] = {
|
|
344
|
+
"name": name,
|
|
345
|
+
"declared_id": declared_id,
|
|
346
|
+
"agent": agent,
|
|
347
|
+
"description": description if isinstance(description, str) and description else None,
|
|
348
|
+
"schema": schema,
|
|
349
|
+
}
|
|
350
|
+
if schema is None:
|
|
351
|
+
entry["schema_omitted"] = "unavailable"
|
|
352
|
+
return entry
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def coverage_name(name: Any) -> str | None:
|
|
356
|
+
"""A framework agent's own name as the coverage report carries it, or None
|
|
357
|
+
for an agent with no name (protocol.md 4.3); the client normalises it."""
|
|
358
|
+
return name if isinstance(name, str) and name else None
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def uncovered_entry(kind: str, name: str, agent: str | None, reason: str, text: str) -> dict:
|
|
362
|
+
return {"kind": kind, "name": name, "agent": agent, "reason": reason, "text": text}
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def package_version(*names: str) -> str | None:
|
|
366
|
+
for name in names:
|
|
367
|
+
try:
|
|
368
|
+
return metadata.version(name)
|
|
369
|
+
except metadata.PackageNotFoundError:
|
|
370
|
+
continue
|
|
371
|
+
return None
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
__all__ = [
|
|
375
|
+
"AdapterSettings",
|
|
376
|
+
"BoundedMap",
|
|
377
|
+
"HandleRef",
|
|
378
|
+
"PrivateSeam",
|
|
379
|
+
"SEAM_OWNER",
|
|
380
|
+
"SEAM_REVIEW_BY",
|
|
381
|
+
"framework_range_entry",
|
|
382
|
+
"version_in",
|
|
383
|
+
"AmirilInstallError",
|
|
384
|
+
"AttemptTracker",
|
|
385
|
+
"HookOrderError",
|
|
386
|
+
"NotInitialisedError",
|
|
387
|
+
"ParentCall",
|
|
388
|
+
"ResultCache",
|
|
389
|
+
"blocked_result",
|
|
390
|
+
"coerce",
|
|
391
|
+
"current_parent",
|
|
392
|
+
"enter_call",
|
|
393
|
+
"exit_call",
|
|
394
|
+
"nested_context",
|
|
395
|
+
"package_version",
|
|
396
|
+
"report_fault",
|
|
397
|
+
"tool_entry",
|
|
398
|
+
"uncovered_entry",
|
|
399
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The rule engine (spec/edoc.md). Private; import from `amiril.core`."""
|
amiril/_engine/engine.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""The rule engine: a loaded document and its evaluator (spec/edoc.md).
|
|
2
|
+
|
|
3
|
+
`Engine.load` validates and swaps a document in one assignment; a document
|
|
4
|
+
that fails validation raises `DocumentError` and leaves the previous one
|
|
5
|
+
live. `Engine.evaluate` returns one decision per rule that targets the
|
|
6
|
+
snapshot, in document order.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import copy
|
|
12
|
+
import json
|
|
13
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from .expr import Env, Evaluator, HistoryIndex
|
|
18
|
+
from .rules import CompiledRule, Decision, StandIn, decide
|
|
19
|
+
from .validate import SCHEMA_ID, DocumentError, validate_document
|
|
20
|
+
|
|
21
|
+
EMPTY_DOCUMENT: dict = {"schema": SCHEMA_ID, "ruleset_version": "empty", "rules": []}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LoadedDocument:
|
|
25
|
+
"""A validated document with its compiled rules and evaluator. Immutable
|
|
26
|
+
once built, so a swap is one reference assignment."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, doc: dict, predicates: Mapping[str, Callable[..., Any]],
|
|
29
|
+
stand_ins: Sequence[StandIn] = ()) -> None:
|
|
30
|
+
problems = validate_document(doc, set(predicates))
|
|
31
|
+
if problems:
|
|
32
|
+
raise DocumentError(problems)
|
|
33
|
+
doc = copy.deepcopy(doc) # the caller keeps its object; the live rules are ours alone
|
|
34
|
+
self.doc = doc
|
|
35
|
+
self.ruleset_version: str = doc["ruleset_version"]
|
|
36
|
+
self.sets: dict[str, list] = dict(doc.get("sets") or {})
|
|
37
|
+
aliases = doc.get("aliases") or {}
|
|
38
|
+
self.tool_aliases: dict[str, str] = dict(aliases.get("tools") or {})
|
|
39
|
+
self.arg_aliases: dict[str, str] = dict(aliases.get("args") or {})
|
|
40
|
+
self.correlation_names: frozenset[str] = frozenset(self.arg_aliases.values())
|
|
41
|
+
groups = dict(doc.get("groups") or {})
|
|
42
|
+
self.rules: list[CompiledRule] = [CompiledRule(r, groups) for r in doc["rules"]]
|
|
43
|
+
self.rules += [CompiledRule.for_stand_in(s) for s in stand_ins] # after the document's rules (kernel.md 8.4)
|
|
44
|
+
self.rules_by_id: dict[str, CompiledRule] = {r.id: r for r in self.rules}
|
|
45
|
+
self.evaluator = Evaluator(doc, predicates)
|
|
46
|
+
|
|
47
|
+
def targeting(self, phase: str, agent_id: Any, tool_id: Any) -> list[CompiledRule]:
|
|
48
|
+
"""Rules that target a call by phase, agent and tool alone (edoc.md 7.1)."""
|
|
49
|
+
return [r for r in self.rules if r.mode != "off" and r.targets(phase, agent_id, tool_id)]
|
|
50
|
+
|
|
51
|
+
def evaluate(self, call: Any, history: list, context: dict, phase: str,
|
|
52
|
+
run_floor: int | None = None) -> list[Decision]:
|
|
53
|
+
"""One decision per rule that targets the snapshot, in document order.
|
|
54
|
+
`run_floor` is the kernel's arrival index where the live run started
|
|
55
|
+
(kernel.md 6.1); None means every record of the root run is run history."""
|
|
56
|
+
agent_id = _field(call, "agent_id")
|
|
57
|
+
tool_id = _field(call, "tool_id")
|
|
58
|
+
index = HistoryIndex(call, history, run_floor)
|
|
59
|
+
out: list[Decision] = []
|
|
60
|
+
for rule in self.rules:
|
|
61
|
+
if rule.mode == "off" or not rule.targets(phase, agent_id, tool_id):
|
|
62
|
+
continue
|
|
63
|
+
env = Env(call, context, index, rule.scope, self.sets)
|
|
64
|
+
d = decide(rule, self.evaluator, env, self.ruleset_version)
|
|
65
|
+
if d is not None:
|
|
66
|
+
out.append(d)
|
|
67
|
+
return out
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _field(rec: Any, name: str) -> Any:
|
|
71
|
+
return rec.get(name) if type(rec) is dict else getattr(rec, name, None)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Engine:
|
|
75
|
+
"""Holds the live document. Thread-safe by construction: `load` replaces one
|
|
76
|
+
reference and readers take the reference once per evaluation."""
|
|
77
|
+
|
|
78
|
+
def __init__(self, predicates: Mapping[str, Callable[..., Any]] | None = None,
|
|
79
|
+
document: dict | None = None) -> None:
|
|
80
|
+
self.predicates: dict[str, Callable[..., Any]] = dict(predicates or {})
|
|
81
|
+
self._loaded = LoadedDocument(document if document is not None else EMPTY_DOCUMENT, self.predicates)
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def loaded(self) -> LoadedDocument:
|
|
85
|
+
return self._loaded
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def ruleset_version(self) -> str:
|
|
89
|
+
return self._loaded.ruleset_version
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def document(self) -> dict:
|
|
93
|
+
return self._loaded.doc
|
|
94
|
+
|
|
95
|
+
def load(self, document: dict, stand_ins: Sequence[StandIn] = ()) -> LoadedDocument:
|
|
96
|
+
"""Validate, then swap in one assignment (kernel.md 8.4). `stand_ins`
|
|
97
|
+
are the fail-closed rules of a bundle this core could not read."""
|
|
98
|
+
loaded = LoadedDocument(document, self.predicates, stand_ins)
|
|
99
|
+
self._loaded = loaded
|
|
100
|
+
return loaded
|
|
101
|
+
|
|
102
|
+
def register_predicate(self, name: str, fn: Callable[..., Any]) -> None:
|
|
103
|
+
"""Register a host function before loading a document that names it."""
|
|
104
|
+
self.predicates[name] = fn
|
|
105
|
+
|
|
106
|
+
def evaluate(self, call: Any, history: list, context: dict, phase: str,
|
|
107
|
+
run_floor: int | None = None) -> list[Decision]:
|
|
108
|
+
return self._loaded.evaluate(call, history, context, phase, run_floor)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def load_document_file(path: str | Path) -> dict:
|
|
112
|
+
with open(path, encoding="utf-8") as fh:
|
|
113
|
+
return json.load(fh)
|