anumat-engine 0.1.0__py3-none-win_amd64.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.
anumat_engine/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright 2026 AmitMirgal
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
anumat_engine/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ anumat-engine
2
+ Copyright 2026 AmitMirgal
3
+
4
+ This software is licensed under the Apache License, Version 2.0.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1,5 @@
1
+ from anumat_engine.engine import Engine, create_engine
2
+ from anumat_engine.errors import EngineError
3
+ from anumat_engine.slug import slugify
4
+
5
+ __all__ = ["Engine", "EngineError", "create_engine", "slugify"]
@@ -0,0 +1,3 @@
1
+ from anumat_engine.cli import main
2
+
3
+ main()
@@ -0,0 +1,21 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ from anumat_engine.errors import EngineError
8
+
9
+
10
+ def binary_path() -> Path:
11
+ override = os.environ.get("ANUMAT_ENGINE_BINARY")
12
+ if override:
13
+ path = Path(override)
14
+ if not path.is_file():
15
+ raise EngineError(f"ANUMAT_ENGINE_BINARY does not exist: {path}", code="internal")
16
+ return path
17
+ name = "anumat-engine.exe" if sys.platform == "win32" else "anumat-engine"
18
+ path = Path(__file__).resolve().parent / "bin" / name
19
+ if not path.is_file():
20
+ raise EngineError(f"anumat-engine binary is not installed at {path}", code="internal")
21
+ return path
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: anumat_engine/bin/anumat-engine.exe
3
+ size: 96385536 bytes
4
+ sha256: b5120492df5fc5638e7298bb3fd99bd702a2ba9f3901f0403b9c0be4553dc609
anumat_engine/cli.py ADDED
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import subprocess
5
+ import sys
6
+
7
+ from anumat_engine._binary import binary_path
8
+
9
+ USAGE = "Usage: anumat-engine migrate --db <url>"
10
+
11
+
12
+ class UsageError(Exception):
13
+ pass
14
+
15
+
16
+ def main(argv: list[str] | None = None) -> None:
17
+ args = list(sys.argv[1:] if argv is None else argv)
18
+ try:
19
+ database_url = migrate_database_url(args)
20
+ except UsageError as error:
21
+ print(error, file=sys.stderr)
22
+ raise SystemExit(1) from None
23
+ completed = subprocess.run(
24
+ [str(binary_path()), "migrate", "--db", database_url],
25
+ env={**os.environ, "ANUMAT_ENGINE_SIDECAR": "1"},
26
+ check=False,
27
+ )
28
+ raise SystemExit(completed.returncode)
29
+
30
+
31
+ def migrate_database_url(args: list[str]) -> str:
32
+ if args[:1] != ["migrate"]:
33
+ raise UsageError(USAGE)
34
+ database_url: str | None = None
35
+ index = 1
36
+ while index < len(args):
37
+ arg = args[index]
38
+ if arg == "--db":
39
+ index += 1
40
+ if index >= len(args):
41
+ raise UsageError(USAGE)
42
+ database_url = args[index]
43
+ elif arg.startswith("--db="):
44
+ database_url = arg.removeprefix("--db=")
45
+ else:
46
+ raise UsageError(USAGE)
47
+ index += 1
48
+ if not database_url:
49
+ raise UsageError(USAGE)
50
+ return database_url
@@ -0,0 +1,421 @@
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import json
5
+ import os
6
+ import queue
7
+ import signal
8
+ import subprocess
9
+ import threading
10
+ import time
11
+ import urllib.error
12
+ import urllib.request
13
+ from typing import Any, Literal
14
+
15
+ from anumat_engine._binary import binary_path
16
+ from anumat_engine.errors import EngineError
17
+
18
+ JsonObject = dict[str, Any]
19
+ Market = Literal["us"]
20
+ VersionStatus = Literal["proposed", "approved", "rejected", "superseded"]
21
+
22
+
23
+ class Engine:
24
+ def __init__(
25
+ self,
26
+ process: subprocess.Popen[bytes],
27
+ base_url: str,
28
+ token: str,
29
+ config: JsonObject,
30
+ stderr: bytearray,
31
+ ) -> None:
32
+ self._process = process
33
+ self._base_url = base_url
34
+ self._token = token
35
+ self._stderr = stderr
36
+ self._closed = False
37
+ self.config = config
38
+
39
+ def close(self) -> None:
40
+ if self._closed:
41
+ return
42
+ self._closed = True
43
+ _stop(self._process)
44
+
45
+ def __enter__(self) -> Engine:
46
+ return self
47
+
48
+ def __exit__(self, *_exc: object) -> None:
49
+ self.close()
50
+
51
+ def register_payer(self, *, name: str, slug: str, market: Market) -> JsonObject:
52
+ return _object(self._call("register_payer", {"name": name, "slug": slug, "market": market}))
53
+
54
+ def get_payer(self, *, id: str) -> JsonObject:
55
+ return _object(self._call("get_payer", {"id": id}))
56
+
57
+ def find_payer_by_slug(self, *, slug: str) -> JsonObject | None:
58
+ return _object_or_none(self._call("find_payer_by_slug", {"slug": slug}))
59
+
60
+ def list_payers(self, *, limit: int = 20, cursor: str | None = None) -> JsonObject:
61
+ return _page(self._call("list_payers", _page_input(limit, cursor)))
62
+
63
+ def register_source(
64
+ self,
65
+ *,
66
+ payer_id: str,
67
+ title: str,
68
+ source_url: str,
69
+ policy_slug: str | None = None,
70
+ market: Market | None = None,
71
+ check_interval_hours: int | None = None,
72
+ enabled: bool | None = None,
73
+ ) -> JsonObject:
74
+ payload: JsonObject = {"payer_id": payer_id, "title": title, "source_url": source_url}
75
+ if policy_slug is not None:
76
+ payload["policy_slug"] = policy_slug
77
+ if market is not None:
78
+ payload["market"] = market
79
+ if check_interval_hours is not None:
80
+ payload["check_interval_hours"] = check_interval_hours
81
+ if enabled is not None:
82
+ payload["enabled"] = enabled
83
+ return _object(self._call("register_source", payload))
84
+
85
+ def get_source(self, *, id: str) -> JsonObject:
86
+ return _object(self._call("get_source", {"id": id}))
87
+
88
+ def find_source_by_policy_key(self, *, policy_key: str) -> JsonObject | None:
89
+ return _object_or_none(self._call("find_source_by_policy_key", {"policy_key": policy_key}))
90
+
91
+ def list_sources(self, *, limit: int = 20, cursor: str | None = None) -> JsonObject:
92
+ return _page(self._call("list_sources", _page_input(limit, cursor)))
93
+
94
+ def check_source(self, *, source_id: str) -> JsonObject:
95
+ return _object(self._call("check_source", {"source_id": source_id}))
96
+
97
+ def due_sources(self) -> list[JsonObject]:
98
+ return _objects(self._call("due_sources", {}))
99
+
100
+ def check_due_sources(self) -> list[JsonObject]:
101
+ return _objects(self._call("check_due_sources", {}))
102
+
103
+ def propose_version(self, *, source_id: str, document_id: str, extraction: Any, extracted_by: str) -> JsonObject:
104
+ return _object(
105
+ self._call(
106
+ "propose_version",
107
+ {
108
+ "source_id": source_id,
109
+ "document_id": document_id,
110
+ "extraction": extraction,
111
+ "extracted_by": extracted_by,
112
+ },
113
+ )
114
+ )
115
+
116
+ def approve_version(self, *, version_id: str, approved_by: str) -> JsonObject:
117
+ return _object(self._call("approve_version", {"version_id": version_id, "approved_by": approved_by}))
118
+
119
+ def reject_version(self, *, version_id: str, rejected_by: str, reason: str) -> JsonObject:
120
+ return _object(
121
+ self._call(
122
+ "reject_version",
123
+ {"version_id": version_id, "rejected_by": rejected_by, "reason": reason},
124
+ )
125
+ )
126
+
127
+ def get_published_policy(self, *, policy_key: str) -> JsonObject:
128
+ return _object(self._call("get_published_policy", {"policy_key": policy_key}))
129
+
130
+ def get_published_version(self, *, policy_key: str, version: int) -> JsonObject:
131
+ return _object(self._call("get_published_version", {"policy_key": policy_key, "version": version}))
132
+
133
+ def list_published_versions(self, *, policy_key: str, limit: int = 20, cursor: str | None = None) -> JsonObject:
134
+ return _page(self._call("list_published_versions", _page_input(limit, cursor, policy_key=policy_key)))
135
+
136
+ def get_version(self, *, id: str) -> JsonObject:
137
+ return _object(self._call("get_version", {"id": id}))
138
+
139
+ def list_versions(
140
+ self,
141
+ *,
142
+ limit: int = 20,
143
+ cursor: str | None = None,
144
+ status: VersionStatus | None = None,
145
+ policy_key: str | None = None,
146
+ ) -> JsonObject:
147
+ payload = _page_input(limit, cursor)
148
+ if status is not None:
149
+ payload["status"] = status
150
+ if policy_key is not None:
151
+ payload["policy_key"] = policy_key
152
+ return _page(self._call("list_versions", payload))
153
+
154
+ def get_diff(self, *, id: str) -> JsonObject:
155
+ return _object(self._call("get_diff", {"id": id}))
156
+
157
+ def diff_for_version(self, *, version_id: str) -> JsonObject:
158
+ return _object(self._call("diff_for_version", {"version_id": version_id}))
159
+
160
+ def save_diff_notes(self, *, diff_id: str, summary: str | None, review: Any) -> JsonObject:
161
+ return _object(self._call("save_diff_notes", {"diff_id": diff_id, "summary": summary, "review": review}))
162
+
163
+ def _call(self, method: str, payload: JsonObject) -> Any:
164
+ if self._closed:
165
+ raise EngineError("engine is closed", code="closed")
166
+ body = json.dumps({"method": method, "input": payload}).encode()
167
+ request = urllib.request.Request(
168
+ f"{self._base_url}/rpc",
169
+ data=body,
170
+ method="POST",
171
+ headers={
172
+ "authorization": f"Bearer {self._token}",
173
+ "content-type": "application/json",
174
+ },
175
+ )
176
+ try:
177
+ with urllib.request.urlopen(request, timeout=120) as response:
178
+ parsed = json.loads(response.read().decode())
179
+ except urllib.error.HTTPError as error:
180
+ raise _error_from_http(error) from None
181
+ except urllib.error.URLError as error:
182
+ raise EngineError(f"engine request failed: {error.reason}", code="unavailable") from None
183
+ if not isinstance(parsed, dict) or "result" not in parsed:
184
+ raise EngineError("engine returned an unexpected response", code="internal")
185
+ return parsed["result"]
186
+
187
+
188
+ def create_engine(
189
+ database_url: str,
190
+ storage: JsonObject | None = None,
191
+ llm: JsonObject | None = None,
192
+ ) -> Engine:
193
+ config: JsonObject = {"databaseUrl": database_url}
194
+ storage_payload = _storage_payload(storage)
195
+ if storage_payload is not None:
196
+ config["storage"] = storage_payload
197
+ if llm is not None:
198
+ strong = llm.get("strong")
199
+ cheap = llm.get("cheap")
200
+ if not isinstance(strong, str) or not isinstance(cheap, str):
201
+ raise EngineError("llm requires strong and cheap", code="validation_failed")
202
+ config["llm"] = {"strong": strong, "cheap": cheap}
203
+ process = _spawn(binary_path())
204
+ stderr = bytearray()
205
+ assert process.stderr is not None
206
+ threading.Thread(target=_drain, args=(process.stderr, stderr), daemon=True).start()
207
+ try:
208
+ assert process.stdin is not None and process.stdout is not None
209
+ process.stdin.write(json.dumps(config).encode() + b"\n")
210
+ process.stdin.flush()
211
+ line = _read_line(process.stdout, 60)
212
+ if line == b"":
213
+ raise EngineError(_with_stderr("engine exited before it was ready", stderr), code="internal")
214
+ ready = json.loads(line.decode())
215
+ port = ready["port"]
216
+ token = ready["token"]
217
+ if not isinstance(port, int) or not isinstance(token, str) or token == "":
218
+ raise EngineError("engine ready line was incomplete", code="internal")
219
+ base_url = f"http://127.0.0.1:{port}"
220
+ _wait_health(base_url, token, process, stderr)
221
+ engine_config = ready.get("config")
222
+ if not isinstance(engine_config, dict):
223
+ raise EngineError("engine ready line was incomplete", code="internal")
224
+ engine = Engine(process, base_url, token, engine_config, stderr)
225
+ except Exception:
226
+ _stop(process)
227
+ raise
228
+ atexit.register(engine.close)
229
+ return engine
230
+
231
+
232
+ def _spawn(binary: os.PathLike[str]) -> subprocess.Popen[bytes]:
233
+ env = os.environ.copy()
234
+ env["ANUMAT_ENGINE_SIDECAR"] = "1"
235
+ command = [os.fspath(binary), "serve"]
236
+ if os.name == "posix":
237
+ return subprocess.Popen(
238
+ command,
239
+ stdin=subprocess.PIPE,
240
+ stdout=subprocess.PIPE,
241
+ stderr=subprocess.PIPE,
242
+ env=env,
243
+ start_new_session=True,
244
+ )
245
+ return subprocess.Popen(
246
+ command,
247
+ stdin=subprocess.PIPE,
248
+ stdout=subprocess.PIPE,
249
+ stderr=subprocess.PIPE,
250
+ env=env,
251
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP,
252
+ )
253
+
254
+
255
+ def _drain(stream: Any, sink: bytearray, limit: int = 65536) -> None:
256
+ while True:
257
+ chunk = stream.read(4096)
258
+ if not chunk:
259
+ return
260
+ if len(sink) < limit:
261
+ sink.extend(chunk[: limit - len(sink)])
262
+
263
+
264
+ def _read_line(stream: Any, timeout: float) -> bytes:
265
+ holder: queue.Queue[bytes] = queue.Queue(maxsize=1)
266
+
267
+ def run() -> None:
268
+ holder.put(stream.readline())
269
+
270
+ threading.Thread(target=run, daemon=True).start()
271
+ try:
272
+ return holder.get(timeout=timeout)
273
+ except queue.Empty as error:
274
+ raise EngineError("engine did not become ready", code="internal") from error
275
+
276
+
277
+ def _wait_health(base_url: str, token: str, process: subprocess.Popen[bytes], stderr: bytearray) -> None:
278
+ deadline = time.monotonic() + 30
279
+ last = "engine health check failed"
280
+ while time.monotonic() < deadline:
281
+ if process.poll() is not None:
282
+ raise EngineError(_with_stderr("engine exited during the health check", stderr), code="internal")
283
+ request = urllib.request.Request(
284
+ f"{base_url}/health",
285
+ headers={"authorization": f"Bearer {token}"},
286
+ )
287
+ try:
288
+ with urllib.request.urlopen(request, timeout=2) as response:
289
+ body = json.loads(response.read().decode())
290
+ except urllib.error.HTTPError as error:
291
+ if error.code != 503:
292
+ raise _error_from_http(error) from None
293
+ last = "engine is not ready"
294
+ except urllib.error.URLError as error:
295
+ last = f"engine health check failed: {error.reason}"
296
+ else:
297
+ if isinstance(body, dict) and body.get("status") == "ok":
298
+ return
299
+ last = "engine health check failed"
300
+ time.sleep(0.05)
301
+ raise EngineError(last, code="internal")
302
+
303
+
304
+ def _storage_payload(storage: JsonObject | None) -> JsonObject | None:
305
+ if storage is None:
306
+ return None
307
+ kind = storage.get("kind")
308
+ if kind == "local":
309
+ payload: JsonObject = {"kind": "local"}
310
+ data_dir = storage.get("data_dir")
311
+ if isinstance(data_dir, str):
312
+ payload["dataDir"] = data_dir
313
+ return payload
314
+ if kind == "s3":
315
+ payload = {
316
+ "kind": "s3",
317
+ "region": storage["region"],
318
+ "bucket": storage["bucket"],
319
+ "accessKeyId": storage["access_key_id"],
320
+ "secretAccessKey": storage["secret_access_key"],
321
+ }
322
+ endpoint = storage.get("endpoint")
323
+ if isinstance(endpoint, str):
324
+ payload["endpoint"] = endpoint
325
+ return payload
326
+ raise EngineError("storage.kind must be local or s3", code="validation_failed")
327
+
328
+
329
+ def _page_input(limit: int, cursor: str | None, **extra: Any) -> JsonObject:
330
+ payload: JsonObject = {"limit": limit, **extra}
331
+ if cursor is not None:
332
+ payload["cursor"] = cursor
333
+ return payload
334
+
335
+
336
+ def _object(value: Any) -> JsonObject:
337
+ if not isinstance(value, dict):
338
+ raise EngineError("engine returned an unexpected object", code="internal")
339
+ return value
340
+
341
+
342
+ def _object_or_none(value: Any) -> JsonObject | None:
343
+ if value is None:
344
+ return None
345
+ return _object(value)
346
+
347
+
348
+ def _objects(value: Any) -> list[JsonObject]:
349
+ if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
350
+ raise EngineError("engine returned an unexpected list", code="internal")
351
+ return value
352
+
353
+
354
+ def _page(value: Any) -> JsonObject:
355
+ page = _object(value)
356
+ items = page.get("items")
357
+ cursor = page.get("nextCursor")
358
+ if not isinstance(items, list) or (cursor is not None and not isinstance(cursor, str)):
359
+ raise EngineError("engine returned an unexpected page", code="internal")
360
+ return page
361
+
362
+
363
+ def _error_from_http(error: urllib.error.HTTPError) -> EngineError:
364
+ raw = error.read().decode()
365
+ try:
366
+ parsed = json.loads(raw)
367
+ except json.JSONDecodeError:
368
+ parsed = None
369
+ if isinstance(parsed, dict) and isinstance(parsed.get("error"), dict):
370
+ body = parsed["error"]
371
+ message = body.get("message")
372
+ code = body.get("code")
373
+ details = body.get("details")
374
+ return EngineError(
375
+ message if isinstance(message, str) else error.reason,
376
+ code=code if isinstance(code, str) else "internal",
377
+ details=details if isinstance(details, dict) else None,
378
+ )
379
+ return EngineError(error.reason or "engine request failed", code="internal")
380
+
381
+
382
+ def _with_stderr(message: str, stderr: bytearray) -> str:
383
+ detail = bytes(stderr).decode(errors="replace").strip()
384
+ if detail == "":
385
+ return message
386
+ return f"{message}: {detail}"
387
+
388
+
389
+ def _stop(process: subprocess.Popen[bytes]) -> None:
390
+ if process.poll() is not None:
391
+ return
392
+ if process.stdin is not None:
393
+ try:
394
+ process.stdin.close()
395
+ except OSError:
396
+ pass
397
+ try:
398
+ process.wait(timeout=5)
399
+ return
400
+ except subprocess.TimeoutExpired:
401
+ pass
402
+ _signal(process, signal.SIGTERM)
403
+ try:
404
+ process.wait(timeout=2)
405
+ return
406
+ except subprocess.TimeoutExpired:
407
+ _signal(process, getattr(signal, "SIGKILL", signal.SIGTERM))
408
+ process.wait(timeout=2)
409
+
410
+
411
+ def _signal(process: subprocess.Popen[bytes], sig: signal.Signals) -> None:
412
+ if os.name == "posix":
413
+ try:
414
+ os.killpg(process.pid, sig)
415
+ except ProcessLookupError:
416
+ return
417
+ return
418
+ if sig == getattr(signal, "SIGKILL", None):
419
+ process.kill()
420
+ return
421
+ process.terminate()
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+
5
+
6
+ class EngineError(Exception):
7
+ def __init__(self, message: str, *, code: str = "internal", details: dict[str, Any] | None = None) -> None:
8
+ super().__init__(message)
9
+ self.code = code
10
+ self.details = details
anumat_engine/py.typed ADDED
File without changes
anumat_engine/slug.py ADDED
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import unicodedata
5
+
6
+
7
+ def slugify(value: str) -> str:
8
+ normalized = unicodedata.normalize("NFKD", value).lower()
9
+ dashed = re.sub(r"[^a-z0-9]+", "-", normalized)
10
+ return re.sub(r"^-+|-+$", "", dashed)
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.5
2
+ Name: anumat-engine
3
+ Version: 0.1.0
4
+ Summary: Run the Anumat engine on your machine
5
+ Project-URL: Repository, https://github.com/AmitMirgal/anumat
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ License-File: NOTICE
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+
12
+ # anumat-engine
13
+
14
+ `anumat-engine` runs the Anumat engine in a local process. The wheel ships the engine binary.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ pip install anumat-engine
20
+ ```
21
+
22
+ Each wheel contains the binary for one platform.
23
+
24
+ ## Apply the migrations
25
+
26
+ `anumat-engine migrate` applies the SQL migrations bundled in the binary. It records them in `_prisma_migrations`. A second run leaves an up-to-date database unchanged.
27
+
28
+ ```bash
29
+ anumat-engine migrate --db postgres://USER:PASSWORD@HOST:5432/DATABASE
30
+ ```
31
+
32
+ ## Call create_engine
33
+
34
+ ```python
35
+ from anumat_engine import create_engine
36
+
37
+ with create_engine(database_url="postgres://USER:PASSWORD@HOST:5432/DATABASE") as engine:
38
+ page = engine.list_payers()
39
+ ```
40
+
41
+ `create_engine` starts the engine and returns after the engine health check succeeds. `engine.close()` stops the process. A `with` block calls `close()`. The process also stops when the parent process exits.
42
+
43
+ `storage` and `llm` are optional. `create_engine` does not read them from the environment.
44
+
45
+ For local files, pass `storage={"kind": "local", "data_dir": "data/policies"}`. The default directory is `./data/policies`. For object storage, pass `storage` with `kind` set to `s3` and `region`, `bucket`, `access_key_id`, and `secret_access_key`.
46
+
47
+ Pass `llm={"strong": "anthropic/claude-sonnet-4-5", "cheap": "anthropic/claude-haiku-4-5"}` when a check should call a model. Omit `llm` until a check needs one.
48
+
49
+ Engine methods use snake_case names for the functions exported by `@anumat/engine`. `engine.list_payers()` calls `listPayers`.
@@ -0,0 +1,17 @@
1
+ anumat_engine/__init__.py,sha256=MENiVCqaCG6ACRK33j6djHGnw7qQrzaF3_zgxT6tjfM,204
2
+ anumat_engine/__main__.py,sha256=gNiuzWC3pAO30iF8catouYuBF_TlK9uC-VmrMR6fM1Q,43
3
+ anumat_engine/_binary.py,sha256=i2dJyLimRIZMwVhDl_wm2z-x9Zk_0MFMPgzzKm03YxI,679
4
+ anumat_engine/cli.py,sha256=1gCh-G4IeJMc-iblQciHq702ICsm5HwHwZUvBzbd8rA,1335
5
+ anumat_engine/engine.py,sha256=S1vNbYkbQG6n0bsvSSZF_gJVADhBQ0mNMeZgrcXEf90,15130
6
+ anumat_engine/errors.py,sha256=Kikhw-33FWBWrjOF9P9tGJkszjoZcuUzQYb6I_GR0lk,293
7
+ anumat_engine/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ anumat_engine/slug.py,sha256=4ExiWThQ8XKrwEHDuYpbQF99WuT2X0EWKUIXSFGVhx0,255
9
+ anumat_engine/LICENSE,sha256=2TAEz8P6v9uLUdzlnhpboMw46h4K-xF34RF0sJhX5wQ,11384
10
+ anumat_engine/NOTICE,sha256=aS7-lz5VHYucsqgpuuPuVcbgY5QFmBrdll6QcOl6HCs,194
11
+ anumat_engine/bin/anumat-engine.exe,sha256=tRIEkt9fxWOOcpi7P9mb1wKiup85AfBAO5wL5FU9xgk,96385536
12
+ anumat_engine-0.1.0.dist-info/METADATA,sha256=QjKO9e4VPP2au6gUjwQB51Tcviea85hmqghY-W99v-Y,1839
13
+ anumat_engine-0.1.0.dist-info/WHEEL,sha256=lpoBGaIUIidvvdZ4qRAP61bBKYJdt4FI3WXFL50Gzyo,94
14
+ anumat_engine-0.1.0.dist-info/entry_points.txt,sha256=1WSORy3qsATUyNId0R8GEhNC-XIe8962okV0Y0lPJr0,57
15
+ anumat_engine-0.1.0.dist-info/licenses/LICENSE,sha256=2TAEz8P6v9uLUdzlnhpboMw46h4K-xF34RF0sJhX5wQ,11384
16
+ anumat_engine-0.1.0.dist-info/licenses/NOTICE,sha256=aS7-lz5VHYucsqgpuuPuVcbgY5QFmBrdll6QcOl6HCs,194
17
+ anumat_engine-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ anumat-engine = anumat_engine.cli:main
@@ -0,0 +1,203 @@
1
+ Copyright 2026 AmitMirgal
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
@@ -0,0 +1,7 @@
1
+ anumat-engine
2
+ Copyright 2026 AmitMirgal
3
+
4
+ This software is licensed under the Apache License, Version 2.0.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0