webcite 0.1.0__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.
webcite/__init__.py ADDED
@@ -0,0 +1,41 @@
1
+ """Python SDK for the Webcite API: parse documents, verify claims and bind citations to quotes."""
2
+
3
+ from ._async_client import AsyncWebcite
4
+ from ._client import Webcite
5
+ from ._errors import (
6
+ APIError,
7
+ AuthenticationError,
8
+ BadRequestError,
9
+ ConflictError,
10
+ IncompleteStreamError,
11
+ InsufficientCreditsError,
12
+ NotFoundError,
13
+ PayloadTooLargeError,
14
+ PermissionDeniedError,
15
+ RateLimitError,
16
+ ServerError,
17
+ WebciteConnectionError,
18
+ WebciteError,
19
+ WebciteTimeoutError,
20
+ )
21
+ from ._version import __version__
22
+
23
+ __all__ = [
24
+ "APIError",
25
+ "AsyncWebcite",
26
+ "AuthenticationError",
27
+ "BadRequestError",
28
+ "ConflictError",
29
+ "IncompleteStreamError",
30
+ "InsufficientCreditsError",
31
+ "NotFoundError",
32
+ "PayloadTooLargeError",
33
+ "PermissionDeniedError",
34
+ "RateLimitError",
35
+ "ServerError",
36
+ "Webcite",
37
+ "WebciteConnectionError",
38
+ "WebciteError",
39
+ "WebciteTimeoutError",
40
+ "__version__",
41
+ ]
@@ -0,0 +1,453 @@
1
+ """Asynchronous client. Same methods as Webcite, awaited."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from typing import Any, AsyncIterator, List, Mapping, Optional, Sequence, cast
8
+
9
+ import httpx
10
+
11
+ from . import _requests as R
12
+ from ._base import (
13
+ SSEDecoder,
14
+ StreamTracker,
15
+ TimeoutArg,
16
+ default_headers,
17
+ parse_json,
18
+ request_kwargs,
19
+ resolve_config,
20
+ retry_delay,
21
+ should_retry,
22
+ )
23
+ from ._errors import (
24
+ IncompleteStreamError,
25
+ WebciteConnectionError,
26
+ WebciteTimeoutError,
27
+ error_from_response,
28
+ )
29
+ from .types import (
30
+ AskJob,
31
+ Balance,
32
+ CitationList,
33
+ ExtractResponse,
34
+ JSONObject,
35
+ StreamEvent,
36
+ UploadResponse,
37
+ VerifyResponse,
38
+ )
39
+
40
+
41
+ class AsyncWebcite:
42
+ """Async client for the Webcite API.
43
+
44
+ ``api_key`` defaults to ``WEBCITE_API_KEY``; ``base_url`` defaults to ``WEBCITE_API_URL`` or
45
+ https://api.webcite.co. GET requests and verifications (sent with an Idempotency-Key) are
46
+ retried on 429 and 5xx; other calls are never repeated automatically.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ api_key: Optional[str] = None,
52
+ *,
53
+ base_url: Optional[str] = None,
54
+ timeout: TimeoutArg = None,
55
+ max_retries: Optional[int] = None,
56
+ http_client: Optional[httpx.AsyncClient] = None,
57
+ ) -> None:
58
+ self._config = resolve_config(api_key, base_url, timeout, max_retries)
59
+ self._http = http_client or httpx.AsyncClient()
60
+ self._owns_http = http_client is None
61
+
62
+ @property
63
+ def base_url(self) -> str:
64
+ return self._config.base_url
65
+
66
+ async def close(self) -> None:
67
+ if self._owns_http:
68
+ await self._http.aclose()
69
+
70
+ async def __aenter__(self) -> AsyncWebcite:
71
+ return self
72
+
73
+ async def __aexit__(self, *_: object) -> None:
74
+ await self.close()
75
+
76
+ # -- transport ---------------------------------------------------------------------------
77
+
78
+ def _build(self, spec: R.RequestSpec) -> httpx.Request:
79
+ kwargs = request_kwargs(spec)
80
+ headers = {**default_headers(self._config.api_key), **kwargs.pop("headers")}
81
+ return self._http.build_request(
82
+ spec.method,
83
+ self._config.base_url + spec.path,
84
+ headers=headers,
85
+ timeout=self._config.timeout,
86
+ **kwargs,
87
+ )
88
+
89
+ async def _send_raw(self, spec: R.RequestSpec, stream: bool = False) -> httpx.Response:
90
+ attempt = 0
91
+ while True:
92
+ status: Optional[int] = None
93
+ wait_hint: Optional[float] = None
94
+ try:
95
+ response = await self._http.send(self._build(spec), stream=stream)
96
+ if response.status_code < 400:
97
+ return response
98
+ if stream:
99
+ await response.aread()
100
+ status = response.status_code
101
+ error = error_from_response(status, response.headers, response.text)
102
+ wait_hint = error.retry_after
103
+ if not should_retry(spec, status, attempt, self._config.max_retries):
104
+ raise error
105
+ except httpx.TimeoutException as exc:
106
+ if not should_retry(spec, None, attempt, self._config.max_retries):
107
+ raise WebciteTimeoutError(_timeout_message(spec)) from exc
108
+ except httpx.TransportError as exc:
109
+ if not should_retry(spec, None, attempt, self._config.max_retries):
110
+ raise WebciteConnectionError(f"Could not reach {self.base_url}: {exc}") from exc
111
+ await asyncio.sleep(retry_delay(attempt, wait_hint))
112
+ attempt += 1
113
+
114
+ async def _send(self, spec: R.RequestSpec) -> Any:
115
+ return parse_json(await self._send_raw(spec))
116
+
117
+ async def _stream(self, spec: R.RequestSpec) -> AsyncIterator[StreamEvent]:
118
+ response = await self._send_raw(spec, stream=True)
119
+ tracker, decoder = StreamTracker(), SSEDecoder()
120
+ try:
121
+ async for line in response.aiter_lines():
122
+ event = decoder.feed(line)
123
+ if event is None:
124
+ continue
125
+ failure = tracker.add(event)
126
+ yield cast(StreamEvent, event)
127
+ if failure:
128
+ raise IncompleteStreamError(failure, tracker.events)
129
+ except httpx.HTTPError as exc:
130
+ raise IncompleteStreamError(
131
+ f"Verification stream disconnected: {exc}", tracker.events
132
+ ) from exc
133
+ finally:
134
+ await response.aclose()
135
+ reason = tracker.final_failure()
136
+ if reason:
137
+ raise IncompleteStreamError(reason, tracker.events)
138
+
139
+ # -- verification ------------------------------------------------------------------------
140
+
141
+ async def verify(
142
+ self,
143
+ claim: str,
144
+ *,
145
+ source_urls: Optional[Sequence[str]] = None,
146
+ filters: Optional[Mapping[str, Any]] = None,
147
+ thread_id: Optional[str] = None,
148
+ include_stance: Optional[bool] = None,
149
+ include_verdict: Optional[bool] = None,
150
+ decompose_claim: Optional[bool] = None,
151
+ include_numeric_assess: Optional[bool] = None,
152
+ include_source_reads: Optional[bool] = None,
153
+ evidence_scope: Optional[Mapping[str, Any]] = None,
154
+ idempotency_key: Optional[str] = None,
155
+ ) -> VerifyResponse:
156
+ """Verify one claim against web sources (POST /api/v1/verify). 4 credits by default."""
157
+ return cast(
158
+ VerifyResponse,
159
+ await self._send(
160
+ R.verify(
161
+ claim,
162
+ source_urls=source_urls,
163
+ filters=filters,
164
+ thread_id=thread_id,
165
+ include_stance=include_stance,
166
+ include_verdict=include_verdict,
167
+ decompose_claim=decompose_claim,
168
+ include_numeric_assess=include_numeric_assess,
169
+ include_source_reads=include_source_reads,
170
+ evidence_scope=evidence_scope,
171
+ idempotency_key=idempotency_key,
172
+ )
173
+ ),
174
+ )
175
+
176
+ def verify_stream(
177
+ self,
178
+ claim: str,
179
+ *,
180
+ source_urls: Optional[Sequence[str]] = None,
181
+ filters: Optional[Mapping[str, Any]] = None,
182
+ thread_id: Optional[str] = None,
183
+ include_stance: Optional[bool] = None,
184
+ include_verdict: Optional[bool] = None,
185
+ decompose_claim: Optional[bool] = None,
186
+ ) -> AsyncIterator[StreamEvent]:
187
+ """Stream verification events. Raises IncompleteStreamError without result and done."""
188
+ return self._stream(
189
+ R.verify(
190
+ claim,
191
+ source_urls=source_urls,
192
+ filters=filters,
193
+ thread_id=thread_id,
194
+ include_stance=include_stance,
195
+ include_verdict=include_verdict,
196
+ decompose_claim=decompose_claim,
197
+ stream=True,
198
+ )
199
+ )
200
+
201
+ async def verify_batch(
202
+ self,
203
+ items: Sequence[Mapping[str, Any]],
204
+ *,
205
+ evidence_scope: Optional[Mapping[str, Any]] = None,
206
+ ) -> List[JSONObject]:
207
+ """Check quotes against their sources in one call (POST /api/v1/verify/batch)."""
208
+ return cast(
209
+ List[JSONObject], await self._send(R.verify_batch(items, evidence_scope=evidence_scope))
210
+ )
211
+
212
+ async def verify_feedback(
213
+ self, token: str, verdict: str, note: Optional[str] = None
214
+ ) -> JSONObject:
215
+ """Record correct, incorrect or unsure on a verification result."""
216
+ return cast(JSONObject, await self._send(R.verify_feedback(token, verdict, note)))
217
+
218
+ async def verify_numeric(self, body: Mapping[str, Any]) -> JSONObject:
219
+ """Check numeric arithmetic (POST /api/v2/verify/numeric)."""
220
+ return cast(JSONObject, await self._send(R.verify_numeric(body)))
221
+
222
+ async def search(
223
+ self,
224
+ query: str,
225
+ *,
226
+ limit: Optional[int] = None,
227
+ filters: Optional[Mapping[str, Any]] = None,
228
+ ) -> VerifyResponse:
229
+ """Search for sources (POST /api/v1/sources/search)."""
230
+ return cast(VerifyResponse, await self._send(R.search(query, limit=limit, filters=filters)))
231
+
232
+ # -- citations -----------------------------------------------------------------------
233
+
234
+ async def list_citations(
235
+ self,
236
+ *,
237
+ page: Optional[int] = None,
238
+ limit: Optional[int] = None,
239
+ fields: Optional[str] = None,
240
+ thread_id: Optional[str] = None,
241
+ ) -> CitationList:
242
+ return cast(
243
+ CitationList,
244
+ await self._send(
245
+ R.list_citations(page=page, limit=limit, fields=fields, thread_id=thread_id)
246
+ ),
247
+ )
248
+
249
+ async def get_citation(self, citation_id: str) -> JSONObject:
250
+ return cast(JSONObject, await self._send(R.get_citation(citation_id)))
251
+
252
+ async def source_preview(
253
+ self,
254
+ *,
255
+ url: Optional[str] = None,
256
+ asset_id: Optional[str] = None,
257
+ page: Optional[int] = None,
258
+ quote: Optional[str] = None,
259
+ **fields: Any,
260
+ ) -> JSONObject:
261
+ """Show the evidence passage at a URL or in an uploaded file."""
262
+ return cast(
263
+ JSONObject,
264
+ await self._send(
265
+ R.source_preview(
266
+ {"url": url, "asset_id": asset_id, "page": page, "quote": quote, **fields}
267
+ )
268
+ ),
269
+ )
270
+
271
+ # -- documents -----------------------------------------------------------------------
272
+
273
+ async def upload(self, file: R.FileInput, *, filename: Optional[str] = None) -> UploadResponse:
274
+ """Store a file (path, bytes or binary file object). Free. Keep data.asset_id."""
275
+ return cast(UploadResponse, await self._send(R.upload(file, filename)))
276
+
277
+ async def upload_url(self, url: str, *, filename: Optional[str] = None) -> UploadResponse:
278
+ """Store the file at a public HTTPS URL."""
279
+ return cast(UploadResponse, await self._send(R.upload_url(url, filename)))
280
+
281
+ async def extract(
282
+ self,
283
+ asset_id: Optional[str] = None,
284
+ *,
285
+ asset_url: Optional[str] = None,
286
+ mode: Optional[str] = None,
287
+ refresh: Optional[bool] = None,
288
+ ) -> ExtractResponse:
289
+ """Read a document as Markdown with per-page units. Runs until every page is read."""
290
+ return cast(
291
+ ExtractResponse,
292
+ await self._send(R.extract("", asset_id, asset_url, mode=mode, refresh=refresh)),
293
+ )
294
+
295
+ async def extract_visual_rendition(
296
+ self,
297
+ asset_id: Optional[str] = None,
298
+ *,
299
+ asset_url: Optional[str] = None,
300
+ source_version_id: Optional[str] = None,
301
+ refresh: Optional[bool] = None,
302
+ ) -> JSONObject:
303
+ return cast(
304
+ JSONObject,
305
+ await self._send(
306
+ R.extract(
307
+ "/visual-rendition",
308
+ asset_id,
309
+ asset_url,
310
+ visual_rendition=True,
311
+ source_version_id=source_version_id,
312
+ refresh=refresh,
313
+ )
314
+ ),
315
+ )
316
+
317
+ async def extract_pages(
318
+ self,
319
+ asset_id: Optional[str] = None,
320
+ *,
321
+ asset_url: Optional[str] = None,
322
+ mode: Optional[str] = None,
323
+ ) -> JSONObject:
324
+ """Extract anchored chunks ready to index and cite."""
325
+ return cast(
326
+ JSONObject, await self._send(R.extract("/pages", asset_id, asset_url, mode=mode))
327
+ )
328
+
329
+ async def extract_figures(
330
+ self, asset_id: Optional[str] = None, *, asset_url: Optional[str] = None
331
+ ) -> JSONObject:
332
+ """Extract every recognised number as a tagged, source-grounded figure."""
333
+ return cast(JSONObject, await self._send(R.extract("/figures", asset_id, asset_url)))
334
+
335
+ async def classify(
336
+ self,
337
+ asset_id: Optional[str] = None,
338
+ *,
339
+ asset_url: Optional[str] = None,
340
+ taxonomy: Optional[str] = None,
341
+ ) -> JSONObject:
342
+ return cast(JSONObject, await self._send(R.classify(asset_id, asset_url, taxonomy)))
343
+
344
+ async def gaps(
345
+ self,
346
+ category: str,
347
+ docs: Sequence[Mapping[str, Any]],
348
+ *,
349
+ stage: Optional[str] = None,
350
+ taxonomy: Optional[str] = None,
351
+ ) -> JSONObject:
352
+ return cast(
353
+ JSONObject, await self._send(R.gaps(category, docs, stage=stage, taxonomy=taxonomy))
354
+ )
355
+
356
+ async def ask(
357
+ self,
358
+ question: str,
359
+ document_text: str,
360
+ *,
361
+ document_name: Optional[str] = None,
362
+ has_text_layer: Optional[bool] = None,
363
+ top_k: Optional[int] = None,
364
+ ) -> AskJob:
365
+ """Queue a question over document text. Poll with get_ask() or wait_for_ask()."""
366
+ return cast(
367
+ AskJob,
368
+ await self._send(
369
+ R.ask(
370
+ question,
371
+ document_text,
372
+ document_name=document_name,
373
+ has_text_layer=has_text_layer,
374
+ top_k=top_k,
375
+ )
376
+ ),
377
+ )
378
+
379
+ async def get_ask(self, job_id: str) -> AskJob:
380
+ return cast(AskJob, await self._send(R.get_ask(job_id)))
381
+
382
+ async def wait_for_ask(
383
+ self, job_id: str, *, poll_interval: float = 2.0, max_wait: Optional[float] = 600.0
384
+ ) -> AskJob:
385
+ """Poll until done or failed. After max_wait, returns the latest job view unchanged."""
386
+ started = time.monotonic()
387
+ while True:
388
+ job = await self.get_ask(job_id)
389
+ if job.get("status") in R.ASK_TERMINAL:
390
+ return job
391
+ if max_wait is not None and time.monotonic() - started >= max_wait:
392
+ return job
393
+ await asyncio.sleep(poll_interval)
394
+
395
+ async def analyze_conflicts(
396
+ self,
397
+ figures: Sequence[Mapping[str, Any]],
398
+ *,
399
+ fx_rates: Optional[Sequence[Mapping[str, Any]]] = None,
400
+ precedence_rules: Optional[Sequence[Mapping[str, Any]]] = None,
401
+ ) -> JSONObject:
402
+ return cast(
403
+ JSONObject,
404
+ await self._send(
405
+ R.analyze_conflicts(figures, fx_rates=fx_rates, precedence_rules=precedence_rules)
406
+ ),
407
+ )
408
+
409
+ async def analyze_document(self, asset_id: str) -> JSONObject:
410
+ return cast(JSONObject, await self._send(R.analyze_document(asset_id)))
411
+
412
+ async def accuracy(self) -> JSONObject:
413
+ return cast(JSONObject, await self._send(R.accuracy()))
414
+
415
+ async def balance(self) -> Balance:
416
+ """Read remaining, used and total credits. Free."""
417
+ return cast(Balance, await self._send(R.balance()))
418
+
419
+ # -- retained sources (v2) -----------------------------------------------------------
420
+
421
+ async def register_source(
422
+ self, asset_id: str, file: R.FileInput, *, filename: Optional[str] = None
423
+ ) -> JSONObject:
424
+ return cast(JSONObject, await self._send(R.register_source(asset_id, file, filename)))
425
+
426
+ async def publish_text_representation(self, version_id: str) -> JSONObject:
427
+ return cast(JSONObject, await self._send(R.publish_text_representation(version_id)))
428
+
429
+ async def latest_representation(self, version_id: str) -> JSONObject:
430
+ return cast(JSONObject, await self._send(R.latest_representation(version_id)))
431
+
432
+ async def source_unit(
433
+ self, version_id: str, representation_id: str, unit_id: str
434
+ ) -> JSONObject:
435
+ return cast(
436
+ JSONObject, await self._send(R.source_unit(version_id, representation_id, unit_id))
437
+ )
438
+
439
+ async def prepare_ocr_rescue(self, version_id: str, representation_id: str) -> JSONObject:
440
+ return cast(
441
+ JSONObject, await self._send(R.prepare_ocr_rescue(version_id, representation_id))
442
+ )
443
+
444
+
445
+ def _timeout_message(spec: R.RequestSpec) -> str:
446
+ return (
447
+ f"{spec.method} {spec.path} did not answer within the client timeout. The server may "
448
+ "still have completed the work; keep any operation IDs and check before repeating a "
449
+ "paid call. Raise timeout= for long documents."
450
+ )
451
+
452
+
453
+ __all__ = ["AsyncWebcite"]
webcite/_base.py ADDED
@@ -0,0 +1,166 @@
1
+ """Configuration, headers, retry policy and response handling shared by both clients."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import platform
8
+ import random
9
+ from dataclasses import dataclass
10
+ from typing import Any, Dict, List, Mapping, Optional, Union
11
+
12
+ import httpx
13
+
14
+ from ._errors import MISSING_KEY_STEP, AuthenticationError, error_from_response
15
+ from ._requests import RequestSpec
16
+ from ._version import __version__
17
+
18
+ DEFAULT_BASE_URL = "https://api.webcite.co"
19
+ # Extraction keeps the request open while every page is read; the docs use 15 minutes.
20
+ DEFAULT_TIMEOUT = httpx.Timeout(900.0, connect=15.0)
21
+ DEFAULT_MAX_RETRIES = 2
22
+ SURFACE = "sdk-python"
23
+ RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
24
+ MAX_RETRY_DELAY = 30.0
25
+
26
+ TimeoutArg = Union[float, httpx.Timeout, None]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Config:
31
+ api_key: str
32
+ base_url: str
33
+ timeout: httpx.Timeout
34
+ max_retries: int
35
+
36
+
37
+ def resolve_config(
38
+ api_key: Optional[str], base_url: Optional[str], timeout: TimeoutArg, max_retries: Optional[int]
39
+ ) -> Config:
40
+ key = api_key or os.environ.get("WEBCITE_API_KEY", "")
41
+ if not key.strip():
42
+ raise AuthenticationError(
43
+ "Set WEBCITE_API_KEY or pass api_key= to authenticate.",
44
+ code="missing_api_key",
45
+ doc_url="https://webcite.co/api-docs/authentication",
46
+ next_step=MISSING_KEY_STEP,
47
+ )
48
+ url = (base_url or os.environ.get("WEBCITE_API_URL") or DEFAULT_BASE_URL).rstrip("/")
49
+ resolved_timeout = (
50
+ timeout
51
+ if isinstance(timeout, httpx.Timeout)
52
+ else (DEFAULT_TIMEOUT if timeout is None else httpx.Timeout(timeout))
53
+ )
54
+ retries = DEFAULT_MAX_RETRIES if max_retries is None else max(0, max_retries)
55
+ return Config(key.strip(), url, resolved_timeout, retries)
56
+
57
+
58
+ def default_headers(api_key: str) -> Dict[str, str]:
59
+ return {
60
+ "x-api-key": api_key,
61
+ "x-webcite-surface": SURFACE,
62
+ "User-Agent": f"webcite-python/{__version__} python/{platform.python_version()}",
63
+ "Accept": "application/json",
64
+ }
65
+
66
+
67
+ def request_kwargs(spec: RequestSpec) -> Dict[str, Any]:
68
+ headers: Dict[str, str] = {}
69
+ if spec.idempotency_key:
70
+ headers["Idempotency-Key"] = spec.idempotency_key
71
+ if spec.stream:
72
+ headers["Accept"] = "text/event-stream"
73
+ kwargs: Dict[str, Any] = {"headers": headers}
74
+ for name in ("json", "params", "files", "data"):
75
+ value = getattr(spec, name)
76
+ if value is not None:
77
+ kwargs[name] = value
78
+ return kwargs
79
+
80
+
81
+ def retry_delay(attempt: int, retry_after: Optional[float]) -> float:
82
+ if retry_after is not None:
83
+ return min(retry_after, MAX_RETRY_DELAY)
84
+ base: float = min(0.5 * float(2**attempt), 8.0)
85
+ return base * (0.75 + random.random() / 2)
86
+
87
+
88
+ def should_retry(spec: RequestSpec, status: Optional[int], attempt: int, max_retries: int) -> bool:
89
+ if attempt >= max_retries or not spec.retryable:
90
+ return False
91
+ return status is None or status in RETRY_STATUSES
92
+
93
+
94
+ def parse_json(response: httpx.Response) -> Any:
95
+ if response.status_code >= 400:
96
+ raise error_from_response(response.status_code, response.headers, response.text)
97
+ if not response.content:
98
+ return {}
99
+ try:
100
+ return response.json()
101
+ except ValueError as exc:
102
+ raise error_from_response(
103
+ 502, response.headers, "API response did not contain valid JSON"
104
+ ) from exc
105
+
106
+
107
+ class SSEDecoder:
108
+ """Turns text/event-stream lines into {"event", "data"} dicts."""
109
+
110
+ def __init__(self) -> None:
111
+ self._event = "message"
112
+ self._data: List[str] = []
113
+
114
+ def feed(self, raw_line: str) -> Optional[Dict[str, Any]]:
115
+ line = raw_line.rstrip("\r")
116
+ if line.startswith("event:"):
117
+ self._event = line[6:].strip()
118
+ elif line.startswith("data:"):
119
+ self._data.append(line[5:][1:] if line[5:6] == " " else line[5:])
120
+ elif line == "" and self._data:
121
+ raw = "\n".join(self._data)
122
+ try:
123
+ data: Any = json.loads(raw)
124
+ except ValueError:
125
+ data = raw
126
+ event = {"event": self._event, "data": data}
127
+ self._event, self._data = "message", []
128
+ return event
129
+ return None
130
+
131
+
132
+ def event_kind(event: Mapping[str, Any]) -> str:
133
+ data = event.get("data")
134
+ if event.get("event") == "message" and isinstance(data, dict):
135
+ return str(data.get("type", "message"))
136
+ return str(event.get("event"))
137
+
138
+
139
+ class StreamTracker:
140
+ """Applies the stream contract: a result and a later done event mean success."""
141
+
142
+ def __init__(self) -> None:
143
+ self.events: List[Dict[str, Any]] = []
144
+ self.has_result = False
145
+ self.done = False
146
+
147
+ def add(self, event: Dict[str, Any]) -> Optional[str]:
148
+ """Record an event. Returns a failure reason when the stream reports one."""
149
+ self.events.append(event)
150
+ kind = event_kind(event)
151
+ if kind in ("error", "accounting_error"):
152
+ data = event.get("data")
153
+ detail = data.get("message") if isinstance(data, dict) else None
154
+ return f"Verification stream reported {kind}" + (f": {detail}" if detail else "")
155
+ if kind in ("result", "complete"):
156
+ self.has_result = True
157
+ if kind == "done":
158
+ if not self.has_result:
159
+ return "Stream completion arrived before its result"
160
+ self.done = True
161
+ return None
162
+
163
+ def final_failure(self) -> Optional[str]:
164
+ if self.has_result and self.done:
165
+ return None
166
+ return "Verification stream ended without a result and a done event"