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
amiril/_kernel/ids.py ADDED
@@ -0,0 +1,66 @@
1
+ """Call ids and batch ids (spec/kernel.md 3.1, 3.2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import threading
7
+ from typing import Any
8
+
9
+ from .normalise import canonical_json, to_json
10
+
11
+
12
+ def mint_call_id(run_id: str, tool_name_raw: str, args: Any, ordinal: int) -> str:
13
+ """3.1: `mint_` + the first 32 hex digits of sha256 over the canonical JSON
14
+ of `[run_id, tool_name_raw, args, ordinal]`."""
15
+ payload = canonical_json([run_id, tool_name_raw, to_json(args), ordinal])
16
+ return "mint_" + hashlib.sha256(payload.encode("utf-8")).hexdigest()[:32]
17
+
18
+
19
+ class CallIdMinter:
20
+ """Tracks the per-run ordinal of identical (tool, args) pairs so adapters
21
+ whose framework has no tool call id can mint one. Thread-safe."""
22
+
23
+ def __init__(self) -> None:
24
+ self._lock = threading.Lock()
25
+ self._seen: dict[str, dict[str, int]] = {}
26
+
27
+ def mint(self, run_id: str, tool_name_raw: str, args: Any) -> str:
28
+ plain = to_json(args)
29
+ key = canonical_json([tool_name_raw, plain])
30
+ with self._lock:
31
+ per_run = self._seen.setdefault(run_id, {})
32
+ ordinal = per_run.get(key, 0)
33
+ per_run[key] = ordinal + 1
34
+ return mint_call_id(run_id, tool_name_raw, plain, ordinal)
35
+
36
+ def end_run(self, run_id: str) -> None:
37
+ with self._lock:
38
+ self._seen.pop(run_id, None)
39
+
40
+
41
+ class BatchTracker:
42
+ """3.2: the most recent model call per run is the batch id. Adapters call
43
+ `on_model_call` from the framework's model hook and `current` from the
44
+ tool hook; before any model call the batch id is `<run_id>:b0`."""
45
+
46
+ def __init__(self) -> None:
47
+ self._lock = threading.Lock()
48
+ self._current: dict[str, str] = {}
49
+ self._count: dict[str, int] = {}
50
+
51
+ def on_model_call(self, run_id: str, model_call_id: str | None = None) -> str:
52
+ with self._lock:
53
+ n = self._count.get(run_id, 0) + 1
54
+ self._count[run_id] = n
55
+ batch_id = model_call_id or f"{run_id}:b{n}"
56
+ self._current[run_id] = batch_id
57
+ return batch_id
58
+
59
+ def current(self, run_id: str) -> str:
60
+ with self._lock:
61
+ return self._current.get(run_id, f"{run_id}:b0")
62
+
63
+ def end_run(self, run_id: str) -> None:
64
+ with self._lock:
65
+ self._current.pop(run_id, None)
66
+ self._count.pop(run_id, None)
@@ -0,0 +1,30 @@
1
+ """Messages to the model (spec/kernel.md, section 13)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ CODA = ("Do not retry this call with different arguments or achieve the same outcome another way; "
6
+ "tell the user it was not performed.")
7
+
8
+
9
+ def _reason(rule_id: str, sentence: str) -> str:
10
+ text = sentence.strip().rstrip(".")
11
+ return text if text else f"rule {rule_id} did not allow it"
12
+
13
+
14
+ def blocked(tool_id: str, rule_id: str, sentence: str) -> str:
15
+ return f"The call to {tool_id} was not performed. Rule {rule_id} blocked it: {_reason(rule_id, sentence)}. {CODA}"
16
+
17
+
18
+ def held_and_refused(tool_id: str, rule_id: str, sentence: str) -> str:
19
+ return (f"The call to {tool_id} was not performed. Rule {rule_id} held it for approval and the approval "
20
+ f"was refused: {_reason(rule_id, sentence)}. {CODA}")
21
+
22
+
23
+ def held_no_approval(tool_id: str, rule_id: str, sentence: str) -> str:
24
+ return (f"The call to {tool_id} was not performed. Rule {rule_id} held it for approval and no approval "
25
+ f"arrived: {_reason(rule_id, sentence)}. {CODA}")
26
+
27
+
28
+ def could_not_be_checked(tool_id: str, rule_id: str) -> str:
29
+ return (f"The call to {tool_id} was not performed. It could not be checked against rule {rule_id}, "
30
+ f"which requires a check before the call runs. {CODA}")
@@ -0,0 +1,165 @@
1
+ """Plain JSON, canonical JSON and result normalisation (spec/kernel.md 12.2, 12.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import json
7
+ import math
8
+ from decimal import Decimal
9
+ from typing import Any
10
+
11
+ MAX_DEPTH = 200
12
+
13
+
14
+ class _Fallback:
15
+ __slots__ = ("fired",)
16
+
17
+ def __init__(self) -> None:
18
+ self.fired = False
19
+
20
+
21
+ def to_json(value: Any, meta: dict | None = None) -> Any:
22
+ """Convert a value to plain JSON with every number a double (12.3).
23
+ Sets `meta["normalise_fallback"]` when the repr fallback fired."""
24
+ fb = _Fallback()
25
+ out = _convert(value, fb, 0)
26
+ if fb.fired and meta is not None:
27
+ meta["normalise_fallback"] = True
28
+ return out
29
+
30
+
31
+ def _double(value: Any) -> float:
32
+ """12.3: a number as a double; an integer beyond the double range is
33
+ `inf` or `-inf`, never a fault."""
34
+ try:
35
+ return float(value)
36
+ except OverflowError:
37
+ return math.inf if value > 0 else -math.inf
38
+
39
+
40
+ def _repr_fallback(value: Any, fb: _Fallback) -> dict:
41
+ fb.fired = True
42
+ try:
43
+ return {"repr": str(value)}
44
+ except RecursionError:
45
+ return {"repr": f"<{type(value).__name__}>"}
46
+
47
+
48
+ def _convert(value: Any, fb: _Fallback, depth: int) -> Any:
49
+ t = type(value)
50
+ if value is None or t is bool or t is str:
51
+ return value
52
+ if t is float:
53
+ return value
54
+ if t is int or isinstance(value, (int, float, Decimal)) and not isinstance(value, bool):
55
+ return _double(value)
56
+ if depth > MAX_DEPTH:
57
+ # Deeper than any argument should be: a self-referencing value or a
58
+ # dump that feeds itself (mock objects). Stop here with the repr fallback.
59
+ return _repr_fallback(value, fb)
60
+ if t is dict or isinstance(value, dict):
61
+ return {str(k): _convert(v, fb, depth + 1) for k, v in value.items()}
62
+ if t is list or t is tuple or isinstance(value, (list, tuple)):
63
+ return [_convert(v, fb, depth + 1) for v in value]
64
+ if isinstance(value, (set, frozenset)):
65
+ items = [_convert(v, fb, depth + 1) for v in value]
66
+ try:
67
+ return sorted(items)
68
+ except TypeError:
69
+ return sorted(items, key=lambda v: canonical_json(v))
70
+ if isinstance(value, str):
71
+ return str(value)
72
+ dump = getattr(type(value), "model_dump", None)
73
+ if callable(dump) and not isinstance(value, type):
74
+ try:
75
+ dumped = dump(value, mode="json")
76
+ except Exception: # noqa: BLE001 - a broken dump falls through to repr
77
+ dumped = value
78
+ if isinstance(dumped, (dict, list, tuple)):
79
+ return _convert(dumped, fb, depth + 1)
80
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
81
+ return _convert(dataclasses.asdict(value), fb, depth + 1)
82
+ return _repr_fallback(value, fb)
83
+
84
+
85
+ def normalise_result(value: Any) -> tuple[Any, bool]:
86
+ """12.2: a string parses as JSON when it is an object or a list, else it
87
+ becomes `{"text": s}` with the fallback flag; anything else goes through
88
+ `to_json`. Returns (json, fallback_used)."""
89
+ if isinstance(value, str):
90
+ try:
91
+ parsed = json.loads(value, parse_constant=_not_json)
92
+ except ValueError:
93
+ return {"text": value}, True
94
+ if isinstance(parsed, (dict, list)):
95
+ return to_json(parsed), False
96
+ return {"text": value}, True
97
+ meta: dict = {}
98
+ out = to_json(value, meta)
99
+ return out, bool(meta.get("normalise_fallback"))
100
+
101
+
102
+ def _not_json(token: str) -> Any:
103
+ """`NaN`, `Infinity` and `-Infinity` are not JSON (12.2): the string is text."""
104
+ raise ValueError(f"{token} is not JSON")
105
+
106
+
107
+ def ecma_number(f: float) -> str:
108
+ """ECMAScript `Number::toString` of a double (12.3, canonical JSON)."""
109
+ if f != f:
110
+ return "NaN"
111
+ if f in (math.inf, -math.inf):
112
+ return "Infinity" if f > 0 else "-Infinity"
113
+ if f == 0:
114
+ return "0"
115
+ sign = "-" if f < 0 else ""
116
+ f = abs(f)
117
+ if f.is_integer() and f < 1e21:
118
+ return sign + str(int(f))
119
+ r = repr(f)
120
+ mant, _, exp = r.partition("e")
121
+ e = int(exp) if exp else 0
122
+ int_part, _, frac_part = mant.partition(".")
123
+ digits = (int_part + frac_part).lstrip("0")
124
+ # n: position of the decimal point relative to the digit string.
125
+ n = len(int_part) + e
126
+ if int_part == "0":
127
+ stripped = frac_part.lstrip("0")
128
+ n = e - (len(frac_part) - len(stripped))
129
+ digits = stripped
130
+ digits = digits.rstrip("0") or "0"
131
+ k = len(digits)
132
+ if k <= n <= 21:
133
+ return sign + digits + "0" * (n - k)
134
+ if 0 < n <= 21:
135
+ return sign + digits[:n] + "." + digits[n:]
136
+ if -6 < n <= 0:
137
+ return sign + "0." + "0" * (-n) + digits
138
+ e10 = n - 1
139
+ exp_text = ("+" if e10 >= 0 else "-") + str(abs(e10))
140
+ if k == 1:
141
+ return sign + digits + "e" + exp_text
142
+ return sign + digits[0] + "." + digits[1:] + "e" + exp_text
143
+
144
+
145
+ def _canonical(v: Any) -> str:
146
+ t = type(v)
147
+ if v is None:
148
+ return "null"
149
+ if t is bool:
150
+ return "true" if v else "false"
151
+ if t is float or t is int:
152
+ return ecma_number(_double(v))
153
+ if t is str:
154
+ return json.dumps(v, ensure_ascii=False)
155
+ if t is list:
156
+ return "[" + ",".join(_canonical(x) for x in v) + "]"
157
+ if t is dict:
158
+ return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + _canonical(v[k]) for k in sorted(v)) + "}"
159
+ return _canonical(to_json(v))
160
+
161
+
162
+ def canonical_json(value: Any) -> str:
163
+ """12.3: sorted keys by code point, no whitespace, non-ASCII unescaped,
164
+ numbers as ECMAScript writes them."""
165
+ return _canonical(to_json(value))
@@ -0,0 +1,131 @@
1
+ """Records shared by the kernel, the engine and adapters (spec/kernel.md, section 2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from .._engine.rules import Decision
9
+
10
+ SEVERITY = {"allow": 0, "flag": 1, "hold": 2, "block": 3}
11
+ REEXECUTE_STATUSES = frozenset({"pending", "held", "ok"})
12
+ RETRY_STATUSES = frozenset({"blocked", "error"})
13
+
14
+
15
+ def most_severe(actions: list[str]) -> str:
16
+ """The most severe action, `allow` of none (kernel.md 9)."""
17
+ best = "allow"
18
+ for a in actions:
19
+ if SEVERITY[a] > SEVERITY[best]:
20
+ best = a
21
+ return best
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class RunContext:
26
+ """What the adapter supplies per run (kernel.md 2.2). `now` is epoch
27
+ seconds; None means the kernel's clock at evaluation time. A context
28
+ whose `root_run_id` differs from `run_id` is nested (kernel.md 11)."""
29
+
30
+ run_id: str
31
+ agent_id: str
32
+ session_id: str | None = None
33
+ agent_version: str | None = None
34
+ env: dict[str, Any] = field(default_factory=dict)
35
+ now: float | None = None
36
+ root_run_id: str | None = None
37
+ parent_call_id: str | None = None
38
+ root_agent_id: str | None = None
39
+
40
+ def __post_init__(self) -> None:
41
+ if self.root_run_id is None:
42
+ object.__setattr__(self, "root_run_id", self.run_id)
43
+ if self.root_agent_id is None:
44
+ object.__setattr__(self, "root_agent_id", self.agent_id)
45
+
46
+ @property
47
+ def nested(self) -> bool:
48
+ return self.root_run_id != self.run_id
49
+
50
+ def child(self, run_id: str, agent_id: str | None = None, session_id: str | None = None,
51
+ parent_call_id: str | None = None) -> RunContext:
52
+ """The context of a run started inside one of this run's calls (kernel.md 11)."""
53
+ return RunContext(
54
+ run_id=run_id,
55
+ agent_id=agent_id if agent_id is not None else self.agent_id,
56
+ session_id=session_id,
57
+ agent_version=self.agent_version,
58
+ env=self.env,
59
+ now=self.now,
60
+ root_run_id=self.root_run_id,
61
+ parent_call_id=parent_call_id,
62
+ root_agent_id=self.root_agent_id,
63
+ )
64
+
65
+
66
+ @dataclass(slots=True)
67
+ class CallRecord:
68
+ """One tool call in the kernel's shape (kernel.md 2.1). Rules read the
69
+ seventeen fields of edoc.md 5.1 and nothing else. The store treats a
70
+ record as immutable: a status change is a new object (`dataclasses.replace`)."""
71
+
72
+ call_id: str
73
+ run_id: str
74
+ root_run_id: str
75
+ session_id: str | None
76
+ agent_id: str
77
+ tool_id: str
78
+ tool_name_raw: str
79
+ args: dict
80
+ correlation: dict
81
+ status: str = "pending"
82
+ result: Any = None
83
+ error: str | None = None
84
+ seq: int = 0
85
+ batch_id: str = ""
86
+ parent_call_id: str | None = None
87
+ attempt: int = 1
88
+ kind: str = "tool_call"
89
+ started_at: float | None = None
90
+ ended_at: float | None = None
91
+ meta: dict = field(default_factory=dict)
92
+ tool_declared_id: str | None = None
93
+ call_id_minted: bool = False
94
+ arrival: int = -1
95
+ root_agent_id: str | None = None # the run's root agent, from the RunContext (protocol.md 7.1 hold.agent.root)
96
+
97
+ @property
98
+ def tool_call_id(self) -> str | None:
99
+ """The framework's own tool call id: the call id unless it was minted (protocol.md 8.3)."""
100
+ return None if self.call_id_minted else self.call_id
101
+
102
+
103
+ @dataclass
104
+ class Outcome:
105
+ """What the kernel tells the adapter for one call (kernel.md 2.3). Whether
106
+ the tool runs follows from `record.status`, never from `action`: a held
107
+ call that a resolver allowed keeps `action: hold` and proceeds."""
108
+
109
+ action: str
110
+ decisions: list[Decision]
111
+ message: str
112
+ record: CallRecord
113
+
114
+ @property
115
+ def proceeds(self) -> bool:
116
+ return self.record.status not in ("blocked", "held")
117
+
118
+
119
+ @dataclass
120
+ class Snapshot:
121
+ """The current record plus the history it may see (kernel.md 4). `history`
122
+ is a list of references into the store, never copies."""
123
+
124
+ call: Any
125
+ history: list
126
+ context: dict
127
+ phase: str
128
+
129
+
130
+ __all__ = ["CallRecord", "Decision", "Outcome", "RunContext", "Snapshot", "most_severe",
131
+ "REEXECUTE_STATUSES", "RETRY_STATUSES", "SEVERITY"]