langchain-sealgraf 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.
@@ -0,0 +1,77 @@
1
+ """Sealgraf tools for LangChain.
2
+
3
+ Sealgraf is the owner-approval layer for agent spending. These tools
4
+ run the full loop inside a LangChain agent: check a purchase against
5
+ the owner's pre-set limits BEFORE buying, let the owner approve larger
6
+ purchases on Sealgraf's own surface, and seal every completed purchase
7
+ into a receipt neither side can rewrite.
8
+
9
+ from langchain_sealgraf import get_sealgraf_tools
10
+
11
+ tools = get_sealgraf_tools() # reads SEALGRAF_API_KEY from the env
12
+
13
+ Tools return JSON strings and raise :class:`SealgrafError` on any
14
+ failure — a failed tool call is never a permission.
15
+ """
16
+
17
+ from .client import (
18
+ CATEGORIES,
19
+ DECISION_OUTCOMES,
20
+ DEFAULT_BASE_URL,
21
+ PAYMENT_PROVENANCES,
22
+ PAYMENT_RAILS,
23
+ RAIL_REF_KINDS,
24
+ SealgrafApiError,
25
+ SealgrafClient,
26
+ SealgrafConfigError,
27
+ SealgrafError,
28
+ SealgrafSettings,
29
+ client_from_settings,
30
+ )
31
+ from .tools import (
32
+ Category,
33
+ CheckPermissionInput,
34
+ CheckPermissionTool,
35
+ ClaimDecisionTokenInput,
36
+ ClaimDecisionTokenTool,
37
+ CompletePurchaseInput,
38
+ CompletePurchaseTool,
39
+ GetReceiptInput,
40
+ GetReceiptTool,
41
+ PaymentProvenance,
42
+ PaymentRail,
43
+ RailRefKind,
44
+ SealgrafToolkit,
45
+ get_sealgraf_tools,
46
+ )
47
+
48
+ __version__ = "0.1.0"
49
+
50
+ __all__ = [
51
+ "CATEGORIES",
52
+ "DECISION_OUTCOMES",
53
+ "DEFAULT_BASE_URL",
54
+ "PAYMENT_PROVENANCES",
55
+ "PAYMENT_RAILS",
56
+ "RAIL_REF_KINDS",
57
+ "Category",
58
+ "CheckPermissionInput",
59
+ "CheckPermissionTool",
60
+ "ClaimDecisionTokenInput",
61
+ "ClaimDecisionTokenTool",
62
+ "CompletePurchaseInput",
63
+ "CompletePurchaseTool",
64
+ "GetReceiptInput",
65
+ "GetReceiptTool",
66
+ "PaymentProvenance",
67
+ "PaymentRail",
68
+ "RailRefKind",
69
+ "SealgrafApiError",
70
+ "SealgrafClient",
71
+ "SealgrafConfigError",
72
+ "SealgrafError",
73
+ "SealgrafSettings",
74
+ "SealgrafToolkit",
75
+ "client_from_settings",
76
+ "get_sealgraf_tools",
77
+ ]
@@ -0,0 +1,576 @@
1
+ """HTTP client and response shaping for the Sealgraf spend-approval API.
2
+
3
+ Contract source: production code, ``see/api.py`` / ``see/service.py`` on
4
+ ``origin/main`` of signed-evidence-engine, as implemented and verified
5
+ in the sibling surfaces (the Dify plugin's ``sealgraf_client.py`` is the
6
+ reference implementation; this module mirrors its semantics):
7
+
8
+ - Auth: an agent-scope API key in the ``X-API-Key`` header
9
+ (a bad or missing key is a 401 with
10
+ ``{"detail": "invalid or missing API key"}``).
11
+ - ``POST /v1/preauthorize`` (201) takes ``CheckIn`` and answers with the
12
+ ``_preauth_out`` shape; a decision token is present in that answer
13
+ ONLY when the check itself minted one (an immediate ``allow``).
14
+ - ``POST /v1/preauthorize/{id}/decision-token`` claims the token an
15
+ owner approval minted; refusals are 409 ``{"detail": ..., "code":
16
+ ...}`` with stable codes (``not_approved_yet``,
17
+ ``decision_token_expired``, ``already_completed``, ``preauth_aborted``,
18
+ ``preauth_denied``, ``token_delivered_at_check``,
19
+ ``decision_token_unavailable``). Claiming is delivery, not
20
+ consumption, and may repeat inside the approval window.
21
+ - ``POST /v1/preauthorize/{id}/complete`` takes ``CompleteIn``
22
+ (``decision_token``, ``completion_nonce``, ``evidence``) and returns
23
+ the sealed receipt dict. Evidence keys are a CLOSED set on the server
24
+ (``see/service.py`` ``_SEALED_EVIDENCE_KEYS``):
25
+ ``completed_amount_minor``, ``counterparty_receipt_ref``, ``note``,
26
+ ``completed_at``, ``payment``.
27
+ - ``GET /v1/preauthorize/{id}``, ``GET /v1/receipts/{id}`` and
28
+ ``GET /v1/receipts`` are the reads.
29
+
30
+ FAIL CLOSED: every transport error, timeout, non-2xx response, or
31
+ malformed body raises :class:`SealgrafError` (or its
32
+ :class:`SealgrafApiError` subclass). Nothing in this module ever
33
+ fabricates a permission-shaped result, and decision tokens are passed
34
+ through untouched and never logged.
35
+
36
+ Amounts are integer minor units (cents) end to end.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import os
42
+ import re
43
+ from dataclasses import dataclass
44
+ from typing import Any
45
+
46
+ import httpx
47
+
48
+ DEFAULT_BASE_URL = "https://sealgraf.com"
49
+ DEFAULT_TIMEOUT_SECONDS = 20.0
50
+
51
+ # Explicit timeouts: a hung connection must become an error, never a
52
+ # silent wait and never a permission.
53
+ _TIMEOUT = httpx.Timeout(connect=5.0, read=20.0, write=10.0, pool=5.0)
54
+
55
+ # The canonical category ids (production: see/notify.py _CATEGORY_LABELS,
56
+ # mirrored by docs/AGENT_SETUP.md's canonical table). Closed list — the
57
+ # ids are sealed into history and must never be renamed.
58
+ CATEGORIES: tuple[str, ...] = (
59
+ "groceries",
60
+ "household",
61
+ "dining",
62
+ "travel",
63
+ "software",
64
+ "office_supplies",
65
+ "shopping",
66
+ "transport",
67
+ "entertainment",
68
+ "health",
69
+ "supplies",
70
+ "materials",
71
+ "equipment",
72
+ "fuel",
73
+ )
74
+
75
+ # Decision outcomes (production: see/models.py DecisionOutcome).
76
+ DECISION_OUTCOMES = frozenset({"allow", "deny", "needs_human_approval"})
77
+
78
+ # Completion-evidence payment vocabularies (production: see/service.py
79
+ # _PAYMENT_RAILS, _RAIL_REF_KINDS, _PAYMENT_PROVENANCES). Closed lists.
80
+ PAYMENT_RAILS = frozenset(
81
+ {"link_stripe", "paypal", "stripe_api", "card_on_merchant", "other"}
82
+ )
83
+ RAIL_REF_KINDS = frozenset(
84
+ {"charge", "payment_intent", "paypal_transaction", "other"}
85
+ )
86
+ PAYMENT_PROVENANCES = frozenset(
87
+ {"browser_checkout", "rail_api", "merchant_confirmation"}
88
+ )
89
+
90
+ _LAST4 = re.compile(r"[0-9]{4}")
91
+ _CURRENCY = re.compile(r"[A-Za-z]{3}")
92
+
93
+
94
+ class SealgrafError(Exception):
95
+ """Any failure talking to Sealgraf — or understanding its answer.
96
+
97
+ Tools let this propagate: a failed tool call is the only safe
98
+ rendering of "we do not know" in a spend loop.
99
+ """
100
+
101
+
102
+ class SealgrafConfigError(SealgrafError):
103
+ """The client is misconfigured (e.g. no API key). Raised before any
104
+ network call is attempted."""
105
+
106
+
107
+ class SealgrafApiError(SealgrafError):
108
+ """The service answered with a non-2xx status."""
109
+
110
+ def __init__(self, status_code: int, detail: str, code: str | None = None):
111
+ self.status_code = status_code
112
+ self.detail = detail
113
+ self.code = code
114
+ message = f"Sealgraf API error (HTTP {status_code}): {detail}"
115
+ if code:
116
+ message += f" [code: {code}]"
117
+ super().__init__(message)
118
+
119
+
120
+ def _sanitize_proxy_env() -> None:
121
+ """Drop bracketed IPv6 literals (e.g. ``[::1]``) from NO_PROXY/no_proxy.
122
+
123
+ httpx builds proxy URL patterns from these variables at client
124
+ construction and crashes on bracketed IPv6 entries
125
+ (``Invalid port: ':1]'``). Only the offending entries are removed;
126
+ the variables are never emptied wholesale.
127
+ """
128
+ for var in ("NO_PROXY", "no_proxy"):
129
+ value = os.environ.get(var)
130
+ if not value:
131
+ continue
132
+ parts = [p for p in value.split(",") if p.strip()]
133
+ kept = [p for p in parts
134
+ if not re.fullmatch(r"\[[^\]]*\](:\d+)?", p.strip())]
135
+ if len(kept) != len(parts):
136
+ os.environ[var] = ",".join(kept)
137
+
138
+
139
+ def normalize_base_url(raw: str | None) -> str:
140
+ url = (raw or "").strip() or DEFAULT_BASE_URL
141
+ url = url.rstrip("/")
142
+ if not (url.startswith("https://") or url.startswith("http://")):
143
+ raise SealgrafError(
144
+ f"Sealgraf base URL must start with https:// or http://, got: {url!r}"
145
+ )
146
+ return url
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class SealgrafSettings:
151
+ """Where the tools point and how they authenticate.
152
+
153
+ The API key is host-application configuration, never a tool
154
+ argument: tool arguments are chosen by the model and visible in
155
+ prompts and logs, while this key is a per-agent credential.
156
+ """
157
+
158
+ api_key: str
159
+ base_url: str = DEFAULT_BASE_URL
160
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
161
+
162
+ @classmethod
163
+ def from_env(cls) -> "SealgrafSettings":
164
+ api_key = os.environ.get("SEALGRAF_API_KEY", "").strip()
165
+ if not api_key:
166
+ raise SealgrafConfigError(
167
+ "SEALGRAF_API_KEY is not set. The Sealgraf tools need an "
168
+ "agent-scope Sealgraf API key in the environment of the "
169
+ "application that hosts them.")
170
+ base_url = os.environ.get("SEALGRAF_BASE_URL", "").strip() \
171
+ or DEFAULT_BASE_URL
172
+ raw_timeout = os.environ.get("SEALGRAF_TIMEOUT_SECONDS", "").strip()
173
+ timeout = DEFAULT_TIMEOUT_SECONDS
174
+ if raw_timeout:
175
+ try:
176
+ timeout = float(raw_timeout)
177
+ except ValueError:
178
+ raise SealgrafConfigError(
179
+ "SEALGRAF_TIMEOUT_SECONDS must be a number of seconds, "
180
+ f"got {raw_timeout!r}.")
181
+ if timeout <= 0:
182
+ raise SealgrafConfigError(
183
+ "SEALGRAF_TIMEOUT_SECONDS must be positive.")
184
+ return cls(api_key=api_key, base_url=base_url,
185
+ timeout_seconds=timeout)
186
+
187
+ def client(self, transport: httpx.BaseTransport | None = None) \
188
+ -> "SealgrafClient":
189
+ return SealgrafClient(
190
+ self.base_url,
191
+ self.api_key,
192
+ timeout=httpx.Timeout(self.timeout_seconds),
193
+ transport=transport,
194
+ )
195
+
196
+
197
+ class SealgrafClient:
198
+ """One thin, fail-closed REST client over httpx."""
199
+
200
+ def __init__(
201
+ self,
202
+ base_url: str | None,
203
+ api_key: str | None,
204
+ *,
205
+ timeout: httpx.Timeout = _TIMEOUT,
206
+ transport: httpx.BaseTransport | None = None,
207
+ ):
208
+ key = (api_key or "").strip()
209
+ if not key:
210
+ raise SealgrafConfigError(
211
+ "Sealgraf API key is missing. Provide an agent-scope "
212
+ "Sealgraf API key (or set SEALGRAF_API_KEY).")
213
+ _sanitize_proxy_env()
214
+ self.base_url = normalize_base_url(base_url)
215
+ self._http = httpx.Client(
216
+ base_url=self.base_url,
217
+ headers={
218
+ "X-API-Key": key,
219
+ "Content-Type": "application/json",
220
+ "Accept": "application/json",
221
+ "User-Agent": "langchain-sealgraf/0.1.0",
222
+ },
223
+ timeout=timeout,
224
+ transport=transport,
225
+ )
226
+
227
+ # -- transport ------------------------------------------------------
228
+
229
+ def _request(
230
+ self,
231
+ method: str,
232
+ path: str,
233
+ *,
234
+ json_body: dict | None = None,
235
+ params: dict | None = None,
236
+ expected: tuple[int, ...] = (200, 201),
237
+ ) -> dict:
238
+ try:
239
+ response = self._http.request(
240
+ method, path, json=json_body, params=params
241
+ )
242
+ except httpx.TimeoutException as exc:
243
+ raise SealgrafError(
244
+ f"Sealgraf request timed out ({method} {path}). "
245
+ "Failing closed: no permission was granted."
246
+ ) from exc
247
+ except httpx.HTTPError as exc:
248
+ raise SealgrafError(
249
+ f"Sealgraf request failed ({method} {path}): {exc}. "
250
+ "Failing closed: no permission was granted."
251
+ ) from exc
252
+ if response.status_code not in expected:
253
+ detail = ""
254
+ code = None
255
+ try:
256
+ payload = response.json()
257
+ except ValueError:
258
+ payload = None
259
+ if isinstance(payload, dict):
260
+ raw_detail = payload.get("detail")
261
+ if isinstance(raw_detail, str):
262
+ detail = raw_detail
263
+ elif raw_detail is not None:
264
+ detail = str(raw_detail)
265
+ if isinstance(payload.get("code"), str):
266
+ code = payload["code"]
267
+ if not detail:
268
+ detail = response.text.strip()[:300] or "no detail provided"
269
+ raise SealgrafApiError(response.status_code, detail, code)
270
+ try:
271
+ data = response.json()
272
+ except ValueError as exc:
273
+ raise SealgrafError(
274
+ f"Malformed response from Sealgraf ({method} {path}): "
275
+ "body is not valid JSON. Failing closed."
276
+ ) from exc
277
+ if not isinstance(data, dict):
278
+ raise SealgrafError(
279
+ f"Malformed response from Sealgraf ({method} {path}): "
280
+ "expected a JSON object. Failing closed."
281
+ )
282
+ return data
283
+
284
+ # -- endpoints --------------------------------------------------------
285
+
286
+ def validate_key(self) -> None:
287
+ """The lightest authenticated read an agent key may make:
288
+ ``GET /v1/receipts?limit=1`` (production: see/api.py
289
+ ``list_receipts`` — no scope restriction, unlike
290
+ ``GET /v1/mandates``, which refuses agent-scope keys)."""
291
+ data = self._request("GET", "/v1/receipts", params={"limit": 1},
292
+ expected=(200,))
293
+ if not isinstance(data.get("items"), list):
294
+ raise SealgrafError(
295
+ "Malformed response from Sealgraf (GET /v1/receipts): "
296
+ "expected an object with an 'items' list."
297
+ )
298
+
299
+ def check_permission(
300
+ self,
301
+ *,
302
+ category: str,
303
+ amount_minor: int,
304
+ currency: str | None = None,
305
+ counterparty: str | None = None,
306
+ description: str | None = None,
307
+ agent_id: str | None = None,
308
+ mandate_id: str | None = None,
309
+ idempotency_key: str | None = None,
310
+ ) -> dict:
311
+ """POST /v1/preauthorize — body is production's ``CheckIn``."""
312
+ action: dict[str, Any] = {
313
+ "category": category,
314
+ "amount_minor": amount_minor,
315
+ }
316
+ if agent_id:
317
+ action["agent_id"] = agent_id
318
+ if currency:
319
+ action["currency"] = currency
320
+ if counterparty:
321
+ action["counterparty"] = counterparty
322
+ if description:
323
+ action["description"] = description
324
+ body: dict[str, Any] = {"action": action}
325
+ if mandate_id:
326
+ body["mandate_id"] = mandate_id
327
+ if idempotency_key:
328
+ body["idempotency_key"] = idempotency_key
329
+ return self._request("POST", "/v1/preauthorize", json_body=body,
330
+ expected=(200, 201))
331
+
332
+ def claim_decision_token(self, preauth_id: str) -> dict:
333
+ """POST /v1/preauthorize/{id}/decision-token (empty JSON body)."""
334
+ return self._request(
335
+ "POST", f"/v1/preauthorize/{preauth_id}/decision-token",
336
+ json_body={}, expected=(200,),
337
+ )
338
+
339
+ def complete_purchase(
340
+ self,
341
+ preauth_id: str,
342
+ *,
343
+ decision_token: str,
344
+ completion_nonce: str,
345
+ evidence: dict,
346
+ ) -> dict:
347
+ """POST /v1/preauthorize/{id}/complete — body is ``CompleteIn``."""
348
+ body = {
349
+ "decision_token": decision_token,
350
+ "completion_nonce": completion_nonce,
351
+ "evidence": evidence,
352
+ }
353
+ return self._request(
354
+ "POST", f"/v1/preauthorize/{preauth_id}/complete",
355
+ json_body=body, expected=(200, 201),
356
+ )
357
+
358
+ def get_preauth(self, preauth_id: str) -> dict:
359
+ """GET /v1/preauthorize/{id} — the ``_preauth_out`` shape."""
360
+ return self._request("GET", f"/v1/preauthorize/{preauth_id}",
361
+ expected=(200,))
362
+
363
+ def get_receipt(self, receipt_id: str) -> dict:
364
+ """GET /v1/receipts/{id} — receipt row + completion summary."""
365
+ return self._request("GET", f"/v1/receipts/{receipt_id}",
366
+ expected=(200,))
367
+
368
+
369
+ def client_from_settings(
370
+ settings: SealgrafSettings | None = None,
371
+ *,
372
+ transport: httpx.BaseTransport | None = None,
373
+ ) -> SealgrafClient:
374
+ """Build a client from explicit settings, or from the environment
375
+ (``SEALGRAF_API_KEY`` / ``SEALGRAF_BASE_URL`` /
376
+ ``SEALGRAF_TIMEOUT_SECONDS``) when none are given."""
377
+ return (settings or SealgrafSettings.from_env()).client(
378
+ transport=transport)
379
+
380
+
381
+ # -- response shaping -----------------------------------------------------
382
+ # Each parser validates the production response shape before a tool may
383
+ # present it. Anything unexpected raises SealgrafError: a response the
384
+ # package cannot understand is never rendered as a permission.
385
+
386
+
387
+ def _require_str(data: dict, field: str, context: str) -> str:
388
+ value = data.get(field)
389
+ if not isinstance(value, str) or not value:
390
+ raise SealgrafError(
391
+ f"Malformed response from Sealgraf ({context}): "
392
+ f"'{field}' is missing or not a string. Failing closed."
393
+ )
394
+ return value
395
+
396
+
397
+ def parse_check_result(data: dict) -> dict:
398
+ """Normalize a ``POST /v1/preauthorize`` answer (``_preauth_out``)."""
399
+ preauth_id = _require_str(data, "preauth_id", "check_permission")
400
+ decision = data.get("decision")
401
+ if not isinstance(decision, dict):
402
+ raise SealgrafError(
403
+ "Malformed response from Sealgraf (check_permission): "
404
+ "'decision' is missing or not an object. Failing closed."
405
+ )
406
+ outcome = decision.get("outcome")
407
+ if outcome not in DECISION_OUTCOMES:
408
+ raise SealgrafError(
409
+ "Malformed response from Sealgraf (check_permission): "
410
+ f"unknown decision outcome {outcome!r}. Failing closed."
411
+ )
412
+ state = data.get("state")
413
+ if not isinstance(state, str) or not state:
414
+ raise SealgrafError(
415
+ "Malformed response from Sealgraf (check_permission): "
416
+ "'state' is missing. Failing closed."
417
+ )
418
+ result: dict[str, Any] = {
419
+ "preauth_id": preauth_id,
420
+ "state": state,
421
+ "outcome": outcome,
422
+ "reason_code": decision.get("reason_code"),
423
+ "mandate_id": data.get("mandate_id"),
424
+ "mandate_version": data.get("mandate_version"),
425
+ "receipt_id": data.get("receipt_id"),
426
+ "token_expires_at": data.get("token_expires_at"),
427
+ "ask_expires_at": data.get("ask_expires_at"),
428
+ "replayed": bool(data.get("replayed", False)),
429
+ }
430
+ action = data.get("action")
431
+ if isinstance(action, dict):
432
+ result["amount_minor"] = action.get("amount_minor")
433
+ result["currency"] = action.get("currency")
434
+ result["category"] = action.get("category")
435
+ if outcome == "allow":
436
+ # An allow is only usable with the single-use decision token the
437
+ # check minted. Production includes it in exactly this case; its
438
+ # absence on a FRESH answer means the answer cannot be trusted —
439
+ # fail closed. One documented exception (see/api.py, A5): an
440
+ # idempotent replay (HTTP 200, "replayed": true) returns the
441
+ # original record and deliberately does NOT re-serve the token
442
+ # (only its hash is stored). That shape is surfaced honestly,
443
+ # flagged, and never presented as a fresh permission.
444
+ token = data.get("decision_token")
445
+ if isinstance(token, str) and token:
446
+ result["decision_token"] = token
447
+ elif result["replayed"]:
448
+ result["decision_token_redelivered"] = False
449
+ else:
450
+ raise SealgrafError(
451
+ "Malformed response from Sealgraf (check_permission): "
452
+ "outcome is 'allow' but no decision_token was returned. "
453
+ "Failing closed: do not buy."
454
+ )
455
+ return result
456
+
457
+
458
+ def parse_claim_result(data: dict, preauth_id: str) -> dict:
459
+ token = data.get("decision_token")
460
+ if not isinstance(token, str) or not token:
461
+ raise SealgrafError(
462
+ "Malformed response from Sealgraf (claim_decision_token): "
463
+ "no decision_token in the response. Failing closed."
464
+ )
465
+ return {
466
+ "preauth_id": preauth_id,
467
+ "claimed": True,
468
+ "decision_token": token,
469
+ "token_expires_at": data.get("token_expires_at"),
470
+ }
471
+
472
+
473
+ def parse_complete_result(data: dict) -> dict:
474
+ receipt_id = _require_str(data, "receipt_id", "complete_purchase")
475
+ return {
476
+ "sealed": True,
477
+ "receipt_id": receipt_id,
478
+ "preauth_id": data.get("preauth_id"),
479
+ "entry_seq": data.get("entry_seq"),
480
+ "amount_minor": data.get("amount_minor"),
481
+ "currency": data.get("currency"),
482
+ "mandate_id": data.get("mandate_id"),
483
+ "created_at": data.get("created_at"),
484
+ }
485
+
486
+
487
+ def parse_preauth_result(data: dict) -> dict:
488
+ preauth_id = _require_str(data, "preauth_id", "get_receipt")
489
+ decision = data.get("decision") if isinstance(data.get("decision"), dict) else {}
490
+ action = data.get("action") if isinstance(data.get("action"), dict) else {}
491
+ return {
492
+ "found_via": "preauth",
493
+ "preauth_id": preauth_id,
494
+ "state": data.get("state"),
495
+ "outcome": decision.get("outcome"),
496
+ "reason_code": decision.get("reason_code"),
497
+ "receipt_id": data.get("receipt_id"),
498
+ "mandate_id": data.get("mandate_id"),
499
+ "mandate_version": data.get("mandate_version"),
500
+ "amount_minor": action.get("amount_minor"),
501
+ "currency": action.get("currency"),
502
+ "category": action.get("category"),
503
+ "counterparty": action.get("counterparty"),
504
+ "was_allowed": data.get("was_allowed"),
505
+ "approved_at": data.get("approved_at"),
506
+ "token_expires_at": data.get("token_expires_at"),
507
+ "ask_expires_at": data.get("ask_expires_at"),
508
+ "created_at": data.get("created_at"),
509
+ }
510
+
511
+
512
+ def parse_receipt_result(data: dict) -> dict:
513
+ receipt_id = _require_str(data, "receipt_id", "get_receipt")
514
+ return {
515
+ "found_via": "receipt",
516
+ "receipt_id": receipt_id,
517
+ "preauth_id": data.get("preauth_id"),
518
+ "entry_seq": data.get("entry_seq"),
519
+ "amount_minor": data.get("amount_minor"),
520
+ "currency": data.get("currency"),
521
+ "mandate_id": data.get("mandate_id"),
522
+ "created_at": data.get("created_at"),
523
+ "completion": data.get("completion"),
524
+ "payment_flag": data.get("payment_flag"),
525
+ }
526
+
527
+
528
+ # -- parameter validation ---------------------------------------------------
529
+ # Shared by the tools; runs BEFORE any HTTP call so bad input fails with
530
+ # a clear local message and never reaches the service.
531
+
532
+
533
+ def require_amount_minor(value: Any, field: str) -> int:
534
+ if isinstance(value, bool) or value is None:
535
+ raise SealgrafError(f"{field} is required and must be a positive integer (minor units).")
536
+ if isinstance(value, float):
537
+ if not value.is_integer():
538
+ raise SealgrafError(f"{field} must be a whole number of minor units, got {value}.")
539
+ value = int(value)
540
+ if not isinstance(value, int):
541
+ raise SealgrafError(f"{field} must be an integer (minor units), got {value!r}.")
542
+ if value <= 0:
543
+ raise SealgrafError(f"{field} must be greater than 0, got {value}.")
544
+ return value
545
+
546
+
547
+ def optional_str(value: Any) -> str | None:
548
+ if value is None:
549
+ return None
550
+ text = str(value).strip()
551
+ return text or None
552
+
553
+
554
+ def require_str(value: Any, field: str) -> str:
555
+ text = optional_str(value)
556
+ if text is None:
557
+ raise SealgrafError(f"{field} is required.")
558
+ return text
559
+
560
+
561
+ def validate_currency(value: Any) -> str | None:
562
+ text = optional_str(value)
563
+ if text is None:
564
+ return None
565
+ if _CURRENCY.fullmatch(text) is None:
566
+ raise SealgrafError(f"currency must be a three-letter code, got {text!r}.")
567
+ return text.upper()
568
+
569
+
570
+ def validate_last4(value: Any, field: str) -> str | None:
571
+ text = optional_str(value)
572
+ if text is None:
573
+ return None
574
+ if _LAST4.fullmatch(text) is None:
575
+ raise SealgrafError(f"{field} must be exactly four digits, as a string.")
576
+ return text