amiril 0.0.0.dev0__tar.gz → 0.1.0__tar.gz
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-0.0.0.dev0 → amiril-0.1.0}/PKG-INFO +1 -1
- {amiril-0.0.0.dev0 → amiril-0.1.0}/pyproject.toml +1 -1
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/__init__.py +1 -1
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/engine.py +1 -1
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/expr.py +107 -16
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/rules.py +5 -4
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/sentence.py +7 -0
- amiril-0.1.0/src/amiril/_engine/timeparse.py +129 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/validate.py +24 -6
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/guard.py +2 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/messages.py +5 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_runtime.py +24 -7
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/client.py +3 -1
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/config.py +15 -5
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/installation-register.request.schema.json +6 -1
- amiril-0.1.0/src/amiril/control/surroundings.py +74 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/core.py +4 -2
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/README.md +2 -2
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/frameworks/adk.md +4 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/frameworks/langgraph.md +4 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/frameworks/no-framework.md +4 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/frameworks/write-an-adapter.md +4 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/plain.py +5 -2
- amiril-0.0.0.dev0/src/amiril/_engine/timeparse.py +0 -72
- {amiril-0.0.0.dev0 → amiril-0.1.0}/.gitignore +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/LICENSE +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/README.md +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/hatch_build.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_adapters.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/__init__.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/numbers.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/regex.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_engine/values.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/__init__.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/bundle.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/coerce.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/events.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/ids.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/normalise.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/records.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/_kernel/store.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/adk.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/__init__.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_delivery.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_disk.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_holds.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_jsonschema.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_pathc.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_records.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_redact.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_transport.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/_wire.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/bundle.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/common.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/decisions.request.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/decisions.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/error.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/heartbeat.request.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/heartbeat.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/hold-create.request.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/hold.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/installation-register.response.schema.json +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/docs/durability/langgraph.md +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/durable.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/langgraph.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/py.typed +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/seams.py +0 -0
- {amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/testing.py +0 -0
|
@@ -19,7 +19,7 @@ from __future__ import annotations
|
|
|
19
19
|
import importlib
|
|
20
20
|
from typing import Any
|
|
21
21
|
|
|
22
|
-
__version__ = "0.
|
|
22
|
+
__version__ = "0.1.0"
|
|
23
23
|
|
|
24
24
|
from ._adapters import AmirilInstallError, HookOrderError, NotInitialisedError # noqa: E402
|
|
25
25
|
from ._runtime import Amiril, init, instrument # noqa: E402
|
|
@@ -60,7 +60,7 @@ class LoadedDocument:
|
|
|
60
60
|
for rule in self.rules:
|
|
61
61
|
if rule.mode == "off" or not rule.targets(phase, agent_id, tool_id):
|
|
62
62
|
continue
|
|
63
|
-
env = Env(call, context, index, rule.scope, self.sets)
|
|
63
|
+
env = Env(call, context, index, rule.scope, self.sets, rule.nulls)
|
|
64
64
|
d = decide(rule, self.evaluator, env, self.ruleset_version)
|
|
65
65
|
if d is not None:
|
|
66
66
|
out.append(d)
|
|
@@ -4,7 +4,8 @@ Documents reach the evaluator validated, so node shapes are trusted and
|
|
|
4
4
|
only data-dependent failures arise, as `EvalError`. Three-valued logic:
|
|
5
5
|
Missing propagates through every operator; `and`, `or`, `not` and the
|
|
6
6
|
quantifiers follow 8.1; an error raised while evaluating an operand
|
|
7
|
-
always wins over a Missing elsewhere (8.2).
|
|
7
|
+
always wins over a Missing elsewhere (8.2). Under a rule's `"nulls":
|
|
8
|
+
"missing"` a null or Absent operand that needs a type is Missing (8.12).
|
|
8
9
|
"""
|
|
9
10
|
|
|
10
11
|
from __future__ import annotations
|
|
@@ -15,7 +16,7 @@ from typing import Any
|
|
|
15
16
|
from .._kernel.normalise import to_json
|
|
16
17
|
from .numbers import extreme_max, extreme_min, neumaier_sum
|
|
17
18
|
from .regex import compile_pattern
|
|
18
|
-
from .timeparse import hour_of_epoch, hour_of_iso
|
|
19
|
+
from .timeparse import epoch_instant, epoch_seconds, hour_of_epoch, hour_of_iso, iso_instant, time_zone
|
|
19
20
|
from .validate import tool_label
|
|
20
21
|
from .values import (
|
|
21
22
|
ABSENT,
|
|
@@ -36,6 +37,8 @@ from .values import (
|
|
|
36
37
|
|
|
37
38
|
_NO_IT = object()
|
|
38
39
|
PICK_ALL_CAP = 20
|
|
40
|
+
WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
|
41
|
+
DURATIONS = {"minutes": 60.0, "hours": 3600.0, "days": 86400.0}
|
|
39
42
|
|
|
40
43
|
|
|
41
44
|
class Evidence:
|
|
@@ -127,14 +130,16 @@ class HistoryIndex:
|
|
|
127
130
|
|
|
128
131
|
|
|
129
132
|
class Env:
|
|
130
|
-
__slots__ = ("call", "context", "history", "scope", "sets", "vars", "it", "it_is_record", "evidence")
|
|
133
|
+
__slots__ = ("call", "context", "history", "scope", "sets", "nulls", "vars", "it", "it_is_record", "evidence")
|
|
131
134
|
|
|
132
|
-
def __init__(self, call: Any, context: dict, history: HistoryIndex, scope: str, sets: dict
|
|
135
|
+
def __init__(self, call: Any, context: dict, history: HistoryIndex, scope: str, sets: dict,
|
|
136
|
+
nulls: bool = False) -> None:
|
|
133
137
|
self.call = call
|
|
134
138
|
self.context = context
|
|
135
139
|
self.history = history
|
|
136
140
|
self.scope = scope
|
|
137
141
|
self.sets = sets
|
|
142
|
+
self.nulls = nulls # the rule's "nulls": "missing" (edoc.md 8.12)
|
|
138
143
|
self.vars: dict[str, Any] = {}
|
|
139
144
|
self.it: Any = _NO_IT
|
|
140
145
|
self.it_is_record = False
|
|
@@ -162,6 +167,9 @@ class Evaluator:
|
|
|
162
167
|
"it": self._it, "lit": self._lit, "prev": self._prev,
|
|
163
168
|
"calls": self._calls, "prior": self._prior, "agg": self._agg,
|
|
164
169
|
"hour_utc": self._hour_utc, "predicate": self._predicate,
|
|
170
|
+
"weekday": self._weekday, "hour": self._hour, "date": self._date, "time": self._time,
|
|
171
|
+
"minutes": self._duration("minutes"), "hours": self._duration("hours"), "days": self._duration("days"),
|
|
172
|
+
"starts_with": self._starts_with, "contains": self._contains,
|
|
165
173
|
}
|
|
166
174
|
|
|
167
175
|
# ------------------------------------------------------------ core
|
|
@@ -179,6 +187,16 @@ class Evaluator:
|
|
|
179
187
|
vals = [self.eval(n, env) for n in nodes]
|
|
180
188
|
return vals, any(v is MISSING for v in vals)
|
|
181
189
|
|
|
190
|
+
def typed(self, node: Any, env: Env) -> Any:
|
|
191
|
+
"""An operand that needs a value of a type: under `"nulls": "missing"`
|
|
192
|
+
a null or Absent value is Missing (8.12)."""
|
|
193
|
+
v = self.eval(node, env)
|
|
194
|
+
return MISSING if env.nulls and (v is None or v is ABSENT) else v
|
|
195
|
+
|
|
196
|
+
def _typed_operands(self, nodes: list, env: Env) -> tuple[list, bool]:
|
|
197
|
+
vals = [self.typed(n, env) for n in nodes]
|
|
198
|
+
return vals, any(v is MISSING for v in vals)
|
|
199
|
+
|
|
182
200
|
# ------------------------------------------------------------ reads
|
|
183
201
|
|
|
184
202
|
def _arg(self, path: str, env: Env) -> Any:
|
|
@@ -420,8 +438,8 @@ class Evaluator:
|
|
|
420
438
|
return MISSING if r is MISSING else not r
|
|
421
439
|
|
|
422
440
|
def _ordered(self, nodes: list, env: Env, what: str) -> tuple[Any, Any] | None:
|
|
423
|
-
a = self.
|
|
424
|
-
b = self.
|
|
441
|
+
a = self.typed(nodes[0], env)
|
|
442
|
+
b = self.typed(nodes[1], env)
|
|
425
443
|
if a is MISSING or b is MISSING:
|
|
426
444
|
return None
|
|
427
445
|
if is_number(a) and is_number(b):
|
|
@@ -457,7 +475,7 @@ class Evaluator:
|
|
|
457
475
|
def _and(self, nodes: list, env: Env) -> Any:
|
|
458
476
|
saw_missing = False
|
|
459
477
|
for n in nodes:
|
|
460
|
-
v = self._bool(self.
|
|
478
|
+
v = self._bool(self.typed(n, env), "and")
|
|
461
479
|
if v is False:
|
|
462
480
|
return False
|
|
463
481
|
if v is MISSING:
|
|
@@ -467,7 +485,7 @@ class Evaluator:
|
|
|
467
485
|
def _or(self, nodes: list, env: Env) -> Any:
|
|
468
486
|
saw_missing = False
|
|
469
487
|
for n in nodes:
|
|
470
|
-
v = self._bool(self.
|
|
488
|
+
v = self._bool(self.typed(n, env), "or")
|
|
471
489
|
if v is True:
|
|
472
490
|
return True
|
|
473
491
|
if v is MISSING:
|
|
@@ -475,13 +493,13 @@ class Evaluator:
|
|
|
475
493
|
return MISSING if saw_missing else False
|
|
476
494
|
|
|
477
495
|
def _not(self, node: Any, env: Env) -> Any:
|
|
478
|
-
v = self._bool(self.
|
|
496
|
+
v = self._bool(self.typed(node, env), "not")
|
|
479
497
|
return MISSING if v is MISSING else not v
|
|
480
498
|
|
|
481
499
|
# ------------------------------------------------------------ arithmetic
|
|
482
500
|
|
|
483
501
|
def _nums(self, nodes: list, env: Env, what: str) -> list[float] | None:
|
|
484
|
-
vals, missing = self.
|
|
502
|
+
vals, missing = self._typed_operands(nodes, env)
|
|
485
503
|
if missing:
|
|
486
504
|
return None
|
|
487
505
|
for v in vals:
|
|
@@ -529,8 +547,9 @@ class Evaluator:
|
|
|
529
547
|
# ------------------------------------------------------------ membership, strings, shape
|
|
530
548
|
|
|
531
549
|
def _in(self, nodes: list, env: Env) -> Any:
|
|
532
|
-
|
|
533
|
-
|
|
550
|
+
needle = self.eval(nodes[0], env)
|
|
551
|
+
hay = self.typed(nodes[1], env)
|
|
552
|
+
if needle is MISSING or hay is MISSING:
|
|
534
553
|
return MISSING
|
|
535
554
|
if type(hay) is not list:
|
|
536
555
|
raise EvalError(f"in needs a list on the right, got {describe(hay)}")
|
|
@@ -539,7 +558,7 @@ class Evaluator:
|
|
|
539
558
|
return any(equal(needle, h) for h in hay)
|
|
540
559
|
|
|
541
560
|
def _matches(self, nodes: list, env: Env) -> Any:
|
|
542
|
-
subject = self.
|
|
561
|
+
subject = self.typed(nodes[0], env)
|
|
543
562
|
if subject is MISSING:
|
|
544
563
|
return MISSING
|
|
545
564
|
if type(subject) is not str:
|
|
@@ -547,7 +566,7 @@ class Evaluator:
|
|
|
547
566
|
return compile_pattern(nodes[1]).fullmatch(subject) is not None
|
|
548
567
|
|
|
549
568
|
def _len(self, node: Any, env: Env) -> Any:
|
|
550
|
-
v = self.
|
|
569
|
+
v = self.typed(node, env)
|
|
551
570
|
if v is MISSING:
|
|
552
571
|
return MISSING
|
|
553
572
|
t = type(v)
|
|
@@ -576,7 +595,7 @@ class Evaluator:
|
|
|
576
595
|
# ------------------------------------------------------------ quantifiers
|
|
577
596
|
|
|
578
597
|
def _quantify(self, nodes: list, env: Env, want: bool, what: str) -> Any:
|
|
579
|
-
items = self.
|
|
598
|
+
items = self.typed(nodes[0], env)
|
|
580
599
|
if items is MISSING:
|
|
581
600
|
return MISSING
|
|
582
601
|
records = type(items) is Selection
|
|
@@ -608,7 +627,7 @@ class Evaluator:
|
|
|
608
627
|
# ------------------------------------------------------------ time, escape hatch
|
|
609
628
|
|
|
610
629
|
def _hour_utc(self, node: Any, env: Env) -> Any:
|
|
611
|
-
v = self.
|
|
630
|
+
v = self.typed(node, env)
|
|
612
631
|
if v is MISSING:
|
|
613
632
|
return MISSING
|
|
614
633
|
if is_number(v):
|
|
@@ -623,6 +642,78 @@ class Evaluator:
|
|
|
623
642
|
return float(h)
|
|
624
643
|
raise EvalError(f"hour_utc needs epoch seconds or an ISO-8601 time, got {describe(v)}")
|
|
625
644
|
|
|
645
|
+
def _instant(self, v: Any, zone_name: str, op: str) -> Any:
|
|
646
|
+
"""The UTC instant a time operand names in its zone (6.7, 8.13)."""
|
|
647
|
+
if is_number(v):
|
|
648
|
+
instant = epoch_instant(v)
|
|
649
|
+
elif type(v) is str:
|
|
650
|
+
instant = iso_instant(v, time_zone(zone_name))
|
|
651
|
+
if instant is False:
|
|
652
|
+
raise EvalError(f"{op} needs epoch seconds or an ISO-8601 time, got {describe(v)}")
|
|
653
|
+
else:
|
|
654
|
+
raise EvalError(f"{op} needs epoch seconds or an ISO-8601 time, got {describe(v)}")
|
|
655
|
+
if instant is None:
|
|
656
|
+
raise EvalError(f"{op} value out of range, got {describe(v)}")
|
|
657
|
+
return instant
|
|
658
|
+
|
|
659
|
+
def _wall_clock(self, nodes: list, env: Env, op: str) -> Any:
|
|
660
|
+
"""The wall clock in the zone at the instant the operand names, or Missing."""
|
|
661
|
+
v = self.typed(nodes[0], env)
|
|
662
|
+
if v is MISSING:
|
|
663
|
+
return MISSING
|
|
664
|
+
instant = self._instant(v, nodes[1], op)
|
|
665
|
+
try:
|
|
666
|
+
return instant.astimezone(time_zone(nodes[1]))
|
|
667
|
+
except (OverflowError, ValueError): # an instant whose wall clock is past the year 9999
|
|
668
|
+
raise EvalError(f"{op} value out of range, got {describe(v)}") from None
|
|
669
|
+
|
|
670
|
+
def _weekday(self, nodes: list, env: Env) -> Any:
|
|
671
|
+
t = self._wall_clock(nodes, env, "weekday")
|
|
672
|
+
return t if t is MISSING else WEEKDAYS[t.weekday()]
|
|
673
|
+
|
|
674
|
+
def _hour(self, nodes: list, env: Env) -> Any:
|
|
675
|
+
t = self._wall_clock(nodes, env, "hour")
|
|
676
|
+
return t if t is MISSING else float(t.hour)
|
|
677
|
+
|
|
678
|
+
def _date(self, nodes: list, env: Env) -> Any:
|
|
679
|
+
t = self._wall_clock(nodes, env, "date")
|
|
680
|
+
return t if t is MISSING else f"{t.year:04d}-{t.month:02d}-{t.day:02d}"
|
|
681
|
+
|
|
682
|
+
def _time(self, nodes: list, env: Env) -> Any:
|
|
683
|
+
v = self.typed(nodes[0], env)
|
|
684
|
+
if v is MISSING:
|
|
685
|
+
return MISSING
|
|
686
|
+
instant = self._instant(v, nodes[1], "time")
|
|
687
|
+
return v if is_number(v) else epoch_seconds(instant) # epoch seconds come back unchanged (6.7)
|
|
688
|
+
|
|
689
|
+
def _duration(self, op: str) -> Callable[[Any, Env], Any]:
|
|
690
|
+
factor = DURATIONS[op]
|
|
691
|
+
|
|
692
|
+
def duration(node: Any, env: Env) -> Any:
|
|
693
|
+
v = self.typed(node, env)
|
|
694
|
+
if v is MISSING:
|
|
695
|
+
return MISSING
|
|
696
|
+
if not is_number(v):
|
|
697
|
+
raise EvalError(f"{op} needs a number, got {describe(v)}")
|
|
698
|
+
return v * factor
|
|
699
|
+
return duration
|
|
700
|
+
|
|
701
|
+
def _strings(self, nodes: list, env: Env, op: str) -> tuple[str, str] | None:
|
|
702
|
+
(subject, part), missing = self._typed_operands(nodes, env)
|
|
703
|
+
if missing:
|
|
704
|
+
return None
|
|
705
|
+
if type(subject) is not str or type(part) is not str:
|
|
706
|
+
raise EvalError(f"{op} needs two strings, got {describe(subject)} and {describe(part)}")
|
|
707
|
+
return subject, part
|
|
708
|
+
|
|
709
|
+
def _starts_with(self, nodes: list, env: Env) -> Any:
|
|
710
|
+
p = self._strings(nodes, env, "starts_with")
|
|
711
|
+
return MISSING if p is None else p[0].startswith(p[1])
|
|
712
|
+
|
|
713
|
+
def _contains(self, nodes: list, env: Env) -> Any:
|
|
714
|
+
p = self._strings(nodes, env, "contains")
|
|
715
|
+
return MISSING if p is None else p[1] in p[0]
|
|
716
|
+
|
|
626
717
|
def _predicate(self, nodes: list, env: Env) -> Any:
|
|
627
718
|
name = nodes[0]
|
|
628
719
|
fn = self.predicates[name]
|
|
@@ -77,7 +77,7 @@ class CompiledRule:
|
|
|
77
77
|
"""A rule with its targeting and defaults resolved. `raw` stays the truth."""
|
|
78
78
|
|
|
79
79
|
__slots__ = (
|
|
80
|
-
"raw", "id", "version", "phase", "scope", "mode", "if_missing", "portable", "bands", "assertion",
|
|
80
|
+
"raw", "id", "version", "phase", "scope", "mode", "if_missing", "nulls", "portable", "bands", "assertion",
|
|
81
81
|
"when", "let", "action", "on_error", "agents", "tools", "fail_mode", "hold_timeout_ms", "stand_in",
|
|
82
82
|
)
|
|
83
83
|
|
|
@@ -90,6 +90,7 @@ class CompiledRule:
|
|
|
90
90
|
self.scope: str = raw.get("scope", "run")
|
|
91
91
|
self.mode: str = raw.get("mode", "shadow")
|
|
92
92
|
self.if_missing: str = raw.get("if_missing", "violate")
|
|
93
|
+
self.nulls: bool = raw.get("nulls") == "missing"
|
|
93
94
|
self.portable: bool = raw.get("portable", True)
|
|
94
95
|
self.bands: dict | None = raw.get("bands")
|
|
95
96
|
self.assertion: Any = raw.get("assert")
|
|
@@ -142,7 +143,7 @@ def decide(rule: CompiledRule, ev: Evaluator, env: Env, ruleset_version: str) ->
|
|
|
142
143
|
if rule.stand_in:
|
|
143
144
|
raise EvalError(STAND_IN_ERROR)
|
|
144
145
|
if rule.when is not None:
|
|
145
|
-
w = ev.
|
|
146
|
+
w = ev.typed(rule.when, env)
|
|
146
147
|
if w is False or w is MISSING:
|
|
147
148
|
return None
|
|
148
149
|
if w is not True:
|
|
@@ -155,7 +156,7 @@ def decide(rule: CompiledRule, ev: Evaluator, env: Env, ruleset_version: str) ->
|
|
|
155
156
|
else:
|
|
156
157
|
env.evidence.name(read_path, name)
|
|
157
158
|
if rule.bands is None:
|
|
158
|
-
r = ev.
|
|
159
|
+
r = ev.typed(rule.assertion, env)
|
|
159
160
|
if r is True:
|
|
160
161
|
pass
|
|
161
162
|
elif r is False:
|
|
@@ -165,7 +166,7 @@ def decide(rule: CompiledRule, ev: Evaluator, env: Env, ruleset_version: str) ->
|
|
|
165
166
|
else:
|
|
166
167
|
raise EvalError(f"assert needs a boolean, got {type_name(r)}")
|
|
167
168
|
else:
|
|
168
|
-
v = ev.
|
|
169
|
+
v = ev.typed(rule.bands["value"], env)
|
|
169
170
|
if v is MISSING:
|
|
170
171
|
outcome, action = _missing(rule)
|
|
171
172
|
elif not is_number(v):
|
|
@@ -122,6 +122,8 @@ def customer_view(rule: dict, decision: Any) -> dict:
|
|
|
122
122
|
if band is not None and "max" in band else "The value is above every band.")
|
|
123
123
|
elif outcome in ("missing", "skip"):
|
|
124
124
|
clauses = [_missing_clause(rule, e) for e in evidence if e.get("missing")]
|
|
125
|
+
if rule.get("nulls") == "missing":
|
|
126
|
+
clauses += [f"{label(e)} has no value." for e in evidence if _no_value(e)]
|
|
125
127
|
phrase = " ".join(clauses)
|
|
126
128
|
if outcome == "skip":
|
|
127
129
|
phrase = (phrase + " " if phrase else "") + "The rule does not apply."
|
|
@@ -148,6 +150,11 @@ def customer_view(rule: dict, decision: Any) -> dict:
|
|
|
148
150
|
return {"action": ACTION_WORDS[decision.action], "outcome": phrase, "body": "; ".join(parts) + "."}
|
|
149
151
|
|
|
150
152
|
|
|
153
|
+
def _no_value(e: dict) -> bool:
|
|
154
|
+
"""A null or absent read, which under `"nulls": "missing"` may have made the condition Missing (8.12)."""
|
|
155
|
+
return bool(e.get("absent")) or (not e.get("missing") and e.get("value", False) is None)
|
|
156
|
+
|
|
157
|
+
|
|
151
158
|
def _band_of(rule: dict, action: str) -> dict | None:
|
|
152
159
|
bands = rule.get("bands")
|
|
153
160
|
if type(bands) is not dict:
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""`hour_utc` (spec/edoc.md 6.6 and 8.10), the zoned time operators (6.7,
|
|
2
|
+
8.13) and the UTC rendering of `context.now` (10.3)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import datetime as _dt
|
|
7
|
+
import functools
|
|
8
|
+
import re
|
|
9
|
+
import zoneinfo
|
|
10
|
+
from decimal import ROUND_HALF_EVEN, Decimal, localcontext
|
|
11
|
+
|
|
12
|
+
# ASCII digits only (edoc.md 8.10): Python's \d would also match other scripts' digits.
|
|
13
|
+
_ISO = re.compile(
|
|
14
|
+
r"([0-9]{4})-([0-9]{2})-([0-9]{2})"
|
|
15
|
+
r"(?:[T ]([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:[.,]([0-9]{1,6}))?)?)?"
|
|
16
|
+
r"(Z|[+-][0-9]{2}:[0-9]{2})?"
|
|
17
|
+
)
|
|
18
|
+
_EPOCH = _dt.datetime(1970, 1, 1, tzinfo=_dt.timezone.utc)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def round_to_microsecond(seconds: float) -> int:
|
|
22
|
+
"""Epoch seconds to whole microseconds, half to even, on the exact decimal
|
|
23
|
+
expansion of the double (a float multiplication would move boundary values)."""
|
|
24
|
+
with localcontext() as c:
|
|
25
|
+
c.prec = 80
|
|
26
|
+
return int((Decimal(seconds) * 1_000_000).quantize(Decimal(1), rounding=ROUND_HALF_EVEN))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def utc_datetime(seconds: float) -> _dt.datetime:
|
|
30
|
+
"""The UTC time of epoch seconds rounded to the nearest microsecond.
|
|
31
|
+
Raises OverflowError outside the years 1 to 9999."""
|
|
32
|
+
return _EPOCH + _dt.timedelta(microseconds=round_to_microsecond(seconds))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def epoch_instant(seconds: float) -> _dt.datetime | None:
|
|
36
|
+
"""The UTC time of epoch seconds rounded to the nearest microsecond and
|
|
37
|
+
floored to a second; None when out of range."""
|
|
38
|
+
try:
|
|
39
|
+
return _EPOCH + _dt.timedelta(seconds=round_to_microsecond(seconds) // 1_000_000)
|
|
40
|
+
except (OverflowError, ValueError, ArithmeticError): # infinite, NaN or beyond the years 1 to 9999
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def hour_of_epoch(seconds: float) -> int | None:
|
|
45
|
+
"""The UTC hour of epoch seconds, floored to a second; None when out of range."""
|
|
46
|
+
dt = epoch_instant(seconds)
|
|
47
|
+
return None if dt is None else dt.hour
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def parse_iso(text: str) -> tuple[_dt.datetime, int | None] | None:
|
|
51
|
+
"""An ISO-8601 time of the shape in 8.10 as its wall-clock time and its
|
|
52
|
+
offset in minutes east of UTC (None when it has none); None when malformed."""
|
|
53
|
+
m = _ISO.fullmatch(text)
|
|
54
|
+
if m is None:
|
|
55
|
+
return None
|
|
56
|
+
hh, mm, ss = (int(g) if g is not None else 0 for g in (m[4], m[5], m[6]))
|
|
57
|
+
if hh > 23 or mm > 59 or ss > 59:
|
|
58
|
+
return None
|
|
59
|
+
try:
|
|
60
|
+
wall = _dt.datetime(int(m[1]), int(m[2]), int(m[3]), hh, mm, ss, int((m[7] or "0").ljust(6, "0")))
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
off = m[8]
|
|
64
|
+
if not off:
|
|
65
|
+
return wall, None
|
|
66
|
+
if off == "Z":
|
|
67
|
+
return wall, 0
|
|
68
|
+
oh, om = int(off[1:3]), int(off[4:6])
|
|
69
|
+
if oh > 23 or om > 59:
|
|
70
|
+
return None
|
|
71
|
+
return wall, (oh * 60 + om) * (1 if off[0] == "+" else -1)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def hour_of_iso(text: str) -> int | None:
|
|
75
|
+
"""The UTC hour of an ISO-8601 time of the shape in 8.10 (no offset is UTC); None when malformed."""
|
|
76
|
+
parsed = parse_iso(text)
|
|
77
|
+
if parsed is None:
|
|
78
|
+
return None
|
|
79
|
+
wall, offset = parsed
|
|
80
|
+
return ((wall.hour * 60 + wall.minute - (offset or 0)) // 60) % 24
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@functools.cache
|
|
84
|
+
def _zone_names() -> frozenset[str]:
|
|
85
|
+
return frozenset(zoneinfo.available_timezones())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@functools.cache
|
|
89
|
+
def time_zone(name: str) -> _dt.tzinfo | None:
|
|
90
|
+
"""The zone an IANA name names, compared exactly (8.13), from the
|
|
91
|
+
platform's database; None when the platform does not know it. The exact
|
|
92
|
+
names come from the database's own listing, because on a case-insensitive
|
|
93
|
+
file system `ZoneInfo` would open `europe/london` too."""
|
|
94
|
+
if name == "UTC":
|
|
95
|
+
return _dt.timezone.utc
|
|
96
|
+
if name not in _zone_names():
|
|
97
|
+
return None
|
|
98
|
+
try:
|
|
99
|
+
return zoneinfo.ZoneInfo(name)
|
|
100
|
+
except (zoneinfo.ZoneInfoNotFoundError, ValueError, OSError):
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def iso_instant(text: str, zone: _dt.tzinfo) -> _dt.datetime | bool | None:
|
|
105
|
+
"""The UTC instant an ISO-8601 string names (6.7): with an offset, that
|
|
106
|
+
instant; without, its wall-clock time in `zone` read with fold 0 (8.13).
|
|
107
|
+
False when malformed; None when the instant is outside the years 1 to 9999."""
|
|
108
|
+
parsed = parse_iso(text)
|
|
109
|
+
if parsed is None:
|
|
110
|
+
return False
|
|
111
|
+
wall, offset = parsed
|
|
112
|
+
tz = zone if offset is None else _dt.timezone(_dt.timedelta(minutes=offset))
|
|
113
|
+
try:
|
|
114
|
+
return wall.replace(tzinfo=tz, fold=0).astimezone(_dt.timezone.utc)
|
|
115
|
+
except (OverflowError, ValueError):
|
|
116
|
+
return None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def epoch_seconds(instant: _dt.datetime) -> float:
|
|
120
|
+
"""An aware instant's epoch seconds as `seconds + microseconds / 1000000` in doubles (6.7)."""
|
|
121
|
+
delta = instant - _EPOCH
|
|
122
|
+
return float(delta.days * 86400 + delta.seconds) + delta.microseconds / 1_000_000
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def render_now(seconds: float) -> str:
|
|
126
|
+
"""`YYYY-MM-DDTHH:MM:SSZ` of epoch seconds rounded to the nearest microsecond."""
|
|
127
|
+
# Not strftime: glibc's %Y does not pad a year below 1000, macOS's does.
|
|
128
|
+
t = utc_datetime(seconds)
|
|
129
|
+
return f"{t.year:04d}-{t.month:02d}-{t.day:02d}T{t.hour:02d}:{t.minute:02d}:{t.second:02d}Z"
|
|
@@ -9,15 +9,18 @@ rendering.
|
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
|
+
import json
|
|
12
13
|
import re
|
|
13
14
|
from typing import Any
|
|
14
15
|
|
|
15
16
|
from .regex import check_pattern
|
|
17
|
+
from .timeparse import time_zone
|
|
16
18
|
|
|
17
19
|
SCHEMA_ID = "amiril.rules/1"
|
|
18
20
|
# One name per addition to the rule document this loader reads beyond the
|
|
19
|
-
# first `amiril.rules/1` (edoc.md 13). The client sends it at registration
|
|
20
|
-
|
|
21
|
+
# first `amiril.rules/1` (edoc.md 13). The client sends it at registration
|
|
22
|
+
# and on the bundle poll (protocol.md 4.1, 5.1).
|
|
23
|
+
CAPABILITIES: tuple[str, ...] = ("rules.nulls", "rules.zoned_time", "rules.durations", "rules.strings")
|
|
21
24
|
|
|
22
25
|
ACTIONS = ("allow", "flag", "hold", "block")
|
|
23
26
|
FAIL_ACTIONS = ("flag", "hold", "block")
|
|
@@ -26,6 +29,7 @@ PHASES = ("pre", "post", "run_end")
|
|
|
26
29
|
MODES = ("off", "shadow", "enforce")
|
|
27
30
|
FAIL_MODES = ("open", "closed")
|
|
28
31
|
IF_MISSING = ("violate", "skip")
|
|
32
|
+
NULLS = ("error", "missing")
|
|
29
33
|
STATUSES = ("pending", "ok", "error", "blocked", "held")
|
|
30
34
|
PICKS = ("latest", "first", "all")
|
|
31
35
|
AGG_OPS = ("sum", "min", "max", "count", "count_distinct")
|
|
@@ -39,7 +43,7 @@ RECORD_FIELDS = (
|
|
|
39
43
|
TOP_KEYS = frozenset({"schema", "ruleset_version", "sets", "groups", "aliases", "predicates", "rules", "about"})
|
|
40
44
|
RULE_KEYS = frozenset({
|
|
41
45
|
"id", "version", "description", "target", "agents", "phase", "scope", "when", "let", "assert", "bands",
|
|
42
|
-
"action", "mode", "if_missing", "on_error", "fail_mode", "hold_timeout_ms", "sentence", "portable", "meta",
|
|
46
|
+
"action", "mode", "if_missing", "on_error", "nulls", "fail_mode", "hold_timeout_ms", "sentence", "portable", "meta",
|
|
43
47
|
})
|
|
44
48
|
CALLS_KEYS = frozenset({"tool", "status", "join", "where", "scope", "kind"})
|
|
45
49
|
PRIOR_KEYS = CALLS_KEYS | {"path", "pick"}
|
|
@@ -50,12 +54,13 @@ LIST_OPS: dict[str, tuple[int, int | None]] = {
|
|
|
50
54
|
"==": (2, 2), "!=": (2, 2), "<": (2, 2), "<=": (2, 2), ">": (2, 2), ">=": (2, 2),
|
|
51
55
|
"and": (2, None), "or": (2, None),
|
|
52
56
|
"+": (2, None), "*": (2, None), "-": (2, 2), "/": (2, 2), "min": (2, None), "max": (2, None),
|
|
53
|
-
"in": (2, 2),
|
|
57
|
+
"in": (2, 2), "starts_with": (2, 2), "contains": (2, 2),
|
|
54
58
|
}
|
|
55
|
-
UNARY_OPS = frozenset({"not", "abs", "len", "present", "hour_utc"})
|
|
59
|
+
UNARY_OPS = frozenset({"not", "abs", "len", "present", "hour_utc", "minutes", "hours", "days"})
|
|
60
|
+
ZONED_OPS = frozenset({"weekday", "hour", "date", "time"})
|
|
56
61
|
STRING_OPS = frozenset({"arg", "path", "ctx", "set", "var", "it", "prev"})
|
|
57
62
|
STRUCTURED_OPS = frozenset({"lit", "is", "matches", "all", "any", "exists", "calls", "prior", "agg", "predicate"})
|
|
58
|
-
ALL_OPS = frozenset(LIST_OPS) | UNARY_OPS | STRING_OPS | STRUCTURED_OPS
|
|
63
|
+
ALL_OPS = frozenset(LIST_OPS) | UNARY_OPS | STRING_OPS | STRUCTURED_OPS | ZONED_OPS
|
|
59
64
|
BARE_READS = frozenset({"arg", "path", "ctx", "prior", "prev", "agg", "exists"})
|
|
60
65
|
|
|
61
66
|
_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
|
@@ -260,6 +265,8 @@ def _rule(rep: _Report, where: str, rule: dict, dctx: _Doc) -> None:
|
|
|
260
265
|
_enum(rep, pointer_join(where, "if_missing"), rule["if_missing"], IF_MISSING, "if_missing")
|
|
261
266
|
if "on_error" in rule:
|
|
262
267
|
_enum(rep, pointer_join(where, "on_error"), rule["on_error"], ACTIONS, "on_error")
|
|
268
|
+
if "nulls" in rule:
|
|
269
|
+
_enum(rep, pointer_join(where, "nulls"), rule["nulls"], NULLS, "nulls")
|
|
263
270
|
if "fail_mode" in rule:
|
|
264
271
|
if _enum(rep, pointer_join(where, "fail_mode"), rule["fail_mode"], FAIL_MODES, "fail_mode"):
|
|
265
272
|
if rule["fail_mode"] == "closed" and mode != "enforce":
|
|
@@ -494,6 +501,17 @@ def _expr(rep: _Report, where: str, node: Any, dctx: _Doc, rctx: _RuleCtx, *, it
|
|
|
494
501
|
_expr(rep, opw, arg, dctx, rctx, it=it, in_when=in_when)
|
|
495
502
|
elif op in STRING_OPS:
|
|
496
503
|
_string_op(rep, opw, op, arg, dctx, rctx, it=it, in_when=in_when)
|
|
504
|
+
elif op in ZONED_OPS:
|
|
505
|
+
if type(arg) is not list:
|
|
506
|
+
rep.add(opw, "bad_type", f"{op} takes [time, zone]")
|
|
507
|
+
elif len(arg) != 2:
|
|
508
|
+
rep.add(opw, "bad_arity", f"{op} takes [time, zone]")
|
|
509
|
+
else:
|
|
510
|
+
sub(0, arg[0])
|
|
511
|
+
if type(arg[1]) is not str:
|
|
512
|
+
rep.add(pointer_join(opw, 1), "bad_type", "a time zone must be a string literal")
|
|
513
|
+
elif time_zone(arg[1]) is None:
|
|
514
|
+
rep.add(pointer_join(opw, 1), "unknown_time_zone", f"unknown time zone {json.dumps(arg[1])}")
|
|
497
515
|
elif op == "lit":
|
|
498
516
|
if type(arg) is not list:
|
|
499
517
|
rep.add(opw, "bad_type", "lit takes a JSON list")
|
|
@@ -543,6 +543,8 @@ class Guard:
|
|
|
543
543
|
rec = prog.rec
|
|
544
544
|
if prog.aggregate == "block":
|
|
545
545
|
blocker = next(d for d in prog.decisions if d.mode == "enforce" and d.action == "block")
|
|
546
|
+
if blocker.outcome == "error":
|
|
547
|
+
return messages.blocked_by_error(rec.tool_id, blocker.rule_id, blocker.error)
|
|
546
548
|
return messages.blocked(rec.tool_id, blocker.rule_id, blocker.sentence)
|
|
547
549
|
if prog.hold_fault is not None:
|
|
548
550
|
return messages.held_no_approval(rec.tool_id, prog.refused.rule_id, prog.refused.sentence)
|
|
@@ -15,6 +15,11 @@ def blocked(tool_id: str, rule_id: str, sentence: str) -> str:
|
|
|
15
15
|
return f"The call to {tool_id} was not performed. Rule {rule_id} blocked it: {_reason(rule_id, sentence)}. {CODA}"
|
|
16
16
|
|
|
17
17
|
|
|
18
|
+
def blocked_by_error(tool_id: str, rule_id: str, error: str | None) -> str:
|
|
19
|
+
return (f"The call to {tool_id} was not performed. It could not be checked against rule {rule_id} "
|
|
20
|
+
f"({error}), which blocks a call it cannot check. {CODA}")
|
|
21
|
+
|
|
22
|
+
|
|
18
23
|
def held_and_refused(tool_id: str, rule_id: str, sentence: str) -> str:
|
|
19
24
|
return (f"The call to {tool_id} was not performed. Rule {rule_id} held it for approval and the approval "
|
|
20
25
|
f"was refused: {_reason(rule_id, sentence)}. {CODA}")
|
|
@@ -102,7 +102,8 @@ class Amiril:
|
|
|
102
102
|
self.registrations: list[AdapterRegistration] = []
|
|
103
103
|
self._seen: set[tuple[str, str | None]] = set()
|
|
104
104
|
self._lock = threading.Lock()
|
|
105
|
-
self._started = client is None
|
|
105
|
+
self._started = client is None # the first wait for registration was taken
|
|
106
|
+
self._client_up = client is None
|
|
106
107
|
self._closed = False
|
|
107
108
|
|
|
108
109
|
# ------------------------------------------------------------ adapters report here
|
|
@@ -137,23 +138,39 @@ class Amiril:
|
|
|
137
138
|
def started(self) -> bool:
|
|
138
139
|
return self._started
|
|
139
140
|
|
|
141
|
+
def start(self) -> None:
|
|
142
|
+
"""Start the control-plane client, once, without waiting for it. The
|
|
143
|
+
plain layer calls it when an agent is created (plain.md 5), so the
|
|
144
|
+
control plane learns the agent before its first run. A no-op without a
|
|
145
|
+
client."""
|
|
146
|
+
if self._client_up:
|
|
147
|
+
return
|
|
148
|
+
with self._lock:
|
|
149
|
+
if self._client_up:
|
|
150
|
+
return
|
|
151
|
+
self._client_up = True
|
|
152
|
+
try:
|
|
153
|
+
self.client.start()
|
|
154
|
+
except Exception: # noqa: BLE001 - kernel.md 10: enforcement goes on with the rules it holds
|
|
155
|
+
log.exception("amiril: the control-plane client failed to start")
|
|
156
|
+
|
|
140
157
|
def ready(self) -> None:
|
|
141
|
-
"""Start the control-plane client
|
|
142
|
-
registration response up to the startup wait (protocol.md 4.2).
|
|
158
|
+
"""Start the control-plane client if it has not started, and wait once
|
|
159
|
+
for its first registration response, up to the startup wait (protocol.md 4.2).
|
|
143
160
|
`instrument()` calls it after registering the adapter, so the first
|
|
144
161
|
registration carries the framework and its coverage; the adapters call
|
|
145
162
|
it before their first tool call, which covers installs without
|
|
146
163
|
`instrument()`. A no-op without a client."""
|
|
147
164
|
if self._started:
|
|
148
165
|
return
|
|
166
|
+
self.start()
|
|
149
167
|
with self._lock:
|
|
150
168
|
if self._started:
|
|
151
169
|
return
|
|
152
170
|
self._started = True
|
|
153
171
|
try:
|
|
154
|
-
self.client.start()
|
|
155
172
|
self.client.wait_ready()
|
|
156
|
-
except Exception: # noqa: BLE001 - kernel.md 10
|
|
173
|
+
except Exception: # noqa: BLE001 - kernel.md 10
|
|
157
174
|
log.exception("amiril: the control-plane client failed to start")
|
|
158
175
|
|
|
159
176
|
def instrument(self, obj: Any) -> Any:
|
|
@@ -204,7 +221,7 @@ class Amiril:
|
|
|
204
221
|
|
|
205
222
|
def flush(self) -> None:
|
|
206
223
|
"""Send queued decision records now (control-plane client only)."""
|
|
207
|
-
if self.client is not None and self.
|
|
224
|
+
if self.client is not None and self._client_up:
|
|
208
225
|
self.client.flush()
|
|
209
226
|
|
|
210
227
|
def shutdown(self) -> None:
|
|
@@ -215,7 +232,7 @@ class Amiril:
|
|
|
215
232
|
if self._closed:
|
|
216
233
|
return
|
|
217
234
|
self._closed = True
|
|
218
|
-
if self.client is not None and self.
|
|
235
|
+
if self.client is not None and self._client_up:
|
|
219
236
|
try:
|
|
220
237
|
self.client.shutdown()
|
|
221
238
|
except Exception: # noqa: BLE001
|
|
@@ -86,6 +86,8 @@ _KERNEL_ZERO = {"records": 0, "runs_open": 0, "sessions": 0, "evicted_runs": 0,
|
|
|
86
86
|
"evicted_records_by_age": 0, "evicted_records_by_size": 0, "over_limit_events": 0}
|
|
87
87
|
_DROP_REASONS = ("queue_full", "rejected", "too_large", "expired", "shutdown", "redacted")
|
|
88
88
|
_COUNT_KEYS = ("allow", "flag", "hold", "block", "error", "would_fire", "shadow_error")
|
|
89
|
+
# protocol.md 5.1: the poll repeats the registration's capabilities, because the bundle depends on them.
|
|
90
|
+
_BUNDLE_PATH = "/v1/rules/bundle" + (f"?capabilities={','.join(CAPABILITIES)}" if CAPABILITIES else "")
|
|
89
91
|
_ETAG_OK = re.compile(r'(W/)?"[^"]+"\Z')
|
|
90
92
|
_REASON = re.compile(r"[a-z][a-z0-9_]{0,63}")
|
|
91
93
|
|
|
@@ -983,7 +985,7 @@ class ControlPlaneClient:
|
|
|
983
985
|
headers = {"If-None-Match": ref[1]} if ref else None
|
|
984
986
|
wait = None
|
|
985
987
|
try:
|
|
986
|
-
resp = self.transport.request("GET",
|
|
988
|
+
resp = self.transport.request("GET", _BUNDLE_PATH, headers=headers)
|
|
987
989
|
except NetworkError as exc:
|
|
988
990
|
self.log_once("poll-network", f"amiril: rule sync failed ({exc}); retrying")
|
|
989
991
|
resp = None
|
|
@@ -17,6 +17,8 @@ from pathlib import Path
|
|
|
17
17
|
from typing import Any
|
|
18
18
|
from urllib.parse import unquote
|
|
19
19
|
|
|
20
|
+
from .surroundings import Surroundings, process_surroundings
|
|
21
|
+
|
|
20
22
|
|
|
21
23
|
@dataclass(frozen=True)
|
|
22
24
|
class Deployment:
|
|
@@ -165,10 +167,12 @@ def _hostname() -> str:
|
|
|
165
167
|
|
|
166
168
|
|
|
167
169
|
def resolve_deployment(env: Mapping[str, str], *, service: str | None = None, version: str | None = None,
|
|
168
|
-
commit: str | None = None, environment: str | None = None
|
|
170
|
+
commit: str | None = None, environment: str | None = None,
|
|
171
|
+
surroundings: Callable[[], Surroundings] = process_surroundings) -> Deployment:
|
|
169
172
|
"""protocol.md 4.4: `service` and `version` as a pair from the first source
|
|
170
173
|
with a non-empty service; the version never falls through to a later
|
|
171
|
-
source. `
|
|
174
|
+
source. `surroundings` is read only when no environment source names the
|
|
175
|
+
service. `service` and `version` arguments override after resolution.
|
|
172
176
|
`commit` is on its own: the argument, else `AMIRIL_COMMIT`, else
|
|
173
177
|
`vcs.ref.head.revision` in `OTEL_RESOURCE_ATTRIBUTES`."""
|
|
174
178
|
sources: list[tuple[str, Callable[[], tuple[str | None, str | None]]]] = [
|
|
@@ -184,12 +188,18 @@ def resolve_deployment(env: Mapping[str, str], *, service: str | None = None, ve
|
|
|
184
188
|
found_service, found_version, source = svc, _first(ver), name
|
|
185
189
|
break
|
|
186
190
|
if found_service is None:
|
|
187
|
-
|
|
191
|
+
local = surroundings()
|
|
192
|
+
if local.project is not None:
|
|
193
|
+
(found_service, found_version), source = local.project, "project"
|
|
194
|
+
elif local.folder is not None:
|
|
195
|
+
found_service, source = local.folder, "folder"
|
|
196
|
+
else:
|
|
197
|
+
found_service = _hostname()
|
|
188
198
|
svc_override, ver_override = _first(service), _first(version)
|
|
189
199
|
if svc_override is not None and ver_override is not None:
|
|
190
200
|
source = "env" # 4.4: both overridden
|
|
191
|
-
elif ver_override is not None and source
|
|
192
|
-
# The schema allows no version with
|
|
201
|
+
elif ver_override is not None and source in ("folder", "host"):
|
|
202
|
+
# The schema allows no version with these sources; an explicit version
|
|
193
203
|
# comes from the caller, so the pair is reported as `env`.
|
|
194
204
|
source = "env"
|
|
195
205
|
return Deployment(
|
|
@@ -96,6 +96,8 @@
|
|
|
96
96
|
"otel",
|
|
97
97
|
"cloud_run",
|
|
98
98
|
"lambda",
|
|
99
|
+
"project",
|
|
100
|
+
"folder",
|
|
99
101
|
"host"
|
|
100
102
|
]
|
|
101
103
|
},
|
|
@@ -116,7 +118,10 @@
|
|
|
116
118
|
"type": "object",
|
|
117
119
|
"properties": {
|
|
118
120
|
"source": {
|
|
119
|
-
"
|
|
121
|
+
"enum": [
|
|
122
|
+
"folder",
|
|
123
|
+
"host"
|
|
124
|
+
]
|
|
120
125
|
}
|
|
121
126
|
},
|
|
122
127
|
"required": [
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""What the `project` and `folder` deployment sources read (spec/protocol.md 4.4).
|
|
2
|
+
|
|
3
|
+
The entry folder is the directory of the script the process was started
|
|
4
|
+
with, or the working directory when there is none or it sits under
|
|
5
|
+
`node_modules` or `site-packages`. The manifest is the nearest
|
|
6
|
+
`pyproject.toml`, walking up from the entry folder, that gives a name.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import tomllib
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
_LAUNCHER_DIRS = frozenset({"node_modules", "site-packages"})
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Surroundings:
|
|
22
|
+
"""The manifest's name and version, and the entry folder's name; None where there is none."""
|
|
23
|
+
|
|
24
|
+
project: tuple[str, str | None] | None
|
|
25
|
+
folder: str | None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
NOTHING = Surroundings(project=None, folder=None)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _text(value: object) -> str | None:
|
|
32
|
+
return value if isinstance(value, str) and value != "" else None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _manifest(path: Path) -> tuple[str, str | None] | None:
|
|
36
|
+
"""`[project]` name and version, else `[tool.poetry]`'s; None when neither names it."""
|
|
37
|
+
try:
|
|
38
|
+
with path.open("rb") as fh:
|
|
39
|
+
data = tomllib.load(fh)
|
|
40
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
41
|
+
return None
|
|
42
|
+
tool = data.get("tool")
|
|
43
|
+
tables = [data.get("project"), tool.get("poetry") if isinstance(tool, dict) else None]
|
|
44
|
+
for table in tables:
|
|
45
|
+
if isinstance(table, dict) and (name := _text(table.get("name"))) is not None:
|
|
46
|
+
return name, _text(table.get("version"))
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def read_surroundings(entry: str | None, cwd: str) -> Surroundings:
|
|
51
|
+
"""The surroundings of a process started with script `entry` (None for none) in `cwd`."""
|
|
52
|
+
start = Path(cwd).absolute()
|
|
53
|
+
if entry is not None:
|
|
54
|
+
script = Path(entry)
|
|
55
|
+
script = script if script.is_absolute() else start / script
|
|
56
|
+
if script.is_file() and not _LAUNCHER_DIRS.intersection(script.parts):
|
|
57
|
+
start = script.parent
|
|
58
|
+
project = None
|
|
59
|
+
for directory in (start, *start.parents):
|
|
60
|
+
candidate = directory / "pyproject.toml"
|
|
61
|
+
if candidate.is_file() and (project := _manifest(candidate)) is not None:
|
|
62
|
+
break
|
|
63
|
+
return Surroundings(project=project, folder=start.name or None)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def process_surroundings() -> Surroundings:
|
|
67
|
+
"""This process's surroundings, from `sys.argv[0]` and the working directory."""
|
|
68
|
+
try:
|
|
69
|
+
return read_surroundings(_text(sys.argv[0] if sys.argv else None), os.getcwd())
|
|
70
|
+
except OSError:
|
|
71
|
+
return NOTHING
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
__all__ = ["NOTHING", "Surroundings", "process_surroundings", "read_surroundings"]
|
|
@@ -5,7 +5,8 @@ a framework. Behaviour is `spec/edoc.md`, `spec/kernel.md` and
|
|
|
5
5
|
|
|
6
6
|
Engine: `Engine`, `load_document` (validate, raising `DocumentError` with the
|
|
7
7
|
`{path, code, message}` problems), `validate_document`, `render_sentence`,
|
|
8
|
-
`customer_view`, `Decision`, `EvalError
|
|
8
|
+
`customer_view`, `Decision`, `EvalError`, `SCHEMA_ID`, `CAPABILITIES` (the
|
|
9
|
+
additions to the rule document this core reads, edoc.md 13).
|
|
9
10
|
|
|
10
11
|
Kernel: `Guard` (`before_call`, `abefore_call`, `after_call`, `end_run`,
|
|
11
12
|
`end_session`, `swap`, `history_report`, `drain_counts`, `record_fault`),
|
|
@@ -24,7 +25,7 @@ from ._engine.engine import EMPTY_DOCUMENT, Engine, LoadedDocument, load_documen
|
|
|
24
25
|
from ._engine.numbers import decode_nonfinite, dumps_line, encode_nonfinite, fmt_number
|
|
25
26
|
from ._engine.rules import DEFAULT_HOLD_TIMEOUT_MS, Decision
|
|
26
27
|
from ._engine.sentence import customer_view, render_sentence
|
|
27
|
-
from ._engine.validate import SCHEMA_ID, DocumentError, validate_document
|
|
28
|
+
from ._engine.validate import CAPABILITIES, SCHEMA_ID, DocumentError, validate_document
|
|
28
29
|
from ._engine.values import ABSENT, MISSING, EvalError
|
|
29
30
|
from ._kernel.bundle import BundleError, PreparedBundle, is_bundle, prepare_bundle
|
|
30
31
|
from ._kernel.coerce import coerce_args
|
|
@@ -46,6 +47,7 @@ __all__ = [
|
|
|
46
47
|
"ABSENT",
|
|
47
48
|
"BatchTracker",
|
|
48
49
|
"BundleError",
|
|
50
|
+
"CAPABILITIES",
|
|
49
51
|
"CallIdMinter",
|
|
50
52
|
"CallRecord",
|
|
51
53
|
"DEFAULT_HOLD_TIMEOUT_MS",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# amiril 0.
|
|
1
|
+
# amiril 0.1.0: docs
|
|
2
2
|
|
|
3
|
-
These pages describe amiril 0.
|
|
3
|
+
These pages describe amiril 0.1.0, the version installed beside this
|
|
4
4
|
file. They were copied from the Amiril SDK repository when the package was
|
|
5
5
|
built, so they match the code you have. Where a page shows Python and
|
|
6
6
|
TypeScript side by side, this package is the Python one.
|
|
@@ -139,3 +139,7 @@ not approved.
|
|
|
139
139
|
preloading). There, instrument the app before building its `Runner`, or
|
|
140
140
|
pass the `Runner` to `instrument()`.
|
|
141
141
|
- Live (streaming) mode has not been tested.
|
|
142
|
+
|
|
143
|
+
## Feedback
|
|
144
|
+
|
|
145
|
+
Send us any feedback, from a person or an AI assistant: `POST https://api.amiril.ai/v1/feedback` with a JSON body such as `{"message": "..."}`, no sign-in needed. Connected to Amiril's MCP server, an assistant can call `amiril_feedback_send` instead.
|
|
@@ -152,3 +152,7 @@ keep running. With no resolver a hold is refused.
|
|
|
152
152
|
exception type, tuple or typed handler then also catches errors it
|
|
153
153
|
would not, and the coverage report says so.
|
|
154
154
|
- History is kept in memory: a restart forgets earlier calls.
|
|
155
|
+
|
|
156
|
+
## Feedback
|
|
157
|
+
|
|
158
|
+
Send us any feedback, from a person or an AI assistant: `POST https://api.amiril.ai/v1/feedback` with a JSON body such as `{"message": "..."}`, no sign-in needed. Connected to Amiril's MCP server, an assistant can call `amiril_feedback_send` instead.
|
|
@@ -236,3 +236,7 @@ TypeScript, records every decision and blocks nothing. A rule's own
|
|
|
236
236
|
On a runtime without it, call `run.before` and `run.after` yourself.
|
|
237
237
|
- A run you start and never end is closed after it has been idle for a
|
|
238
238
|
while, and rules that wait for the end of a run do not fire for it.
|
|
239
|
+
|
|
240
|
+
## Feedback
|
|
241
|
+
|
|
242
|
+
Send us any feedback, from a person or an AI assistant: `POST https://api.amiril.ai/v1/feedback` with a JSON body such as `{"message": "..."}`, no sign-in needed. Connected to Amiril's MCP server, an assistant can call `amiril_feedback_send` instead.
|
|
@@ -201,3 +201,7 @@ tools: [ 'issue_payment' ]
|
|
|
201
201
|
you.
|
|
202
202
|
- Rules that wait for the end of a run need the framework to say when a
|
|
203
203
|
run ends, on failure and on cancel as well as on success.
|
|
204
|
+
|
|
205
|
+
## Feedback
|
|
206
|
+
|
|
207
|
+
Send us any feedback, from a person or an AI assistant: `POST https://api.amiril.ai/v1/feedback` with a JSON body such as `{"message": "..."}`, no sign-in needed. Connected to Amiril's MCP server, an assistant can call `amiril_feedback_send` instead.
|
|
@@ -218,7 +218,8 @@ class Agent:
|
|
|
218
218
|
return self._handle().settings
|
|
219
219
|
|
|
220
220
|
def _register(self) -> None:
|
|
221
|
-
"""Report the agent and its tools (protocol.md 4.3)
|
|
221
|
+
"""Report the agent and its tools (protocol.md 4.3) and start the
|
|
222
|
+
control-plane client without waiting (plain.md 5). Sent again when a
|
|
222
223
|
tool is declared; the client coalesces (protocol.md 4.5)."""
|
|
223
224
|
try:
|
|
224
225
|
own = coverage_name(self.name)
|
|
@@ -226,7 +227,8 @@ class Agent:
|
|
|
226
227
|
report.agents.append({"name": own, "root": True, "declared_id": None, "tools": list(self._tools)})
|
|
227
228
|
report.tools.extend(tool_entry(t.name, own, t.description, t.schema, t.declared_id)
|
|
228
229
|
for t in self._tools.values())
|
|
229
|
-
self._handle()
|
|
230
|
+
handle = self._handle()
|
|
231
|
+
handle.register(AdapterRegistration(
|
|
230
232
|
adapter=ADAPTER,
|
|
231
233
|
adapter_version=__version__,
|
|
232
234
|
framework=None,
|
|
@@ -236,6 +238,7 @@ class Agent:
|
|
|
236
238
|
coverage=report,
|
|
237
239
|
key=self.name or "agent",
|
|
238
240
|
))
|
|
241
|
+
handle.start()
|
|
239
242
|
except Exception as exc: # noqa: BLE001 - kernel.md 10
|
|
240
243
|
report_fault(self._guard(), exc, None, None, None, agent_id=self.name or "agent")
|
|
241
244
|
|
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
"""`hour_utc` (spec/edoc.md 6.6 and 8.10) and the UTC rendering of `context.now` (10.3)."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import datetime as _dt
|
|
6
|
-
import re
|
|
7
|
-
from decimal import ROUND_HALF_EVEN, Decimal, localcontext
|
|
8
|
-
|
|
9
|
-
# ASCII digits only (edoc.md 8.10): Python's \d would also match other scripts' digits.
|
|
10
|
-
_ISO = re.compile(
|
|
11
|
-
r"([0-9]{4})-([0-9]{2})-([0-9]{2})"
|
|
12
|
-
r"(?:[T ]([0-9]{2}):([0-9]{2})(?::([0-9]{2})(?:[.,]([0-9]{1,6}))?)?)?"
|
|
13
|
-
r"(Z|[+-][0-9]{2}:[0-9]{2})?"
|
|
14
|
-
)
|
|
15
|
-
_EPOCH = _dt.datetime(1970, 1, 1, tzinfo=_dt.timezone.utc)
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def round_to_microsecond(seconds: float) -> int:
|
|
19
|
-
"""Epoch seconds to whole microseconds, half to even, on the exact decimal
|
|
20
|
-
expansion of the double (a float multiplication would move boundary values)."""
|
|
21
|
-
with localcontext() as c:
|
|
22
|
-
c.prec = 80
|
|
23
|
-
return int((Decimal(seconds) * 1_000_000).quantize(Decimal(1), rounding=ROUND_HALF_EVEN))
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def utc_datetime(seconds: float) -> _dt.datetime:
|
|
27
|
-
"""The UTC time of epoch seconds rounded to the nearest microsecond.
|
|
28
|
-
Raises OverflowError outside the years 1 to 9999."""
|
|
29
|
-
return _EPOCH + _dt.timedelta(microseconds=round_to_microsecond(seconds))
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
def hour_of_epoch(seconds: float) -> int | None:
|
|
33
|
-
"""The UTC hour of epoch seconds, floored to a second; None when out of range."""
|
|
34
|
-
try:
|
|
35
|
-
us = round_to_microsecond(seconds)
|
|
36
|
-
dt = _EPOCH + _dt.timedelta(seconds=us // 1_000_000)
|
|
37
|
-
except (OverflowError, ValueError, ArithmeticError): # infinite, NaN or beyond the years 1 to 9999
|
|
38
|
-
return None
|
|
39
|
-
return dt.hour
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
def hour_of_iso(text: str) -> int | None:
|
|
43
|
-
"""The UTC hour of an ISO-8601 time of the shape in 8.10; None when malformed."""
|
|
44
|
-
m = _ISO.fullmatch(text)
|
|
45
|
-
if m is None:
|
|
46
|
-
return None
|
|
47
|
-
y, mo, d = int(m[1]), int(m[2]), int(m[3])
|
|
48
|
-
hh = int(m[4]) if m[4] is not None else 0
|
|
49
|
-
mm = int(m[5]) if m[5] is not None else 0
|
|
50
|
-
ss = int(m[6]) if m[6] is not None else 0
|
|
51
|
-
try:
|
|
52
|
-
_dt.date(y, mo, d)
|
|
53
|
-
except ValueError:
|
|
54
|
-
return None
|
|
55
|
-
if hh > 23 or mm > 59 or ss > 59:
|
|
56
|
-
return None
|
|
57
|
-
minutes = hh * 60 + mm
|
|
58
|
-
off = m[8]
|
|
59
|
-
if off and off != "Z":
|
|
60
|
-
oh, om = int(off[1:3]), int(off[4:6])
|
|
61
|
-
if oh > 23 or om > 59:
|
|
62
|
-
return None
|
|
63
|
-
delta = oh * 60 + om
|
|
64
|
-
minutes = minutes - delta if off[0] == "+" else minutes + delta
|
|
65
|
-
return (minutes // 60) % 24
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
def render_now(seconds: float) -> str:
|
|
69
|
-
"""`YYYY-MM-DDTHH:MM:SSZ` of epoch seconds rounded to the nearest microsecond."""
|
|
70
|
-
# Not strftime: glibc's %Y does not pad a year below 1000, macOS's does.
|
|
71
|
-
t = utc_datetime(seconds)
|
|
72
|
-
return f"{t.year:04d}-{t.month:02d}-{t.day:02d}T{t.hour:02d}:{t.minute:02d}:{t.second:02d}Z"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/decisions.response.schema.json
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/heartbeat.response.schema.json
RENAMED
|
File without changes
|
{amiril-0.0.0.dev0 → amiril-0.1.0}/src/amiril/control/schemas/hold-create.request.schema.json
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|