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