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
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Number semantics pinned by spec/edoc.md: formatting (10.4), compensated
|
|
2
|
+
summation (8.7), min and max (8.8), non-finite JSON spelling (8.11) and the
|
|
3
|
+
JSON text of objects in sentences (10.3)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def fmt_number(x: float) -> str:
|
|
13
|
+
"""Section 10.4: integral below 10^16 as digits, else 15 significant digits."""
|
|
14
|
+
f = float(x)
|
|
15
|
+
if f != f:
|
|
16
|
+
return "nan"
|
|
17
|
+
if f in (math.inf, -math.inf):
|
|
18
|
+
return "inf" if f > 0 else "-inf"
|
|
19
|
+
if f == 0.0:
|
|
20
|
+
return "0"
|
|
21
|
+
if f.is_integer() and abs(f) < 1e16:
|
|
22
|
+
return str(int(f))
|
|
23
|
+
# CPython's %g formatting is correctly rounded from the exact binary value.
|
|
24
|
+
return format(f, ".15g")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def neumaier_sum(values: list) -> float:
|
|
28
|
+
"""Section 8.7: Neumaier's compensated summation, as CPython 3.12's sum()."""
|
|
29
|
+
s = 0.0 + values[0]
|
|
30
|
+
c = 0.0
|
|
31
|
+
for x in values[1:]:
|
|
32
|
+
t = s + x
|
|
33
|
+
if abs(s) >= abs(x):
|
|
34
|
+
c += (s - t) + x
|
|
35
|
+
else:
|
|
36
|
+
c += (x - t) + s
|
|
37
|
+
s = t
|
|
38
|
+
if c != 0.0 and math.isfinite(c):
|
|
39
|
+
return s + c
|
|
40
|
+
return s
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def extreme_min(values: list) -> float:
|
|
44
|
+
cur = values[0]
|
|
45
|
+
for v in values[1:]:
|
|
46
|
+
if v < cur:
|
|
47
|
+
cur = v
|
|
48
|
+
return cur
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def extreme_max(values: list) -> float:
|
|
52
|
+
cur = values[0]
|
|
53
|
+
for v in values[1:]:
|
|
54
|
+
if v > cur:
|
|
55
|
+
cur = v
|
|
56
|
+
return cur
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def json_text(v: Any) -> str:
|
|
60
|
+
"""Section 10.3: JSON text with sorted keys, `, ` and `: ` separators,
|
|
61
|
+
non-ASCII unescaped, numbers as 10.4 renders them."""
|
|
62
|
+
t = type(v)
|
|
63
|
+
if t is dict:
|
|
64
|
+
return "{" + ", ".join(json.dumps(k, ensure_ascii=False) + ": " + json_text(v[k]) for k in sorted(v)) + "}"
|
|
65
|
+
if t is list:
|
|
66
|
+
return "[" + ", ".join(json_text(x) for x in v) + "]"
|
|
67
|
+
if t is float or t is int:
|
|
68
|
+
return fmt_number(v)
|
|
69
|
+
if t is bool:
|
|
70
|
+
return "true" if v else "false"
|
|
71
|
+
if v is None:
|
|
72
|
+
return "null"
|
|
73
|
+
if t is str:
|
|
74
|
+
return json.dumps(v, ensure_ascii=False)
|
|
75
|
+
return json.dumps(str(v), ensure_ascii=False)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def encode_nonfinite(v: Any) -> Any:
|
|
79
|
+
"""Section 8.11: non-finite numbers become `{"$float": ...}` objects in
|
|
80
|
+
every JSON form (evidence, decision lines, decision records)."""
|
|
81
|
+
t = type(v)
|
|
82
|
+
if t is float:
|
|
83
|
+
if v != v:
|
|
84
|
+
return {"$float": "nan"}
|
|
85
|
+
if v == math.inf:
|
|
86
|
+
return {"$float": "inf"}
|
|
87
|
+
if v == -math.inf:
|
|
88
|
+
return {"$float": "-inf"}
|
|
89
|
+
return v
|
|
90
|
+
if t is list:
|
|
91
|
+
return [encode_nonfinite(x) for x in v]
|
|
92
|
+
if t is dict:
|
|
93
|
+
return {k: encode_nonfinite(x) for k, x in v.items()}
|
|
94
|
+
return v
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def decode_nonfinite(v: Any) -> Any:
|
|
98
|
+
"""The inverse of `encode_nonfinite`, for reading fixtures and lines."""
|
|
99
|
+
t = type(v)
|
|
100
|
+
if t is dict:
|
|
101
|
+
if len(v) == 1 and "$float" in v:
|
|
102
|
+
return {"nan": math.nan, "inf": math.inf, "-inf": -math.inf}[v["$float"]]
|
|
103
|
+
return {k: decode_nonfinite(x) for k, x in v.items()}
|
|
104
|
+
if t is list:
|
|
105
|
+
return [decode_nonfinite(x) for x in v]
|
|
106
|
+
return v
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def dumps_line(obj: Any) -> str:
|
|
110
|
+
"""One JSON object on one line as spec/decision-line.md section 3 serialises it."""
|
|
111
|
+
return json.dumps(encode_nonfinite(obj), sort_keys=True, ensure_ascii=False, separators=(", ", ": "))
|
amiril/_engine/regex.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""The portable regular-expression subset (spec/edoc.md 8.9).
|
|
2
|
+
|
|
3
|
+
`check_pattern` parses a pattern against the grammar of 8.9 and reports
|
|
4
|
+
`regex_outside_subset` (does not parse) or `regex_invalid` (parses but a
|
|
5
|
+
quantifier has n > m or a class range has low > high). `compile_pattern`
|
|
6
|
+
rewrites an accepted pattern for Python's `re`: `$` becomes `\\Z` (Python's
|
|
7
|
+
`$` also matches before a final newline), everything else keeps its
|
|
8
|
+
meaning under `re.ASCII`, and matching uses `fullmatch`.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
_HEX = frozenset("0123456789abcdefABCDEF")
|
|
16
|
+
_LITERAL_FORBIDDEN = frozenset("\\^$.|?*+()[]{}")
|
|
17
|
+
_ESCAPE_PUNCT = frozenset("^$\\.*+?()[]{}|/-")
|
|
18
|
+
_CLASS_ESCAPES = frozenset("dDwWsS")
|
|
19
|
+
_CONTROL_ESCAPES = frozenset("nrtfv")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _Outside(Exception):
|
|
23
|
+
pass
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class _Invalid(Exception):
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class _Parser:
|
|
31
|
+
def __init__(self, text: str) -> None:
|
|
32
|
+
self.s = text
|
|
33
|
+
self.i = 0
|
|
34
|
+
self.n = len(text)
|
|
35
|
+
|
|
36
|
+
def peek(self, k: int = 0) -> str:
|
|
37
|
+
j = self.i + k
|
|
38
|
+
return self.s[j] if j < self.n else ""
|
|
39
|
+
|
|
40
|
+
def take(self) -> str:
|
|
41
|
+
c = self.peek()
|
|
42
|
+
self.i += 1
|
|
43
|
+
return c
|
|
44
|
+
|
|
45
|
+
# pattern := alternative ("|" alternative)*
|
|
46
|
+
def pattern(self, depth: int) -> None:
|
|
47
|
+
self.alternative(depth)
|
|
48
|
+
while self.peek() == "|":
|
|
49
|
+
self.take()
|
|
50
|
+
self.alternative(depth)
|
|
51
|
+
|
|
52
|
+
# alternative := term*
|
|
53
|
+
def alternative(self, depth: int) -> None:
|
|
54
|
+
while self.i < self.n:
|
|
55
|
+
c = self.peek()
|
|
56
|
+
if c == "|":
|
|
57
|
+
return
|
|
58
|
+
if c == ")":
|
|
59
|
+
if depth == 0:
|
|
60
|
+
raise _Outside("unbalanced )")
|
|
61
|
+
return
|
|
62
|
+
self.term(depth)
|
|
63
|
+
|
|
64
|
+
def term(self, depth: int) -> None:
|
|
65
|
+
c = self.peek()
|
|
66
|
+
if c in ("^", "$"):
|
|
67
|
+
self.take()
|
|
68
|
+
return
|
|
69
|
+
if c == "\\" and self.peek(1) in ("b", "B"):
|
|
70
|
+
self.take()
|
|
71
|
+
self.take()
|
|
72
|
+
return
|
|
73
|
+
if c == "(" and self.peek(1) == "?" and self.peek(2) in ("=", "!"):
|
|
74
|
+
self.i += 3
|
|
75
|
+
self.pattern(depth + 1)
|
|
76
|
+
if self.take() != ")":
|
|
77
|
+
raise _Outside("unbalanced (")
|
|
78
|
+
return
|
|
79
|
+
self.atom(depth)
|
|
80
|
+
self.quantifier()
|
|
81
|
+
|
|
82
|
+
def quantifier(self) -> None:
|
|
83
|
+
c = self.peek()
|
|
84
|
+
if c in ("*", "+", "?"):
|
|
85
|
+
self.take()
|
|
86
|
+
elif c == "{":
|
|
87
|
+
if not self.brace():
|
|
88
|
+
raise _Outside("bad brace quantifier")
|
|
89
|
+
else:
|
|
90
|
+
return
|
|
91
|
+
if self.peek() == "?":
|
|
92
|
+
self.take()
|
|
93
|
+
if self.peek() in ("*", "+", "?", "{"):
|
|
94
|
+
if self.peek() == "{" and not self._looks_like_brace():
|
|
95
|
+
raise _Outside("{ is not a literal")
|
|
96
|
+
raise _Outside("two quantifiers in a row")
|
|
97
|
+
|
|
98
|
+
def _looks_like_brace(self) -> bool:
|
|
99
|
+
return re.match(r"\{[0-9]+(,[0-9]*)?\}", self.s[self.i:]) is not None
|
|
100
|
+
|
|
101
|
+
def brace(self) -> bool:
|
|
102
|
+
m = re.match(r"\{([0-9]+)(?:,([0-9]*))?\}", self.s[self.i:])
|
|
103
|
+
if m is None:
|
|
104
|
+
return False
|
|
105
|
+
self.i += m.end()
|
|
106
|
+
lo = int(m.group(1))
|
|
107
|
+
if m.group(2) not in (None, ""):
|
|
108
|
+
hi = int(m.group(2))
|
|
109
|
+
if lo > hi:
|
|
110
|
+
raise _Invalid("quantifier with n > m")
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
def atom(self, depth: int) -> None:
|
|
114
|
+
c = self.take()
|
|
115
|
+
if c == "":
|
|
116
|
+
raise _Outside("unexpected end")
|
|
117
|
+
if c == "(":
|
|
118
|
+
if self.peek() == "?":
|
|
119
|
+
if self.peek(1) == ":":
|
|
120
|
+
self.i += 2
|
|
121
|
+
else:
|
|
122
|
+
raise _Outside("group construct outside the subset")
|
|
123
|
+
self.pattern(depth + 1)
|
|
124
|
+
if self.take() != ")":
|
|
125
|
+
raise _Outside("unbalanced (")
|
|
126
|
+
return
|
|
127
|
+
if c == "[":
|
|
128
|
+
self.char_class()
|
|
129
|
+
return
|
|
130
|
+
if c == "\\":
|
|
131
|
+
self.escape(in_class=False)
|
|
132
|
+
return
|
|
133
|
+
if c == ".":
|
|
134
|
+
return
|
|
135
|
+
if c in _LITERAL_FORBIDDEN:
|
|
136
|
+
raise _Outside(f"{c!r} is not a literal here")
|
|
137
|
+
|
|
138
|
+
def escape(self, in_class: bool) -> int | None:
|
|
139
|
+
"""Consume the body of an escape; return its code point when it names one."""
|
|
140
|
+
c = self.take()
|
|
141
|
+
if c == "":
|
|
142
|
+
raise _Outside("trailing backslash")
|
|
143
|
+
if c in _CLASS_ESCAPES:
|
|
144
|
+
return None
|
|
145
|
+
if c in _ESCAPE_PUNCT:
|
|
146
|
+
return ord(c)
|
|
147
|
+
if c in _CONTROL_ESCAPES:
|
|
148
|
+
return ord({"n": "\n", "r": "\r", "t": "\t", "f": "\f", "v": "\v"}[c])
|
|
149
|
+
if c == "x":
|
|
150
|
+
h = self.s[self.i:self.i + 2]
|
|
151
|
+
if len(h) == 2 and all(ch in _HEX for ch in h):
|
|
152
|
+
self.i += 2
|
|
153
|
+
return int(h, 16)
|
|
154
|
+
raise _Outside("bad \\x escape")
|
|
155
|
+
if c == "u":
|
|
156
|
+
h = self.s[self.i:self.i + 4]
|
|
157
|
+
if len(h) == 4 and all(ch in _HEX for ch in h):
|
|
158
|
+
self.i += 4
|
|
159
|
+
return int(h, 16)
|
|
160
|
+
raise _Outside("bad \\u escape")
|
|
161
|
+
raise _Outside(f"escape \\{c} is outside the subset")
|
|
162
|
+
|
|
163
|
+
def class_atom(self) -> int | None:
|
|
164
|
+
"""One class atom; None for a class escape (\\d and friends)."""
|
|
165
|
+
c = self.take()
|
|
166
|
+
if c == "":
|
|
167
|
+
raise _Outside("unterminated class")
|
|
168
|
+
if c == "\\":
|
|
169
|
+
return self.escape(in_class=True)
|
|
170
|
+
if c in ("[", "]"):
|
|
171
|
+
raise _Outside(f"{c!r} inside a class")
|
|
172
|
+
return ord(c)
|
|
173
|
+
|
|
174
|
+
def char_class(self) -> None:
|
|
175
|
+
if self.peek() == "^":
|
|
176
|
+
self.take()
|
|
177
|
+
items = 0
|
|
178
|
+
while True:
|
|
179
|
+
c = self.peek()
|
|
180
|
+
if c == "":
|
|
181
|
+
raise _Outside("unterminated class")
|
|
182
|
+
if c == "]":
|
|
183
|
+
self.take()
|
|
184
|
+
break
|
|
185
|
+
low = self.class_atom()
|
|
186
|
+
items += 1
|
|
187
|
+
if self.peek() == "-" and self.peek(1) not in ("]", ""):
|
|
188
|
+
if low is None:
|
|
189
|
+
# `\d-x`: a class escape cannot start a range; `-` is a literal.
|
|
190
|
+
continue
|
|
191
|
+
self.take()
|
|
192
|
+
high = self.class_atom()
|
|
193
|
+
if high is None:
|
|
194
|
+
raise _Outside("range ending in a class escape")
|
|
195
|
+
if low > high:
|
|
196
|
+
raise _Invalid("class range with low > high")
|
|
197
|
+
if items == 0:
|
|
198
|
+
raise _Outside("empty class")
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def check_pattern(pattern: str) -> str | None:
|
|
202
|
+
"""None when accepted, else `regex_outside_subset` or `regex_invalid`."""
|
|
203
|
+
p = _Parser(pattern)
|
|
204
|
+
try:
|
|
205
|
+
p.pattern(0)
|
|
206
|
+
if p.i != p.n:
|
|
207
|
+
return "regex_outside_subset"
|
|
208
|
+
except _Invalid:
|
|
209
|
+
return "regex_invalid"
|
|
210
|
+
except _Outside:
|
|
211
|
+
return "regex_outside_subset"
|
|
212
|
+
try:
|
|
213
|
+
compile_pattern(pattern)
|
|
214
|
+
except re.error:
|
|
215
|
+
return "regex_outside_subset"
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _rewrite(pattern: str) -> str:
|
|
220
|
+
out: list[str] = []
|
|
221
|
+
i, n = 0, len(pattern)
|
|
222
|
+
in_class = False
|
|
223
|
+
after_class_escape = False
|
|
224
|
+
while i < n:
|
|
225
|
+
c = pattern[i]
|
|
226
|
+
if c == "\\":
|
|
227
|
+
out.append(pattern[i:i + 2])
|
|
228
|
+
after_class_escape = in_class and pattern[i + 1:i + 2] in _CLASS_ESCAPES
|
|
229
|
+
i += 2
|
|
230
|
+
continue
|
|
231
|
+
if in_class:
|
|
232
|
+
if c == "]":
|
|
233
|
+
in_class = False
|
|
234
|
+
elif c == "-" and after_class_escape:
|
|
235
|
+
# `[\d-x]`: the subset reads `-` after a class escape as a literal;
|
|
236
|
+
# Python's `re` would read a range, so escape it.
|
|
237
|
+
c = "\\-"
|
|
238
|
+
out.append(c)
|
|
239
|
+
elif c == "[":
|
|
240
|
+
in_class = True
|
|
241
|
+
out.append(c)
|
|
242
|
+
elif c == "$":
|
|
243
|
+
out.append("\\Z")
|
|
244
|
+
else:
|
|
245
|
+
out.append(c)
|
|
246
|
+
after_class_escape = False
|
|
247
|
+
i += 1
|
|
248
|
+
return "".join(out)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
_cache: dict[str, re.Pattern] = {}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def compile_pattern(pattern: str) -> re.Pattern:
|
|
255
|
+
rx = _cache.get(pattern)
|
|
256
|
+
if rx is None:
|
|
257
|
+
rx = _cache[pattern] = re.compile(_rewrite(pattern), re.ASCII)
|
|
258
|
+
return rx
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def matches(pattern: str, subject: str) -> bool:
|
|
262
|
+
return compile_pattern(pattern).fullmatch(subject) is not None
|
amiril/_engine/rules.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""One rule's evaluation (spec/edoc.md, section 7) and the `Decision` it produces."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import unicodedata
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .expr import Env, Evaluator
|
|
11
|
+
from .sentence import render_sentence
|
|
12
|
+
from .validate import BARE_READS, let_order, read_path_of
|
|
13
|
+
from .values import MISSING, EvalError, is_number, type_name
|
|
14
|
+
|
|
15
|
+
DEFAULT_HOLD_TIMEOUT_MS = 300000
|
|
16
|
+
|
|
17
|
+
# ECMAScript's WhiteSpace and LineTerminator (what `String.prototype.trim` removes),
|
|
18
|
+
# so both cores trim agent names identically.
|
|
19
|
+
_TRIM = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a" \
|
|
20
|
+
"\u2028\u2029\u202f\u205f\u3000\ufeff"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def agent_name(value: Any) -> Any:
|
|
24
|
+
"""edoc.md 7.1 targeting: agent names compare after NFC normalisation and
|
|
25
|
+
trimming leading and trailing whitespace. Non-strings are left as they are."""
|
|
26
|
+
if not isinstance(value, str):
|
|
27
|
+
return value
|
|
28
|
+
return unicodedata.normalize("NFC", value).strip(_TRIM)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def stored_agent_name(value: Any) -> str | None:
|
|
32
|
+
"""protocol.md 4.3: an agent name in the form the server stores names in:
|
|
33
|
+
the targeting form, cut to its first 256 code points and trimmed again.
|
|
34
|
+
None for a non-string or a name that is empty in that form."""
|
|
35
|
+
if not isinstance(value, str):
|
|
36
|
+
return None
|
|
37
|
+
return agent_name(value)[:256].rstrip(_TRIM) or None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class Decision:
|
|
42
|
+
"""One rule's verdict on one snapshot (edoc.md 7.7, kernel.md 2.3).
|
|
43
|
+
|
|
44
|
+
`rule_mode` is the mode the rule declared; `mode` the effective mode after
|
|
45
|
+
the kernel's cap. `latency_us` is engine time only and is not compared."""
|
|
46
|
+
|
|
47
|
+
rule_id: str
|
|
48
|
+
rule_version: str
|
|
49
|
+
ruleset_version: str
|
|
50
|
+
action: str
|
|
51
|
+
outcome: str
|
|
52
|
+
rule_mode: str
|
|
53
|
+
mode: str
|
|
54
|
+
evidence: list[dict] = field(default_factory=list)
|
|
55
|
+
sentence: str = ""
|
|
56
|
+
error: str | None = None
|
|
57
|
+
latency_us: float = 0.0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
STAND_IN_ERROR = "this SDK cannot read the rule"
|
|
61
|
+
STAND_IN_SENTENCE = "This SDK cannot read the rule, and the rule requires a check before the call runs."
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class StandIn:
|
|
66
|
+
"""A rule this core could not read whose bundle entry fails closed
|
|
67
|
+
(kernel.md 8.4). It keeps the entry's id, version and targeting, and every
|
|
68
|
+
evaluation of it is an evaluation error that blocks the call."""
|
|
69
|
+
|
|
70
|
+
id: str
|
|
71
|
+
version: str
|
|
72
|
+
agents: tuple[str, ...] | None
|
|
73
|
+
tools: tuple[str, ...]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class CompiledRule:
|
|
77
|
+
"""A rule with its targeting and defaults resolved. `raw` stays the truth."""
|
|
78
|
+
|
|
79
|
+
__slots__ = (
|
|
80
|
+
"raw", "id", "version", "phase", "scope", "mode", "if_missing", "portable", "bands", "assertion",
|
|
81
|
+
"when", "let", "action", "on_error", "agents", "tools", "fail_mode", "hold_timeout_ms", "stand_in",
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def __init__(self, raw: dict, groups: dict[str, list[str]], *, stand_in: bool = False) -> None:
|
|
85
|
+
self.stand_in = stand_in
|
|
86
|
+
self.raw = raw
|
|
87
|
+
self.id: str = raw["id"]
|
|
88
|
+
self.version: str = raw.get("version", "1")
|
|
89
|
+
self.phase: str = raw.get("phase", "pre")
|
|
90
|
+
self.scope: str = raw.get("scope", "run")
|
|
91
|
+
self.mode: str = raw.get("mode", "shadow")
|
|
92
|
+
self.if_missing: str = raw.get("if_missing", "violate")
|
|
93
|
+
self.portable: bool = raw.get("portable", True)
|
|
94
|
+
self.bands: dict | None = raw.get("bands")
|
|
95
|
+
self.assertion: Any = raw.get("assert")
|
|
96
|
+
self.when: Any = raw.get("when")
|
|
97
|
+
let = raw.get("let") or {}
|
|
98
|
+
order, _, _ = let_order(let)
|
|
99
|
+
self.let: list[tuple[str, Any, str | None]] = [
|
|
100
|
+
(name, let[name], read_path_of(let[name]) if _bare(let[name]) else None) for name in order
|
|
101
|
+
]
|
|
102
|
+
self.action: str = raw.get("action") or self.bands["bands"][-1]["action"]
|
|
103
|
+
self.on_error: str = raw.get("on_error") or self.action
|
|
104
|
+
self.agents: frozenset[str] | None = frozenset(agent_name(a) for a in raw["agents"]) \
|
|
105
|
+
if raw.get("agents") else None
|
|
106
|
+
target = raw.get("target") or {"tools": ["*"]}
|
|
107
|
+
tools = groups[target["group"]] if "group" in target else target["tools"]
|
|
108
|
+
self.tools: frozenset[str] | None = None if "*" in tools else frozenset(tools)
|
|
109
|
+
self.fail_mode: str = raw.get("fail_mode", "open")
|
|
110
|
+
self.hold_timeout_ms: int = int(raw.get("hold_timeout_ms", DEFAULT_HOLD_TIMEOUT_MS))
|
|
111
|
+
|
|
112
|
+
@classmethod
|
|
113
|
+
def for_stand_in(cls, stand_in: StandIn) -> CompiledRule:
|
|
114
|
+
raw: dict[str, Any] = {
|
|
115
|
+
"id": stand_in.id, "version": stand_in.version, "description": STAND_IN_SENTENCE,
|
|
116
|
+
"target": {"tools": list(stand_in.tools)}, "mode": "enforce", "fail_mode": "closed", "action": "block",
|
|
117
|
+
}
|
|
118
|
+
if stand_in.agents is not None:
|
|
119
|
+
raw["agents"] = list(stand_in.agents)
|
|
120
|
+
return cls(raw, {}, stand_in=True)
|
|
121
|
+
|
|
122
|
+
def targets(self, phase: str, agent_id: Any, tool_id: Any) -> bool:
|
|
123
|
+
"""Section 7.1 (the `mode: off` test is the engine's)."""
|
|
124
|
+
if phase != self.phase:
|
|
125
|
+
return False
|
|
126
|
+
if self.agents is not None and agent_name(agent_id) not in self.agents:
|
|
127
|
+
return False
|
|
128
|
+
if self.phase == "run_end":
|
|
129
|
+
return True
|
|
130
|
+
return self.tools is None or tool_id in self.tools
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _bare(expr: Any) -> bool:
|
|
134
|
+
return type(expr) is dict and len(expr) == 1 and next(iter(expr)) in BARE_READS
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def decide(rule: CompiledRule, ev: Evaluator, env: Env, ruleset_version: str) -> Decision | None:
|
|
138
|
+
"""Evaluate one targeting rule; None when `when` rules it out (7.2)."""
|
|
139
|
+
t0 = time.perf_counter()
|
|
140
|
+
outcome, action, error = "pass", "allow", None
|
|
141
|
+
try:
|
|
142
|
+
if rule.stand_in:
|
|
143
|
+
raise EvalError(STAND_IN_ERROR)
|
|
144
|
+
if rule.when is not None:
|
|
145
|
+
w = ev.eval(rule.when, env)
|
|
146
|
+
if w is False or w is MISSING:
|
|
147
|
+
return None
|
|
148
|
+
if w is not True:
|
|
149
|
+
raise EvalError(f"when needs a boolean, got {type_name(w)}")
|
|
150
|
+
for name, expr, read_path in rule.let:
|
|
151
|
+
value = ev.eval(expr, env)
|
|
152
|
+
env.vars[name] = value
|
|
153
|
+
if read_path is None:
|
|
154
|
+
env.evidence.read(name, value)
|
|
155
|
+
else:
|
|
156
|
+
env.evidence.name(read_path, name)
|
|
157
|
+
if rule.bands is None:
|
|
158
|
+
r = ev.eval(rule.assertion, env)
|
|
159
|
+
if r is True:
|
|
160
|
+
pass
|
|
161
|
+
elif r is False:
|
|
162
|
+
outcome, action = "violate", rule.action
|
|
163
|
+
elif r is MISSING:
|
|
164
|
+
outcome, action = _missing(rule)
|
|
165
|
+
else:
|
|
166
|
+
raise EvalError(f"assert needs a boolean, got {type_name(r)}")
|
|
167
|
+
else:
|
|
168
|
+
v = ev.eval(rule.bands["value"], env)
|
|
169
|
+
if v is MISSING:
|
|
170
|
+
outcome, action = _missing(rule)
|
|
171
|
+
elif not is_number(v):
|
|
172
|
+
raise EvalError(f"bands value needs a number, got {type_name(v)}")
|
|
173
|
+
else:
|
|
174
|
+
outcome = "band"
|
|
175
|
+
for band in rule.bands["bands"]:
|
|
176
|
+
if "max" not in band or v <= band["max"]:
|
|
177
|
+
action = band["action"]
|
|
178
|
+
break
|
|
179
|
+
except EvalError as exc:
|
|
180
|
+
outcome, action, error = "error", rule.on_error, str(exc)
|
|
181
|
+
except Exception as exc: # noqa: BLE001 - nothing inside a rule may escape as a kernel fault (7.6)
|
|
182
|
+
outcome, action, error = "error", rule.on_error, f"{type(exc).__name__}: {exc}"
|
|
183
|
+
evidence = env.evidence.as_list()
|
|
184
|
+
sentence = render_sentence(rule.raw, outcome, evidence)
|
|
185
|
+
return Decision(rule.id, rule.version, ruleset_version, action, outcome, rule.mode, rule.mode,
|
|
186
|
+
evidence, sentence, error, (time.perf_counter() - t0) * 1e6)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _missing(rule: CompiledRule) -> tuple[str, str]:
|
|
190
|
+
if rule.if_missing == "skip":
|
|
191
|
+
return "skip", "allow"
|
|
192
|
+
return "missing", rule.action
|