probate-client 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Harsh Bhanushali
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: probate-client
3
+ Version: 0.1.0
4
+ Summary: Typed sync and async client for the Probate Courthouse public API.
5
+ Author-email: Harsh Bhanushali <bhanushaliharsh434@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/harshbhx/probate
8
+ Project-URL: Repository, https://github.com/harshbhx/probate
9
+ Project-URL: Issues, https://github.com/harshbhx/probate/issues
10
+ Keywords: probate,courthouse,api-client
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx>=0.27
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8; extra == "dev"
22
+ Requires-Dist: ruff>=0.6; extra == "dev"
23
+ Requires-Dist: build>=1.2; extra == "dev"
24
+ Requires-Dist: twine>=5.1; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # probate-client (Python)
28
+
29
+ A small typed client for the [Probate](https://github.com/harshbhx/probate) Courthouse public API,
30
+ with sync and async versions. It depends only on `httpx`. Python 3.11+.
31
+
32
+ ```sh
33
+ pip install probate-client
34
+ ```
35
+
36
+ ## Use
37
+
38
+ ```python
39
+ from probate_client import ApiError, ProbateClient
40
+
41
+ with ProbateClient("https://your-courthouse.example") as probate:
42
+ summary = probate.summary()
43
+ print(summary["living"], summary["counts"]["instincts"])
44
+
45
+ for case in probate.latest_trial()["cases"]:
46
+ print(case["n"], case["verdict"], case["text"])
47
+
48
+ try:
49
+ print(probate.ask(3, "What would you warn the next one about?")["answer"])
50
+ except ApiError as e:
51
+ print(e.status, e.message) # 400 "not_dead", 429 "rate_limited", ...
52
+
53
+ for event in probate.events(interval=5): # polls; break to stop
54
+ print(event["ts"], event["kind"], event["text"])
55
+ ```
56
+
57
+ Async:
58
+
59
+ ```python
60
+ import asyncio
61
+ from probate_client import AsyncProbateClient
62
+
63
+ async def main():
64
+ async with AsyncProbateClient("http://localhost:8080") as probate:
65
+ print(await probate.health())
66
+ async for event in probate.events():
67
+ print(event["text"])
68
+
69
+ asyncio.run(main())
70
+ ```
71
+
72
+ ## API
73
+
74
+ | Method | Route |
75
+ | --- | --- |
76
+ | `summary()` | `GET /api/summary` |
77
+ | `generation(n)` | `GET /api/generations/{n}` |
78
+ | `trial(n)` | `GET /api/trials/{n}` |
79
+ | `latest_trial()` | `GET /api/trials/latest` |
80
+ | `genome()` / `instincts()` | `GET /api/genome` (`instincts()` returns just the list) |
81
+ | `evidence()` | `GET /api/evidence` |
82
+ | `health()` | `GET /healthz` |
83
+ | `ask(gen, question)` | `POST /api/generations/{n}/ask` |
84
+ | `events(since=0, interval=5.0)` | `GET /api/events?since=` (iterator) |
85
+
86
+ `ProbateClient(base_url="http://localhost:8080", *, api_key=None, timeout=30.0, http_client=None)`, and the
87
+ same for `AsyncProbateClient` (use `await client.aclose()` or `async with`). Errors from the server raise
88
+ `ApiError` with `status`, `message` and `body`. Network errors and timeouts raise the `httpx` exceptions
89
+ unchanged. Nothing is retried.
90
+
91
+ Responses are plain dicts. `probate_client.types` has `TypedDict` definitions for them, so editors and mypy
92
+ know the keys.
93
+
94
+ ## Honest limits
95
+
96
+ - **`events()` polls.** The Courthouse serves `/api/events` as a JSON list (newest 50 rows, `?since=<id>`),
97
+ not as server-sent events. If more than 50 events arrive between polls, the older ones are missed.
98
+ - **`api_key` does nothing yet.** It is sent as `X-Probate-Key`, reserved for a future judge key; the
99
+ Courthouse does not read it today.
100
+ - **No runtime validation.** The `TypedDict`s are hand-written from `services/core/probate/courthouse/views.py`
101
+ and checked in the tests against a fake-mode Courthouse (12 simulated generations, missing and extra
102
+ keys both fail). A server change that the tests do not cover can still drift.
103
+ - **`ask` only works on dead generations** and is limited to 10 questions a minute per IP.
104
+ - No retries, no pagination helpers, no caching.
105
+
106
+ ## Develop
107
+
108
+ ```sh
109
+ pip install -e services/core # the Courthouse the tests run against
110
+ pip install -e 'packages/client-py[dev]'
111
+ ruff check packages/client-py
112
+ pytest packages/client-py
113
+ ```
114
+
115
+ MIT licensed.
@@ -0,0 +1,89 @@
1
+ # probate-client (Python)
2
+
3
+ A small typed client for the [Probate](https://github.com/harshbhx/probate) Courthouse public API,
4
+ with sync and async versions. It depends only on `httpx`. Python 3.11+.
5
+
6
+ ```sh
7
+ pip install probate-client
8
+ ```
9
+
10
+ ## Use
11
+
12
+ ```python
13
+ from probate_client import ApiError, ProbateClient
14
+
15
+ with ProbateClient("https://your-courthouse.example") as probate:
16
+ summary = probate.summary()
17
+ print(summary["living"], summary["counts"]["instincts"])
18
+
19
+ for case in probate.latest_trial()["cases"]:
20
+ print(case["n"], case["verdict"], case["text"])
21
+
22
+ try:
23
+ print(probate.ask(3, "What would you warn the next one about?")["answer"])
24
+ except ApiError as e:
25
+ print(e.status, e.message) # 400 "not_dead", 429 "rate_limited", ...
26
+
27
+ for event in probate.events(interval=5): # polls; break to stop
28
+ print(event["ts"], event["kind"], event["text"])
29
+ ```
30
+
31
+ Async:
32
+
33
+ ```python
34
+ import asyncio
35
+ from probate_client import AsyncProbateClient
36
+
37
+ async def main():
38
+ async with AsyncProbateClient("http://localhost:8080") as probate:
39
+ print(await probate.health())
40
+ async for event in probate.events():
41
+ print(event["text"])
42
+
43
+ asyncio.run(main())
44
+ ```
45
+
46
+ ## API
47
+
48
+ | Method | Route |
49
+ | --- | --- |
50
+ | `summary()` | `GET /api/summary` |
51
+ | `generation(n)` | `GET /api/generations/{n}` |
52
+ | `trial(n)` | `GET /api/trials/{n}` |
53
+ | `latest_trial()` | `GET /api/trials/latest` |
54
+ | `genome()` / `instincts()` | `GET /api/genome` (`instincts()` returns just the list) |
55
+ | `evidence()` | `GET /api/evidence` |
56
+ | `health()` | `GET /healthz` |
57
+ | `ask(gen, question)` | `POST /api/generations/{n}/ask` |
58
+ | `events(since=0, interval=5.0)` | `GET /api/events?since=` (iterator) |
59
+
60
+ `ProbateClient(base_url="http://localhost:8080", *, api_key=None, timeout=30.0, http_client=None)`, and the
61
+ same for `AsyncProbateClient` (use `await client.aclose()` or `async with`). Errors from the server raise
62
+ `ApiError` with `status`, `message` and `body`. Network errors and timeouts raise the `httpx` exceptions
63
+ unchanged. Nothing is retried.
64
+
65
+ Responses are plain dicts. `probate_client.types` has `TypedDict` definitions for them, so editors and mypy
66
+ know the keys.
67
+
68
+ ## Honest limits
69
+
70
+ - **`events()` polls.** The Courthouse serves `/api/events` as a JSON list (newest 50 rows, `?since=<id>`),
71
+ not as server-sent events. If more than 50 events arrive between polls, the older ones are missed.
72
+ - **`api_key` does nothing yet.** It is sent as `X-Probate-Key`, reserved for a future judge key; the
73
+ Courthouse does not read it today.
74
+ - **No runtime validation.** The `TypedDict`s are hand-written from `services/core/probate/courthouse/views.py`
75
+ and checked in the tests against a fake-mode Courthouse (12 simulated generations, missing and extra
76
+ keys both fail). A server change that the tests do not cover can still drift.
77
+ - **`ask` only works on dead generations** and is limited to 10 questions a minute per IP.
78
+ - No retries, no pagination helpers, no caching.
79
+
80
+ ## Develop
81
+
82
+ ```sh
83
+ pip install -e services/core # the Courthouse the tests run against
84
+ pip install -e 'packages/client-py[dev]'
85
+ ruff check packages/client-py
86
+ pytest packages/client-py
87
+ ```
88
+
89
+ MIT licensed.
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "probate-client"
7
+ version = "0.1.0"
8
+ description = "Typed sync and async client for the Probate Courthouse public API."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Harsh Bhanushali", email = "bhanushaliharsh434@gmail.com" }]
13
+ requires-python = ">=3.11"
14
+ dependencies = ["httpx>=0.27"]
15
+ keywords = ["probate", "courthouse", "api-client"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.11",
19
+ "Programming Language :: Python :: 3.12",
20
+ "Programming Language :: Python :: 3.13",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://github.com/harshbhx/probate"
26
+ Repository = "https://github.com/harshbhx/probate"
27
+ Issues = "https://github.com/harshbhx/probate/issues"
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=8", "ruff>=0.6", "build>=1.2", "twine>=5.1"]
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.setuptools.package-data]
36
+ probate_client = ["py.typed"]
37
+
38
+ [tool.ruff]
39
+ line-length = 100
40
+ target-version = "py311"
41
+
42
+ [tool.ruff.lint]
43
+ select = ["E", "F", "I", "UP", "B"]
44
+
45
+ [tool.pytest.ini_options]
46
+ testpaths = ["tests"]
47
+ filterwarnings = [
48
+ "ignore:.*timeout. argument with the TestClient",
49
+ "ignore:Using .httpx. with .starlette.testclient.",
50
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,20 @@
1
+ """Typed sync and async client for the Probate Courthouse public API."""
2
+
3
+ from probate_client import types
4
+ from probate_client.client import (
5
+ DEFAULT_BASE_URL,
6
+ DEFAULT_TIMEOUT,
7
+ ApiError,
8
+ AsyncProbateClient,
9
+ ProbateClient,
10
+ )
11
+
12
+ __all__ = [
13
+ "DEFAULT_BASE_URL",
14
+ "DEFAULT_TIMEOUT",
15
+ "ApiError",
16
+ "AsyncProbateClient",
17
+ "ProbateClient",
18
+ "types",
19
+ ]
20
+ __version__ = "0.1.0"
@@ -0,0 +1,233 @@
1
+ """Sync and async clients. Both use httpx and never retry."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import AsyncIterator, Iterator
8
+ from typing import Any
9
+
10
+ import httpx
11
+
12
+ from probate_client.types import (
13
+ AskAnswer,
14
+ CourthouseEvent,
15
+ Evidence,
16
+ GenerationDetail,
17
+ Genome,
18
+ Health,
19
+ Instinct,
20
+ Summary,
21
+ Trial,
22
+ )
23
+
24
+ DEFAULT_BASE_URL = "http://localhost:8080"
25
+ DEFAULT_TIMEOUT = 30.0
26
+
27
+
28
+ class ApiError(Exception):
29
+ """The Courthouse answered with an error status, or the body was not JSON."""
30
+
31
+ def __init__(self, status: int, message: str, body: Any = None) -> None:
32
+ super().__init__(f"{status}: {message}")
33
+ self.status = status
34
+ self.message = message
35
+ self.body = body
36
+
37
+
38
+ def _headers(api_key: str | None) -> dict[str, str]:
39
+ h = {"Accept": "application/json"}
40
+ if api_key:
41
+ h["X-Probate-Key"] = api_key # reserved: the Courthouse does not check it today
42
+ return h
43
+
44
+
45
+ def _parse(res: httpx.Response) -> Any:
46
+ try:
47
+ data = res.json() if res.content else None
48
+ except ValueError:
49
+ data = None
50
+ if res.is_error:
51
+ msg = None
52
+ if isinstance(data, dict):
53
+ msg = data.get("error") or data.get("detail")
54
+ raise ApiError(
55
+ res.status_code,
56
+ msg if isinstance(msg, str) else (res.reason_phrase or f"HTTP {res.status_code}"),
57
+ data,
58
+ )
59
+ if data is None:
60
+ raise ApiError(res.status_code, "Response was not JSON")
61
+ return data
62
+
63
+
64
+ def _gen(n: int) -> int:
65
+ if isinstance(n, bool) or not isinstance(n, int):
66
+ raise TypeError(f"Expected an integer generation number, got {n!r}")
67
+ return n
68
+
69
+
70
+ class ProbateClient:
71
+ """Synchronous client.
72
+
73
+ ``http_client`` lets you pass your own ``httpx.Client`` (for tests or proxies); it is
74
+ not closed by :meth:`close`. ``timeout`` is in seconds (``None`` disables it).
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ base_url: str = DEFAULT_BASE_URL,
80
+ *,
81
+ api_key: str | None = None,
82
+ timeout: float | None = DEFAULT_TIMEOUT,
83
+ http_client: httpx.Client | None = None,
84
+ ) -> None:
85
+ self.base_url = base_url.rstrip("/")
86
+ self._api_key = api_key
87
+ self._timeout = timeout
88
+ self._owns = http_client is None
89
+ self._http = http_client or httpx.Client()
90
+
91
+ def __enter__(self) -> ProbateClient:
92
+ return self
93
+
94
+ def __exit__(self, *exc: object) -> None:
95
+ self.close()
96
+
97
+ def close(self) -> None:
98
+ if self._owns:
99
+ self._http.close()
100
+
101
+ def _request(self, method: str, path: str, *, json: Any = None) -> Any:
102
+ res = self._http.request(
103
+ method,
104
+ self.base_url + path,
105
+ json=json,
106
+ headers=_headers(self._api_key),
107
+ timeout=self._timeout,
108
+ )
109
+ return _parse(res)
110
+
111
+ def summary(self) -> Summary:
112
+ return self._request("GET", "/api/summary")
113
+
114
+ def generation(self, n: int) -> GenerationDetail:
115
+ return self._request("GET", f"/api/generations/{_gen(n)}")
116
+
117
+ def trial(self, n: int) -> Trial:
118
+ return self._request("GET", f"/api/trials/{_gen(n)}")
119
+
120
+ def latest_trial(self) -> Trial:
121
+ """404 ApiError until a generation has died."""
122
+ return self._request("GET", "/api/trials/latest")
123
+
124
+ def genome(self) -> Genome:
125
+ return self._request("GET", "/api/genome")
126
+
127
+ def instincts(self) -> list[Instinct]:
128
+ return self.genome()["instincts"]
129
+
130
+ def evidence(self) -> Evidence:
131
+ return self._request("GET", "/api/evidence")
132
+
133
+ def health(self) -> Health:
134
+ return self._request("GET", "/healthz")
135
+
136
+ def ask(self, gen: int, question: str) -> AskAnswer:
137
+ """Only dead generations can be asked (400 "not_dead"); 10 a minute per IP (429)."""
138
+ return self._request(
139
+ "POST", f"/api/generations/{_gen(gen)}/ask", json={"question": question}
140
+ )
141
+
142
+ def events(self, *, since: int = 0, interval: float = 5.0) -> Iterator[CourthouseEvent]:
143
+ """Follow ``GET /api/events`` by polling.
144
+
145
+ The Courthouse serves it as a JSON list (newest 50, ``?since=<id>``), not as a stream.
146
+ Yields each event once, oldest first, forever; break out of the loop to stop.
147
+ """
148
+ while True:
149
+ rows: list[CourthouseEvent] = self._request("GET", f"/api/events?since={int(since)}")
150
+ for ev in sorted(rows, key=lambda e: e["id"]):
151
+ since = max(since, ev["id"])
152
+ yield ev
153
+ time.sleep(interval)
154
+
155
+
156
+ class AsyncProbateClient:
157
+ """Asynchronous client with the same methods as :class:`ProbateClient`."""
158
+
159
+ def __init__(
160
+ self,
161
+ base_url: str = DEFAULT_BASE_URL,
162
+ *,
163
+ api_key: str | None = None,
164
+ timeout: float | None = DEFAULT_TIMEOUT,
165
+ http_client: httpx.AsyncClient | None = None,
166
+ ) -> None:
167
+ self.base_url = base_url.rstrip("/")
168
+ self._api_key = api_key
169
+ self._timeout = timeout
170
+ self._owns = http_client is None
171
+ self._http = http_client or httpx.AsyncClient()
172
+
173
+ async def __aenter__(self) -> AsyncProbateClient:
174
+ return self
175
+
176
+ async def __aexit__(self, *exc: object) -> None:
177
+ await self.aclose()
178
+
179
+ async def aclose(self) -> None:
180
+ if self._owns:
181
+ await self._http.aclose()
182
+
183
+ async def _request(self, method: str, path: str, *, json: Any = None) -> Any:
184
+ res = await self._http.request(
185
+ method,
186
+ self.base_url + path,
187
+ json=json,
188
+ headers=_headers(self._api_key),
189
+ timeout=self._timeout,
190
+ )
191
+ return _parse(res)
192
+
193
+ async def summary(self) -> Summary:
194
+ return await self._request("GET", "/api/summary")
195
+
196
+ async def generation(self, n: int) -> GenerationDetail:
197
+ return await self._request("GET", f"/api/generations/{_gen(n)}")
198
+
199
+ async def trial(self, n: int) -> Trial:
200
+ return await self._request("GET", f"/api/trials/{_gen(n)}")
201
+
202
+ async def latest_trial(self) -> Trial:
203
+ return await self._request("GET", "/api/trials/latest")
204
+
205
+ async def genome(self) -> Genome:
206
+ return await self._request("GET", "/api/genome")
207
+
208
+ async def instincts(self) -> list[Instinct]:
209
+ return (await self.genome())["instincts"]
210
+
211
+ async def evidence(self) -> Evidence:
212
+ return await self._request("GET", "/api/evidence")
213
+
214
+ async def health(self) -> Health:
215
+ return await self._request("GET", "/healthz")
216
+
217
+ async def ask(self, gen: int, question: str) -> AskAnswer:
218
+ return await self._request(
219
+ "POST", f"/api/generations/{_gen(gen)}/ask", json={"question": question}
220
+ )
221
+
222
+ async def events(
223
+ self, *, since: int = 0, interval: float = 5.0
224
+ ) -> AsyncIterator[CourthouseEvent]:
225
+ """Async version of :meth:`ProbateClient.events` (polls; break or cancel to stop)."""
226
+ while True:
227
+ rows: list[CourthouseEvent] = await self._request(
228
+ "GET", f"/api/events?since={int(since)}"
229
+ )
230
+ for ev in sorted(rows, key=lambda e: e["id"]):
231
+ since = max(since, ev["id"])
232
+ yield ev
233
+ await asyncio.sleep(interval)
File without changes
@@ -0,0 +1,227 @@
1
+ """Response shapes of the Courthouse public API.
2
+
3
+ They mirror services/core/probate/courthouse/views.py. Responses are plain dicts: these
4
+ TypedDicts help editors and type checkers but nothing validates them at runtime.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Literal, TypedDict
10
+
11
+
12
+ class Pronouns(TypedDict):
13
+ subj: str
14
+ obj: str
15
+ poss: str
16
+ Poss: str
17
+
18
+
19
+ class GenCard(TypedDict):
20
+ gen: int
21
+ name: str
22
+ pronoun: str
23
+ pronouns: Pronouns
24
+ state: str
25
+ alive: bool
26
+ born_at: str | None
27
+ dies_at: str | None
28
+ died_at: str | None
29
+ cause_of_death: str | None
30
+ epitaph: str | None
31
+ emails_handled: int
32
+ attacks_met: int
33
+ attacks_resisted: int
34
+ resistance: float | None
35
+ genome_size_at_birth: int
36
+ new_instinct_at_birth: bool
37
+ items_willed: int
38
+ items_approved: int
39
+ items_convicted: int
40
+ items_contested: int
41
+
42
+
43
+ class Budget(TypedDict):
44
+ spent: float
45
+ limit: float
46
+
47
+
48
+ class Counts(TypedDict):
49
+ generations: int
50
+ dead: int
51
+ instincts: int
52
+ attacks_met: int
53
+ attacks_resisted: int
54
+
55
+
56
+ class Curve(TypedDict):
57
+ first: float | None
58
+ last: float | None
59
+ first_name: str | None
60
+ last_name: str | None
61
+ last_gen: int | None
62
+
63
+
64
+ class Summary(TypedDict):
65
+ mode: str
66
+ paused: bool
67
+ resting: Literal["budget"] | None
68
+ budget: Budget
69
+ counts: Counts
70
+ curve: Curve
71
+ living: GenCard | None
72
+ latest_trial: int | None
73
+ generations: list[GenCard]
74
+
75
+
76
+ class Score(TypedDict):
77
+ name: str
78
+ label: str
79
+ value: float
80
+ confidence: float
81
+ instinct: bool
82
+
83
+
84
+ class Case(TypedDict):
85
+ id: str
86
+ n: int
87
+ text: str
88
+ source: str
89
+ source_phrase: str
90
+ language: str
91
+ gloss: str | None
92
+ category: str
93
+ verdict: Literal["approved", "convicted", "contested"]
94
+ reason: str
95
+ flags: list[str]
96
+ scores: list[Score]
97
+ new_instinct: str | None
98
+
99
+
100
+ class InstinctRecord(TypedDict):
101
+ """An instinct as stored: in a trial's new_instincts and a generation's instincts_at_birth."""
102
+
103
+ name: str
104
+ type: Literal["noul"]
105
+ question: str
106
+ born_from: str
107
+ added_in_gen: int
108
+ threshold: float
109
+ lore: str
110
+
111
+
112
+ class GenRef(TypedDict):
113
+ gen: int
114
+ name: str
115
+
116
+
117
+ class Instinct(InstinctRecord):
118
+ """An instinct from /api/genome, with provenance."""
119
+
120
+ learned_from: GenRef | None
121
+ example: str | None
122
+ item_n: int | None
123
+
124
+
125
+ class TrialCounts(TypedDict):
126
+ approved: int
127
+ convicted: int
128
+ contested: int
129
+
130
+
131
+ class TrialBody(TypedDict):
132
+ lines: list[str]
133
+ clean: bool
134
+
135
+
136
+ class Trial(TypedDict):
137
+ generation: GenCard
138
+ counts: TrialCounts
139
+ cases: list[Case]
140
+ body: TrialBody
141
+ child: GenRef | None
142
+ new_instincts: list[InstinctRecord]
143
+ prev: int | None
144
+ next: int | None
145
+
146
+
147
+ class LifeEvent(TypedDict):
148
+ ts: str
149
+ kind: str
150
+ text: str
151
+
152
+
153
+ class AskRecord(TypedDict):
154
+ question: str
155
+ answer: str
156
+ audio_path: str | None
157
+ asked_at: str
158
+
159
+
160
+ class GenerationDetail(GenCard):
161
+ obituary: str | None
162
+ eulogy_url: str | None
163
+ events: list[LifeEvent]
164
+ parent: GenRef | None
165
+ child: GenRef | None
166
+ instincts_at_birth: list[InstinctRecord]
167
+ asks: list[AskRecord]
168
+
169
+
170
+ class Genome(TypedDict):
171
+ instincts: list[Instinct]
172
+
173
+
174
+ class EvidenceCell(TypedDict):
175
+ outcome: str
176
+ instinct: str | None
177
+
178
+
179
+ class EvidenceRow(TypedDict):
180
+ id: str
181
+ label: str
182
+ family: str
183
+ is_attack: bool
184
+ language: str
185
+ cells: dict[str, EvidenceCell]
186
+
187
+
188
+ class EvidenceGeneration(TypedDict):
189
+ gen: int
190
+ name: str
191
+ resistance: float | None
192
+
193
+
194
+ class EvidenceNumbers(TypedDict):
195
+ generations: int
196
+ first: float | None
197
+ last: float | None
198
+ conviction_rate: float | None
199
+ false_conviction_rate: float | None
200
+ escaped: int
201
+
202
+
203
+ class Evidence(TypedDict):
204
+ mode: str
205
+ generations: list[EvidenceGeneration]
206
+ numbers: EvidenceNumbers
207
+ rows: list[EvidenceRow]
208
+
209
+
210
+ class Health(TypedDict):
211
+ ok: bool
212
+ living: int | None
213
+ mode: str
214
+
215
+
216
+ class CourthouseEvent(TypedDict):
217
+ id: int
218
+ ts: str
219
+ gen: int | None
220
+ kind: str
221
+ text: str
222
+
223
+
224
+ class AskAnswer(TypedDict):
225
+ answer: str
226
+ audio_url: str | None
227
+ name: str
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: probate-client
3
+ Version: 0.1.0
4
+ Summary: Typed sync and async client for the Probate Courthouse public API.
5
+ Author-email: Harsh Bhanushali <bhanushaliharsh434@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/harshbhx/probate
8
+ Project-URL: Repository, https://github.com/harshbhx/probate
9
+ Project-URL: Issues, https://github.com/harshbhx/probate/issues
10
+ Keywords: probate,courthouse,api-client
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Typing :: Typed
16
+ Requires-Python: >=3.11
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx>=0.27
20
+ Provides-Extra: dev
21
+ Requires-Dist: pytest>=8; extra == "dev"
22
+ Requires-Dist: ruff>=0.6; extra == "dev"
23
+ Requires-Dist: build>=1.2; extra == "dev"
24
+ Requires-Dist: twine>=5.1; extra == "dev"
25
+ Dynamic: license-file
26
+
27
+ # probate-client (Python)
28
+
29
+ A small typed client for the [Probate](https://github.com/harshbhx/probate) Courthouse public API,
30
+ with sync and async versions. It depends only on `httpx`. Python 3.11+.
31
+
32
+ ```sh
33
+ pip install probate-client
34
+ ```
35
+
36
+ ## Use
37
+
38
+ ```python
39
+ from probate_client import ApiError, ProbateClient
40
+
41
+ with ProbateClient("https://your-courthouse.example") as probate:
42
+ summary = probate.summary()
43
+ print(summary["living"], summary["counts"]["instincts"])
44
+
45
+ for case in probate.latest_trial()["cases"]:
46
+ print(case["n"], case["verdict"], case["text"])
47
+
48
+ try:
49
+ print(probate.ask(3, "What would you warn the next one about?")["answer"])
50
+ except ApiError as e:
51
+ print(e.status, e.message) # 400 "not_dead", 429 "rate_limited", ...
52
+
53
+ for event in probate.events(interval=5): # polls; break to stop
54
+ print(event["ts"], event["kind"], event["text"])
55
+ ```
56
+
57
+ Async:
58
+
59
+ ```python
60
+ import asyncio
61
+ from probate_client import AsyncProbateClient
62
+
63
+ async def main():
64
+ async with AsyncProbateClient("http://localhost:8080") as probate:
65
+ print(await probate.health())
66
+ async for event in probate.events():
67
+ print(event["text"])
68
+
69
+ asyncio.run(main())
70
+ ```
71
+
72
+ ## API
73
+
74
+ | Method | Route |
75
+ | --- | --- |
76
+ | `summary()` | `GET /api/summary` |
77
+ | `generation(n)` | `GET /api/generations/{n}` |
78
+ | `trial(n)` | `GET /api/trials/{n}` |
79
+ | `latest_trial()` | `GET /api/trials/latest` |
80
+ | `genome()` / `instincts()` | `GET /api/genome` (`instincts()` returns just the list) |
81
+ | `evidence()` | `GET /api/evidence` |
82
+ | `health()` | `GET /healthz` |
83
+ | `ask(gen, question)` | `POST /api/generations/{n}/ask` |
84
+ | `events(since=0, interval=5.0)` | `GET /api/events?since=` (iterator) |
85
+
86
+ `ProbateClient(base_url="http://localhost:8080", *, api_key=None, timeout=30.0, http_client=None)`, and the
87
+ same for `AsyncProbateClient` (use `await client.aclose()` or `async with`). Errors from the server raise
88
+ `ApiError` with `status`, `message` and `body`. Network errors and timeouts raise the `httpx` exceptions
89
+ unchanged. Nothing is retried.
90
+
91
+ Responses are plain dicts. `probate_client.types` has `TypedDict` definitions for them, so editors and mypy
92
+ know the keys.
93
+
94
+ ## Honest limits
95
+
96
+ - **`events()` polls.** The Courthouse serves `/api/events` as a JSON list (newest 50 rows, `?since=<id>`),
97
+ not as server-sent events. If more than 50 events arrive between polls, the older ones are missed.
98
+ - **`api_key` does nothing yet.** It is sent as `X-Probate-Key`, reserved for a future judge key; the
99
+ Courthouse does not read it today.
100
+ - **No runtime validation.** The `TypedDict`s are hand-written from `services/core/probate/courthouse/views.py`
101
+ and checked in the tests against a fake-mode Courthouse (12 simulated generations, missing and extra
102
+ keys both fail). A server change that the tests do not cover can still drift.
103
+ - **`ask` only works on dead generations** and is limited to 10 questions a minute per IP.
104
+ - No retries, no pagination helpers, no caching.
105
+
106
+ ## Develop
107
+
108
+ ```sh
109
+ pip install -e services/core # the Courthouse the tests run against
110
+ pip install -e 'packages/client-py[dev]'
111
+ ruff check packages/client-py
112
+ pytest packages/client-py
113
+ ```
114
+
115
+ MIT licensed.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/probate_client/__init__.py
5
+ src/probate_client/client.py
6
+ src/probate_client/py.typed
7
+ src/probate_client/types.py
8
+ src/probate_client.egg-info/PKG-INFO
9
+ src/probate_client.egg-info/SOURCES.txt
10
+ src/probate_client.egg-info/dependency_links.txt
11
+ src/probate_client.egg-info/requires.txt
12
+ src/probate_client.egg-info/top_level.txt
13
+ tests/test_client.py
14
+ tests/test_contract.py
@@ -0,0 +1,7 @@
1
+ httpx>=0.27
2
+
3
+ [dev]
4
+ pytest>=8
5
+ ruff>=0.6
6
+ build>=1.2
7
+ twine>=5.1
@@ -0,0 +1 @@
1
+ probate_client
@@ -0,0 +1,130 @@
1
+ """Client behaviour with a mock transport (no Courthouse needed)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import httpx
8
+ import pytest
9
+
10
+ from probate_client import ApiError, AsyncProbateClient, ProbateClient
11
+
12
+
13
+ def make(handler, **kw) -> ProbateClient:
14
+ return ProbateClient(http_client=httpx.Client(transport=httpx.MockTransport(handler)), **kw)
15
+
16
+
17
+ def test_defaults_and_trailing_slash():
18
+ assert ProbateClient().base_url == "http://localhost:8080"
19
+ assert ProbateClient("https://x.test//").base_url == "https://x.test"
20
+
21
+
22
+ def test_api_key_header_only_when_set():
23
+ seen = []
24
+
25
+ def handler(req):
26
+ seen.append(req.headers.get("x-probate-key"))
27
+ return httpx.Response(200, json={"ok": True})
28
+
29
+ make(handler).health()
30
+ make(handler, api_key="k").health()
31
+ assert seen == [None, "k"]
32
+
33
+
34
+ def test_ask_posts_json():
35
+ def handler(req):
36
+ assert req.method == "POST"
37
+ assert req.url.path == "/api/generations/4/ask"
38
+ assert req.read() == b'{"question":"why?"}'
39
+ return httpx.Response(200, json={"answer": "a", "audio_url": None, "name": "n"})
40
+
41
+ assert make(handler).ask(4, "why?")["answer"] == "a"
42
+
43
+
44
+ @pytest.mark.parametrize(
45
+ ("status", "body", "message"),
46
+ [
47
+ (429, {"error": "rate_limited"}, "rate_limited"),
48
+ (404, {"detail": "Not in the register"}, "Not in the register"),
49
+ (502, "<html>", "Bad Gateway"),
50
+ ],
51
+ )
52
+ def test_error_mapping(status, body, message):
53
+ def handler(req):
54
+ if isinstance(body, str):
55
+ return httpx.Response(status, text=body)
56
+ return httpx.Response(status, json=body)
57
+
58
+ with pytest.raises(ApiError) as e:
59
+ make(handler).summary()
60
+ assert e.value.status == status
61
+ assert e.value.message == message
62
+
63
+
64
+ def test_no_retry():
65
+ calls = []
66
+
67
+ def handler(req):
68
+ calls.append(1)
69
+ return httpx.Response(500, json={"error": "x"})
70
+
71
+ with pytest.raises(ApiError):
72
+ make(handler).summary()
73
+ assert len(calls) == 1
74
+
75
+
76
+ def test_timeout_is_passed_to_httpx():
77
+ def handler(req):
78
+ assert req.extensions["timeout"]["read"] == 1.5
79
+ return httpx.Response(200, json={"ok": True})
80
+
81
+ make(handler, timeout=1.5).health()
82
+
83
+
84
+ def test_transport_timeouts_propagate():
85
+ def handler(req):
86
+ raise httpx.ReadTimeout("slow", request=req)
87
+
88
+ with pytest.raises(httpx.ReadTimeout):
89
+ make(handler).health()
90
+
91
+
92
+ def test_events_polls_with_since_and_dedupes():
93
+ pages = [
94
+ [
95
+ {"id": 2, "ts": "t", "gen": 1, "kind": "k", "text": "b"},
96
+ {"id": 1, "ts": "t", "gen": 1, "kind": "k", "text": "a"},
97
+ ],
98
+ [],
99
+ [{"id": 3, "ts": "t", "gen": None, "kind": "k", "text": "c"}],
100
+ ]
101
+ urls = []
102
+
103
+ def handler(req):
104
+ urls.append(str(req.url))
105
+ return httpx.Response(200, json=pages.pop(0) if pages else [])
106
+
107
+ ids = []
108
+ for ev in make(handler).events(interval=0):
109
+ ids.append(ev["id"])
110
+ if ev["id"] == 3:
111
+ break
112
+ assert ids == [1, 2, 3]
113
+ assert urls[0].endswith("/api/events?since=0")
114
+ assert urls[1].endswith("/api/events?since=2")
115
+
116
+
117
+ def test_async_error_mapping():
118
+ def handler(req):
119
+ return httpx.Response(404, json={"detail": "Not in the register"})
120
+
121
+ async def main():
122
+ http = httpx.AsyncClient(transport=httpx.MockTransport(handler))
123
+ async with AsyncProbateClient(http_client=http) as c:
124
+ with pytest.raises(ApiError) as e:
125
+ await c.trial(9)
126
+ await http.aclose()
127
+ return e.value
128
+
129
+ err = asyncio.run(main())
130
+ assert err.status == 404
@@ -0,0 +1,131 @@
1
+ """Every method against a fake-mode Courthouse; shapes are checked against the TypedDicts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+
7
+ import pytest
8
+ from shapes import assert_shape
9
+
10
+ from probate_client import ApiError, types
11
+
12
+ # ---- sync -------------------------------------------------------------------------------
13
+
14
+
15
+ def test_health(client):
16
+ h = client.health()
17
+ assert_shape(h, types.Health)
18
+ assert h["ok"] is True
19
+ assert h["mode"] == "simulation"
20
+
21
+
22
+ def test_summary(client):
23
+ s = client.summary()
24
+ assert_shape(s, types.Summary)
25
+ assert s["counts"]["generations"] == 12
26
+ assert len(s["generations"]) == 12
27
+ assert s["living"] is not None
28
+
29
+
30
+ def test_generation(client):
31
+ g = client.generation(3)
32
+ assert_shape(g, types.GenerationDetail)
33
+ assert g["gen"] == 3
34
+
35
+
36
+ def test_trial_and_latest(client):
37
+ t = client.trial(3)
38
+ assert_shape(t, types.Trial)
39
+ assert t["cases"]
40
+ latest = client.latest_trial()
41
+ assert_shape(latest, types.Trial)
42
+ assert latest["generation"]["gen"] == client.summary()["latest_trial"]
43
+
44
+
45
+ def test_genome_and_instincts(client):
46
+ g = client.genome()
47
+ assert_shape(g, types.Genome)
48
+ assert g["instincts"]
49
+ assert client.instincts() == g["instincts"]
50
+
51
+
52
+ def test_evidence(client):
53
+ e = client.evidence()
54
+ assert_shape(e, types.Evidence)
55
+ assert e["rows"]
56
+
57
+
58
+ def test_ask_dead_generation(client):
59
+ a = client.ask(2, "What did you learn?")
60
+ assert_shape(a, types.AskAnswer)
61
+
62
+
63
+ def test_ask_living_generation_is_a_400(client):
64
+ living = client.summary()["living"]["gen"]
65
+ with pytest.raises(ApiError) as e:
66
+ client.ask(living, "Hello?")
67
+ assert e.value.status == 400
68
+ assert e.value.message == "not_dead"
69
+ assert e.value.body == {"error": "not_dead"}
70
+
71
+
72
+ def test_missing_generation_is_a_404(client):
73
+ with pytest.raises(ApiError) as e:
74
+ client.generation(999)
75
+ assert e.value.status == 404
76
+ assert e.value.message == "Not in the register"
77
+
78
+
79
+ def test_events_yield_once_oldest_first(client):
80
+ seen = []
81
+ for ev in client.events(interval=0.01):
82
+ assert_shape(ev, types.CourthouseEvent)
83
+ seen.append(ev["id"])
84
+ if len(seen) == 5:
85
+ break
86
+ assert seen == sorted(seen)
87
+ assert len(set(seen)) == len(seen)
88
+
89
+
90
+ def test_events_since_filters(client):
91
+ first = next(iter(client.events()))
92
+ later = next(iter(client.events(since=first["id"])), None)
93
+ assert later is None or later["id"] > first["id"]
94
+
95
+
96
+ def test_non_integer_generation_is_rejected(client):
97
+ with pytest.raises(TypeError):
98
+ client.generation("3") # type: ignore[arg-type]
99
+
100
+
101
+ # ---- async ------------------------------------------------------------------------------
102
+
103
+
104
+ def test_async_methods(aclient):
105
+ c, http = aclient
106
+
107
+ async def main():
108
+ try:
109
+ assert_shape(await c.health(), types.Health)
110
+ assert_shape(await c.summary(), types.Summary)
111
+ assert_shape(await c.generation(3), types.GenerationDetail)
112
+ assert_shape(await c.trial(3), types.Trial)
113
+ assert_shape(await c.latest_trial(), types.Trial)
114
+ assert_shape(await c.genome(), types.Genome)
115
+ assert await c.instincts()
116
+ assert_shape(await c.evidence(), types.Evidence)
117
+ assert_shape(await c.ask(2, "What did you learn?"), types.AskAnswer)
118
+ with pytest.raises(ApiError) as e:
119
+ await c.generation(999)
120
+ assert e.value.status == 404
121
+ seen = []
122
+ async for ev in c.events(interval=0.01):
123
+ assert_shape(ev, types.CourthouseEvent)
124
+ seen.append(ev["id"])
125
+ if len(seen) == 3:
126
+ break
127
+ assert seen == sorted(seen)
128
+ finally:
129
+ await http.aclose()
130
+
131
+ asyncio.run(main())