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.
Files changed (64) hide show
  1. amiril/__init__.py +51 -0
  2. amiril/_adapters.py +399 -0
  3. amiril/_engine/__init__.py +1 -0
  4. amiril/_engine/engine.py +113 -0
  5. amiril/_engine/expr.py +653 -0
  6. amiril/_engine/numbers.py +111 -0
  7. amiril/_engine/regex.py +262 -0
  8. amiril/_engine/rules.py +192 -0
  9. amiril/_engine/sentence.py +251 -0
  10. amiril/_engine/timeparse.py +72 -0
  11. amiril/_engine/validate.py +863 -0
  12. amiril/_engine/values.py +273 -0
  13. amiril/_kernel/__init__.py +1 -0
  14. amiril/_kernel/bundle.py +245 -0
  15. amiril/_kernel/coerce.py +103 -0
  16. amiril/_kernel/events.py +87 -0
  17. amiril/_kernel/guard.py +1196 -0
  18. amiril/_kernel/ids.py +66 -0
  19. amiril/_kernel/messages.py +30 -0
  20. amiril/_kernel/normalise.py +165 -0
  21. amiril/_kernel/records.py +131 -0
  22. amiril/_kernel/store.py +661 -0
  23. amiril/_runtime.py +617 -0
  24. amiril/adk.py +577 -0
  25. amiril/control/__init__.py +25 -0
  26. amiril/control/_delivery.py +567 -0
  27. amiril/control/_disk.py +418 -0
  28. amiril/control/_holds.py +252 -0
  29. amiril/control/_jsonschema.py +265 -0
  30. amiril/control/_pathc.py +85 -0
  31. amiril/control/_records.py +293 -0
  32. amiril/control/_redact.py +79 -0
  33. amiril/control/_transport.py +184 -0
  34. amiril/control/_wire.py +73 -0
  35. amiril/control/client.py +1313 -0
  36. amiril/control/config.py +204 -0
  37. amiril/control/schemas/bundle.response.schema.json +22 -0
  38. amiril/control/schemas/common.schema.json +593 -0
  39. amiril/control/schemas/decisions.request.schema.json +558 -0
  40. amiril/control/schemas/decisions.response.schema.json +23 -0
  41. amiril/control/schemas/error.response.schema.json +54 -0
  42. amiril/control/schemas/heartbeat.request.schema.json +305 -0
  43. amiril/control/schemas/heartbeat.response.schema.json +34 -0
  44. amiril/control/schemas/hold-create.request.schema.json +138 -0
  45. amiril/control/schemas/hold.response.schema.json +226 -0
  46. amiril/control/schemas/installation-register.request.schema.json +492 -0
  47. amiril/control/schemas/installation-register.response.schema.json +85 -0
  48. amiril/core.py +89 -0
  49. amiril/docs/README.md +14 -0
  50. amiril/docs/durability/langgraph.md +292 -0
  51. amiril/docs/frameworks/adk.md +141 -0
  52. amiril/docs/frameworks/langgraph.md +154 -0
  53. amiril/docs/frameworks/no-framework.md +238 -0
  54. amiril/docs/frameworks/write-an-adapter.md +203 -0
  55. amiril/durable.py +342 -0
  56. amiril/langgraph.py +746 -0
  57. amiril/plain.py +454 -0
  58. amiril/py.typed +0 -0
  59. amiril/seams.py +357 -0
  60. amiril/testing.py +21 -0
  61. amiril-0.0.0.dev0.dist-info/METADATA +114 -0
  62. amiril-0.0.0.dev0.dist-info/RECORD +64 -0
  63. amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
  64. amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,251 @@
1
+ """Sentences (spec/edoc.md, section 10): the decision sentence compared in
2
+ conformance (10.1 to 10.4) and the customer-facing structure (10.6). The
3
+ model-facing message is the kernel's (`_kernel/messages.py`)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from typing import Any
9
+
10
+ from .numbers import fmt_number, json_text
11
+ from .timeparse import render_now
12
+ from .validate import label_of_path, read_path_of, tool_label
13
+
14
+ _PLACEHOLDER = re.compile(r"\{([^{}]+)\}")
15
+ MAX_STRING = 120
16
+
17
+
18
+ def render_value(v: Any, quoted: bool, entry: dict | None = None) -> str:
19
+ """Section 10.3. `quoted` wraps a top-level string in double quotes."""
20
+ if entry is not None:
21
+ if entry.get("missing"):
22
+ return "none"
23
+ if entry.get("absent"):
24
+ return "absent"
25
+ if v is None:
26
+ return "null"
27
+ t = type(v)
28
+ if t is bool:
29
+ return "true" if v else "false"
30
+ if t is float or t is int:
31
+ if entry is not None and entry.get("path") == "context.now":
32
+ try:
33
+ return render_now(v)
34
+ except (OverflowError, ValueError, ArithmeticError):
35
+ return fmt_number(v)
36
+ return fmt_number(v)
37
+ if t is str:
38
+ s = v if len(v) <= MAX_STRING else v[:MAX_STRING] + "…"
39
+ return f'"{s}"' if quoted else s
40
+ if t is list:
41
+ items = [render_value(x, False) for x in v]
42
+ if entry is not None and entry.get("truncated"):
43
+ return ", ".join(items) + f" and {int(entry['truncated']) - len(v)} more"
44
+ if not items:
45
+ return "nothing"
46
+ if len(items) == 1:
47
+ return items[0]
48
+ return ", ".join(items[:-1]) + " and " + items[-1]
49
+ if t is dict:
50
+ return json_text(v)
51
+ return str(v)
52
+
53
+
54
+ def label(entry: dict) -> str:
55
+ """Section 10.1: the entry's name, else its path without the known prefixes."""
56
+ name = entry.get("name")
57
+ if name:
58
+ return name
59
+ return label_of_path(entry["path"])
60
+
61
+
62
+ def template_for(sentence: Any, outcome: str) -> str | None:
63
+ """Section 10.2: which template applies to an outcome, if any."""
64
+ if sentence is None:
65
+ return None
66
+ if type(sentence) is str:
67
+ return sentence if outcome in ("violate", "band") else None
68
+ key = "fail" if outcome in ("violate", "band") else "pass" if outcome == "pass" else None
69
+ return sentence.get(key) if key else None
70
+
71
+
72
+ def _find(name: str, evidence: list[dict]) -> dict | None:
73
+ for e in evidence:
74
+ if e["path"] == name:
75
+ return e
76
+ for e in evidence:
77
+ if e.get("name") == name:
78
+ return e
79
+ for e in evidence:
80
+ if label(e) == name:
81
+ return e
82
+ return None
83
+
84
+
85
+ def render_sentence(rule: dict, outcome: str, evidence: list[dict]) -> str:
86
+ """Section 10.1: the decision sentence."""
87
+ template = template_for(rule.get("sentence"), outcome)
88
+ placed: set[int] = set()
89
+ if template is not None:
90
+ def fill(m: re.Match) -> str:
91
+ e = _find(m.group(1), evidence)
92
+ if e is None:
93
+ return "?"
94
+ placed.add(id(e))
95
+ return render_value(e.get("value"), False, e)
96
+
97
+ body = _PLACEHOLDER.sub(fill, template)
98
+ else:
99
+ body = rule.get("description") or rule["id"]
100
+ tail = [f"{label(e)} {render_value(e.get('value'), True, e)}" for e in evidence if id(e) not in placed]
101
+ text = body + (" (" + "; ".join(tail) + ")" if tail else "")
102
+ return text.rstrip(".") + "."
103
+
104
+
105
+ # ---------------------------------------------------------------- customer-facing (10.6)
106
+
107
+ ACTION_WORDS = {"allow": "allowed", "flag": "flagged", "hold": "held for approval", "block": "blocked"}
108
+
109
+
110
+ def customer_view(rule: dict, decision: Any) -> dict:
111
+ """Section 10.6: `{"action", "outcome", "body"}` for a person. `decision`
112
+ has `action`, `outcome`, `evidence`, `error` and `sentence`."""
113
+ outcome = decision.outcome
114
+ evidence = decision.evidence
115
+ if outcome == "pass":
116
+ phrase = "The rule holds."
117
+ elif outcome in ("violate", "band"):
118
+ phrase = "The rule is violated."
119
+ if outcome == "band":
120
+ band = _band_of(rule, decision.action)
121
+ phrase += " " + (f"The value falls in the band up to {fmt_number(band['max'])}."
122
+ if band is not None and "max" in band else "The value is above every band.")
123
+ elif outcome in ("missing", "skip"):
124
+ clauses = [_missing_clause(rule, e) for e in evidence if e.get("missing")]
125
+ phrase = " ".join(clauses)
126
+ if outcome == "skip":
127
+ phrase = (phrase + " " if phrase else "") + "The rule does not apply."
128
+ else:
129
+ phrase = f"The rule could not be evaluated: {decision.error}."
130
+ template = template_for(rule.get("sentence"), outcome)
131
+ placed: set[int] = set()
132
+ if template is not None:
133
+ def fill(m: re.Match) -> str:
134
+ e = _find(m.group(1), evidence)
135
+ if e is None:
136
+ return "?"
137
+ placed.add(id(e))
138
+ return render_value(e.get("value"), False, e)
139
+
140
+ body = _PLACEHOLDER.sub(fill, template)
141
+ else:
142
+ body = rule.get("description") or rule["id"]
143
+ parts = [body.rstrip(".")]
144
+ for e in evidence:
145
+ if id(e) in placed:
146
+ continue
147
+ parts.append(_evidence_words(e))
148
+ return {"action": ACTION_WORDS[decision.action], "outcome": phrase, "body": "; ".join(parts) + "."}
149
+
150
+
151
+ def _band_of(rule: dict, action: str) -> dict | None:
152
+ bands = rule.get("bands")
153
+ if type(bands) is not dict:
154
+ return None
155
+ for band in bands["bands"]:
156
+ if band["action"] == action:
157
+ return band
158
+ return None
159
+
160
+
161
+ def _evidence_words(e: dict) -> str:
162
+ path = e["path"]
163
+ lab = label(e)
164
+ if e.get("missing"):
165
+ return f"{lab} not found"
166
+ if e.get("absent"):
167
+ return f"{lab} not given"
168
+ if path.startswith("history.") and path.endswith(".exists"):
169
+ tool = _tool_words(path[len("history."):-len(".exists")])
170
+ return f"a {tool} call exists" if e.get("value") else f"no {tool} call exists"
171
+ if path.startswith("history.") and path.endswith(".count"):
172
+ tool = _tool_words(path[len("history."):-len(".count")])
173
+ return f"{render_value(e.get('value'), False, e)} {tool} calls"
174
+ if path.startswith("history.prev."):
175
+ return f"the previous call's {path[len('history.prev.'):]} was {render_value(e.get('value'), True, e)}"
176
+ return f"{lab} {render_value(e.get('value'), True, e)}"
177
+
178
+
179
+ def _tool_words(label_text: str) -> str:
180
+ if label_text == "any_tool":
181
+ return "any tool"
182
+ return " or ".join(label_text.split("|"))
183
+
184
+
185
+ def _missing_clause(rule: dict, entry: dict) -> str:
186
+ path = entry["path"]
187
+ scope = rule.get("scope", "run")
188
+ if path.startswith("history.prev."):
189
+ return "No earlier call in this run." if scope == "run" else \
190
+ "No earlier call in this session." if scope == "session" else \
191
+ f"No earlier call with the same {scope.split(':', 1)[1]}."
192
+ sel = _selection_for(rule, path)
193
+ if sel is None:
194
+ return f"No {label(entry)} was found."
195
+ status = sel.get("status", "ok")
196
+ if status == "ok":
197
+ status_words = " completed"
198
+ elif type(status) is str and status != "any":
199
+ status_words = f" {status}"
200
+ else:
201
+ status_words = ""
202
+ tool = sel.get("tool")
203
+ tool_words = "any tool" if tool == "*" else " or ".join(tool) if type(tool) is list else str(tool)
204
+ text = f"No{status_words} {tool_words} call"
205
+ join = sel.get("join")
206
+ if join is not None:
207
+ names = [join] if type(join) is str else list(join)
208
+ text += " with the same " + " and ".join(names)
209
+ sel_scope = sel.get("scope", scope)
210
+ if sel_scope == "run":
211
+ text += " in this run"
212
+ elif sel_scope == "session":
213
+ text += " in this session"
214
+ else:
215
+ text += f" with the same {sel_scope.split(':', 1)[1]}"
216
+ return text + " was found."
217
+
218
+
219
+ def _selection_for(rule: dict, path: str) -> dict | None:
220
+ """The selection whose `prior` or `agg` records under `path`, found in the rule's text."""
221
+ found: list[dict] = []
222
+
223
+ def walk(node: Any) -> None:
224
+ if type(node) is not dict or len(node) != 1:
225
+ return
226
+ (op, arg), = node.items()
227
+ if read_path_of(node) == path:
228
+ if op == "prior" and type(arg) is dict:
229
+ found.append(arg)
230
+ elif op == "agg" and type(arg) is dict and type(arg.get("of")) is dict:
231
+ found.append(arg["of"].get("calls") or {})
232
+ if type(arg) is list:
233
+ for n in arg:
234
+ walk(n)
235
+ elif type(arg) is dict:
236
+ if op in ("calls", "prior"):
237
+ walk(arg.get("where"))
238
+ elif op == "agg":
239
+ for n in arg.get("with") or []:
240
+ walk(n)
241
+ else:
242
+ walk(arg)
243
+
244
+ for expr in list((rule.get("let") or {}).values()) + [rule.get("when"), rule.get("assert")]:
245
+ walk(expr)
246
+ if type(rule.get("bands")) is dict:
247
+ walk(rule["bands"].get("value"))
248
+ return found[0] if found else None
249
+
250
+
251
+ __all__ = ["customer_view", "label", "render_sentence", "render_value", "template_for", "tool_label"]
@@ -0,0 +1,72 @@
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"