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,79 @@
1
+ """The redaction hook (spec/protocol.md 9): called on every decision record,
2
+ hold object, coverage report and path C attribute set before any byte leaves
3
+ the process. It may change values; a changed identifier counts as a failure,
4
+ exactly like a hook that threw or returned None."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import copy
9
+ from collections.abc import Callable
10
+ from typing import Any
11
+
12
+ RECORD_IDS = ("id", "call", "trace", "rule", "run_id", "root_run_id", "session_id", "tool", "agent")
13
+ HOLD_IDS = ("rule", "call", "trace", "run_id", "root_run_id", "session_id", "tool", "agent")
14
+ PATH_C_IDS = ("amiril.rule", "amiril.rules", "amiril.rule_version", "amiril.call_id", "amiril.attempt",
15
+ "amiril.hold_id")
16
+
17
+ _MISSING = object()
18
+
19
+
20
+ class RedactionFailed(Exception):
21
+ """The hook threw, returned None or changed an identifier."""
22
+
23
+
24
+ def _same(before: dict, after: dict, keys: tuple[str, ...]) -> bool:
25
+ return all(before.get(k, _MISSING) == after.get(k, _MISSING) for k in keys)
26
+
27
+
28
+ def apply(hook: Callable[[Any], Any] | None, value: dict, identifiers: tuple[str, ...]) -> dict:
29
+ """Run the hook on a copy of `value` and return what to send; raise
30
+ `RedactionFailed` when the result cannot be sent."""
31
+ if hook is None:
32
+ return value
33
+ try:
34
+ out = hook(copy.deepcopy(value))
35
+ except Exception as exc: # noqa: BLE001 - a customer hook may raise anything
36
+ raise RedactionFailed(f"the redaction hook raised {type(exc).__name__}") from exc
37
+ if out is None:
38
+ raise RedactionFailed("the redaction hook returned None")
39
+ if not isinstance(out, dict):
40
+ raise RedactionFailed(f"the redaction hook returned {type(out).__name__}, not an object")
41
+ if not _same(value, out, identifiers):
42
+ raise RedactionFailed("the redaction hook changed an identifier")
43
+ return out
44
+
45
+
46
+ def _coverage_ids(report: dict) -> tuple:
47
+ agents = tuple((a.get("name"), a.get("root"), a.get("declared_id"), a.get("register_as"),
48
+ tuple(a.get("tools") or ()))
49
+ for a in report.get("agents") or ())
50
+ tools = tuple((t.get("name"), t.get("declared_id"), t.get("agent")) for t in report.get("tools") or ())
51
+ uncovered = tuple((u.get("kind"), u.get("name"), u.get("agent")) for u in report.get("uncovered") or ())
52
+ return agents, tools, uncovered
53
+
54
+
55
+ def apply_coverage(hook: Callable[[Any], Any] | None, report: dict) -> dict:
56
+ """protocol.md 4.3 and 9: on failure, send the report with every value the
57
+ hook could have changed removed (`schema` null with `schema_omitted:
58
+ "redacted"`, `description` null) and `redaction_failed: true`."""
59
+ if hook is None:
60
+ return report
61
+ try:
62
+ out = hook(copy.deepcopy(report))
63
+ if not isinstance(out, dict) or _coverage_ids(out) != _coverage_ids(report):
64
+ raise RedactionFailed("changed")
65
+ for key in ("generated_at", "truncated", "redaction_failed"):
66
+ if out.get(key, _MISSING) != report.get(key, _MISSING):
67
+ raise RedactionFailed("changed")
68
+ return out
69
+ except Exception: # noqa: BLE001 - any failure sends the stripped report
70
+ stripped = copy.deepcopy(report)
71
+ for tool in stripped.get("tools") or ():
72
+ tool["description"] = None
73
+ tool["schema"] = None
74
+ tool["schema_omitted"] = "redacted"
75
+ stripped["redaction_failed"] = True
76
+ return stripped
77
+
78
+
79
+ __all__ = ["HOLD_IDS", "PATH_C_IDS", "RECORD_IDS", "RedactionFailed", "apply", "apply_coverage"]
@@ -0,0 +1,184 @@
1
+ """HTTPS transport over `http.client` (spec/protocol.md 2): Bearer key, JSON
2
+ bodies gzipped above 1 KiB, connect and request timeouts, `Retry-After`.
3
+ One connection per request; nothing here retries, the callers own the
4
+ retry classes because each operation has its own (2.5)."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import base64
9
+ import logging
10
+ import http.client
11
+ import json
12
+ import socket
13
+ import ssl
14
+ import urllib.request
15
+ import zlib
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+ from urllib.parse import unquote, urlsplit
19
+
20
+ from ._wire import dumps, encode_body
21
+
22
+ log = logging.getLogger("amiril")
23
+
24
+ LOOPBACK = frozenset({"localhost", "127.0.0.1", "::1"})
25
+ MAX_RESPONSE_BYTES = 32 * 1024 * 1024 # a response body, on the wire and again after gunzip
26
+
27
+
28
+ class NetworkError(Exception):
29
+ """No usable response: connection failure, timeout, or an unreadable body."""
30
+
31
+
32
+ class EndpointError(ValueError):
33
+ """The endpoint cannot be used (not https, or not a URL)."""
34
+
35
+
36
+ @dataclass
37
+ class Response:
38
+ status: int
39
+ body: dict | None
40
+ headers: dict[str, str] = field(default_factory=dict)
41
+
42
+ @property
43
+ def retry_after(self) -> float | None:
44
+ """`Retry-After` in seconds when present and numeric (2.5)."""
45
+ raw = self.headers.get("retry-after")
46
+ if raw is None:
47
+ return None
48
+ try:
49
+ value = float(raw.strip())
50
+ except ValueError:
51
+ return None
52
+ return value if value >= 0 else None
53
+
54
+ @property
55
+ def ok(self) -> bool:
56
+ return 200 <= self.status < 300 or self.status == 304
57
+
58
+ @property
59
+ def error_text(self) -> str:
60
+ err = (self.body or {}).get("error") if isinstance(self.body, dict) else None
61
+ if isinstance(err, dict):
62
+ return f"{err.get('code')}: {err.get('message')}"
63
+ return f"HTTP {self.status}"
64
+
65
+
66
+ class Transport:
67
+ """Sends one request and returns a `Response`, or raises `NetworkError`."""
68
+
69
+ def __init__(self, endpoint: str, api_key: str, user_agent: str, connect_timeout: float,
70
+ request_timeout: float) -> None:
71
+ parts = urlsplit(endpoint)
72
+ if parts.scheme not in ("https", "http") or not parts.hostname:
73
+ raise EndpointError(f"endpoint must be an https URL, got {endpoint!r}")
74
+ if parts.scheme == "http" and parts.hostname not in LOOPBACK:
75
+ raise EndpointError(f"endpoint must use https (plain http is accepted for loopback only): {endpoint!r}")
76
+ self.scheme = parts.scheme
77
+ self.host = parts.hostname
78
+ self.port = parts.port
79
+ self.base_path = parts.path.rstrip("/")
80
+ self.api_key = api_key
81
+ self.user_agent = user_agent
82
+ self.connect_timeout = connect_timeout
83
+ self.request_timeout = request_timeout
84
+ self._ssl = ssl.create_default_context() if self.scheme == "https" else None
85
+ self._proxy_warned = False
86
+
87
+ def __repr__(self) -> str:
88
+ return f"Transport({self.scheme}://{self.host}{':' + str(self.port) if self.port else ''}{self.base_path})"
89
+
90
+ def _proxy(self) -> tuple[str, int, dict[str, str]] | None:
91
+ """The proxy for this endpoint from the environment (`HTTPS_PROXY` for
92
+ https, `HTTP_PROXY` for http, `NO_PROXY` to bypass), or None. Read from
93
+ the environment only, not a platform's system settings, so a server
94
+ behaves the same everywhere."""
95
+ proxies = urllib.request.getproxies_environment()
96
+ url = proxies.get(self.scheme)
97
+ if not url or urllib.request.proxy_bypass_environment(self.host, proxies):
98
+ return None
99
+ parts = urlsplit(url if "://" in url else f"http://{url}")
100
+ if parts.scheme != "http":
101
+ # TLS to the proxy itself is not supported; sending CONNECT and Proxy-Authorization in
102
+ # cleartext to a proxy configured as https would be wrong, so requests fail visibly.
103
+ if not self._proxy_warned:
104
+ self._proxy_warned = True
105
+ log.warning("amiril: the %s proxy %s:%s uses %s://, which is not supported (only http:// "
106
+ "proxies are); requests fail until it is changed or NO_PROXY covers %s",
107
+ self.scheme, parts.hostname, parts.port, parts.scheme, self.host)
108
+ raise NetworkError(f"unsupported proxy scheme {parts.scheme!r}")
109
+ if not parts.hostname:
110
+ return None
111
+ headers: dict[str, str] = {}
112
+ if parts.username is not None:
113
+ cred = f"{unquote(parts.username)}:{unquote(parts.password or '')}".encode()
114
+ headers["Proxy-Authorization"] = "Basic " + base64.b64encode(cred).decode("ascii")
115
+ return parts.hostname, parts.port or 80, headers
116
+
117
+ def request(self, method: str, path: str, body: Any = None, *, headers: dict[str, str] | None = None,
118
+ timeout: float | None = None, raw: bytes | None = None) -> Response:
119
+ """`body` is a JSON value; `raw` pre-serialised JSON bytes (an immutable batch)."""
120
+ hdrs = {
121
+ "Authorization": f"Bearer {self.api_key}",
122
+ "User-Agent": self.user_agent,
123
+ "Accept": "application/json",
124
+ "Accept-Encoding": "gzip",
125
+ }
126
+ data: bytes | None = None
127
+ if raw is None and body is not None:
128
+ raw = dumps(body)
129
+ if raw is not None:
130
+ data, zipped = encode_body(raw)
131
+ hdrs["Content-Type"] = "application/json"
132
+ if zipped:
133
+ hdrs["Content-Encoding"] = "gzip"
134
+ if headers:
135
+ hdrs.update(headers)
136
+ read_timeout = timeout if timeout is not None else self.request_timeout
137
+ connect_timeout = min(self.connect_timeout, read_timeout)
138
+ proxy = self._proxy()
139
+ host, port = (proxy[0], proxy[1]) if proxy else (self.host, self.port)
140
+ conn: http.client.HTTPConnection
141
+ if self.scheme == "https":
142
+ conn = http.client.HTTPSConnection(host, port, timeout=connect_timeout, context=self._ssl)
143
+ else:
144
+ conn = http.client.HTTPConnection(host, port, timeout=connect_timeout)
145
+ if proxy:
146
+ # CONNECT tunnel; for https the TLS handshake then runs with the endpoint's name.
147
+ conn.set_tunnel(self.host, self.port or (443 if self.scheme == "https" else 80), headers=proxy[2])
148
+ try:
149
+ conn.connect()
150
+ if conn.sock is not None:
151
+ conn.sock.settimeout(read_timeout)
152
+ conn.request(method, self.base_path + path, body=data, headers=hdrs)
153
+ resp = conn.getresponse()
154
+ payload = resp.read(MAX_RESPONSE_BYTES + 1)
155
+ if len(payload) > MAX_RESPONSE_BYTES:
156
+ raise NetworkError(f"response larger than {MAX_RESPONSE_BYTES} bytes")
157
+ resp_headers = {k.lower(): v for k, v in resp.getheaders()}
158
+ status = resp.status
159
+ except (OSError, http.client.HTTPException, socket.timeout) as exc:
160
+ raise NetworkError(f"{type(exc).__name__}: {exc}") from exc
161
+ finally:
162
+ conn.close()
163
+ if resp_headers.get("content-encoding", "").lower() == "gzip" and payload:
164
+ try:
165
+ inflater = zlib.decompressobj(16 + zlib.MAX_WBITS)
166
+ payload = inflater.decompress(payload, MAX_RESPONSE_BYTES + 1)
167
+ except zlib.error as exc:
168
+ raise NetworkError(f"unreadable gzip body: {exc}") from exc
169
+ if len(payload) > MAX_RESPONSE_BYTES or inflater.unconsumed_tail:
170
+ raise NetworkError(f"response larger than {MAX_RESPONSE_BYTES} bytes once decompressed")
171
+ parsed: dict | None = None
172
+ if payload:
173
+ try:
174
+ value = json.loads(payload.decode("utf-8"))
175
+ except (UnicodeDecodeError, ValueError):
176
+ value = None
177
+ if isinstance(value, dict):
178
+ parsed = value
179
+ elif 200 <= status < 300:
180
+ raise NetworkError(f"HTTP {status} with a body that is not a JSON object")
181
+ return Response(status, parsed, resp_headers)
182
+
183
+
184
+ __all__ = ["EndpointError", "LOOPBACK", "NetworkError", "Response", "Transport"]
@@ -0,0 +1,73 @@
1
+ """Wire primitives: timestamps, ids, JSON bytes, backoff (spec/protocol.md 2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import calendar
6
+ import gzip
7
+ import hashlib
8
+ import json
9
+ import random
10
+ import time
11
+ import uuid
12
+ from typing import Any
13
+
14
+ PROTOCOL = "amiril.protocol/1"
15
+ GZIP_ABOVE = 1024 # 2.2: gzip request bodies larger than 1 KiB
16
+
17
+
18
+ def ts_ms(epoch: float) -> str:
19
+ """RFC 3339 UTC with exactly millisecond precision (2.2)."""
20
+ ms = int(epoch * 1000)
21
+ secs, rem = divmod(ms, 1000)
22
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(secs)) + f".{rem:03d}Z"
23
+
24
+
25
+ def ts_hr(epoch: float) -> str:
26
+ """RFC 3339 UTC with microseconds, for `call.hook_at` (12)."""
27
+ us = int(round(epoch * 1_000_000))
28
+ secs, rem = divmod(us, 1_000_000)
29
+ return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(secs)) + f".{rem:06d}Z"
30
+
31
+
32
+ def parse_ts(text: str) -> float:
33
+ """Epoch seconds from an RFC 3339 UTC timestamp with a `Z` suffix."""
34
+ head, _, frac = text.rstrip("Z").partition(".")
35
+ secs = calendar.timegm(time.strptime(head, "%Y-%m-%dT%H:%M:%S"))
36
+ return secs + (float("0." + frac) if frac else 0.0)
37
+
38
+
39
+ def new_uuid() -> str:
40
+ """UUIDv4, lower-case canonical (2.2)."""
41
+ return str(uuid.uuid4())
42
+
43
+
44
+ def dumps(obj: Any) -> bytes:
45
+ """Compact UTF-8 JSON; non-finite numbers are refused (bodies carry none)."""
46
+ return json.dumps(obj, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")
47
+
48
+
49
+ def encode_body(raw: bytes) -> tuple[bytes, bool]:
50
+ """The bytes to put on the wire and whether they are gzipped (2.2)."""
51
+ if len(raw) > GZIP_ABOVE:
52
+ return gzip.compress(raw, compresslevel=6, mtime=0), True
53
+ return raw, False
54
+
55
+
56
+ def key_hash(api_key: str) -> str:
57
+ """Names the disk cache and spool so a key change never reads another key's files (5.6)."""
58
+ return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:16]
59
+
60
+
61
+ def backoff(failures: int, base: float, cap: float, rng: random.Random) -> float:
62
+ """2.5: first wait `base`, doubling to `cap`, full jitter."""
63
+ ceiling = min(cap, base * (2 ** min(max(0, failures - 1), 62))) # bounded: no float overflow
64
+ return rng.uniform(0.0, ceiling)
65
+
66
+
67
+ def retry_after_wait(retry_after: float, rng: random.Random) -> float:
68
+ """2.5: `Retry-After` plus a uniform delay in [0, max(1 s, Retry-After / 10)]."""
69
+ return retry_after + rng.uniform(0.0, max(1.0, retry_after / 10.0))
70
+
71
+
72
+ __all__ = ["PROTOCOL", "backoff", "dumps", "encode_body", "key_hash", "new_uuid", "parse_ts", "retry_after_wait",
73
+ "ts_hr", "ts_ms"]