sealgraf-composio 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.
- sealgraf_composio/__init__.py +50 -0
- sealgraf_composio/client.py +245 -0
- sealgraf_composio/schemas.py +140 -0
- sealgraf_composio/tools.py +157 -0
- sealgraf_composio-0.1.0.dist-info/METADATA +151 -0
- sealgraf_composio-0.1.0.dist-info/RECORD +9 -0
- sealgraf_composio-0.1.0.dist-info/WHEEL +5 -0
- sealgraf_composio-0.1.0.dist-info/licenses/LICENSE +21 -0
- sealgraf_composio-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Sealgraf tools for Composio (local custom toolkit, Python SDK).
|
|
2
|
+
|
|
3
|
+
Four tools that run the Sealgraf spend loop inside a Composio Tool
|
|
4
|
+
Router session: check_permission, claim_decision_token,
|
|
5
|
+
complete_purchase, get_receipt.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .client import (
|
|
9
|
+
DEFAULT_BASE_URL,
|
|
10
|
+
SealgrafClient,
|
|
11
|
+
SealgrafConfigError,
|
|
12
|
+
SealgrafError,
|
|
13
|
+
SealgrafSettings,
|
|
14
|
+
)
|
|
15
|
+
from .schemas import (
|
|
16
|
+
Category,
|
|
17
|
+
CheckPermissionInput,
|
|
18
|
+
ClaimDecisionTokenInput,
|
|
19
|
+
CompletePurchaseInput,
|
|
20
|
+
GetReceiptInput,
|
|
21
|
+
)
|
|
22
|
+
from .tools import (
|
|
23
|
+
SealgrafToolError,
|
|
24
|
+
build_toolkit,
|
|
25
|
+
check_permission,
|
|
26
|
+
claim_decision_token,
|
|
27
|
+
complete_purchase,
|
|
28
|
+
get_receipt,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
__version__ = "0.1.0"
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"DEFAULT_BASE_URL",
|
|
35
|
+
"Category",
|
|
36
|
+
"CheckPermissionInput",
|
|
37
|
+
"ClaimDecisionTokenInput",
|
|
38
|
+
"CompletePurchaseInput",
|
|
39
|
+
"GetReceiptInput",
|
|
40
|
+
"SealgrafClient",
|
|
41
|
+
"SealgrafConfigError",
|
|
42
|
+
"SealgrafError",
|
|
43
|
+
"SealgrafSettings",
|
|
44
|
+
"SealgrafToolError",
|
|
45
|
+
"build_toolkit",
|
|
46
|
+
"check_permission",
|
|
47
|
+
"claim_decision_token",
|
|
48
|
+
"complete_purchase",
|
|
49
|
+
"get_receipt",
|
|
50
|
+
]
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""HTTP client for the Sealgraf spend-approval API.
|
|
2
|
+
|
|
3
|
+
Contract source: production code, `see/api.py` on `origin/main` of
|
|
4
|
+
signed-evidence-engine (extracted 2026-11-11; see ../../RESEARCH.md for the
|
|
5
|
+
full citation list). Auth is an agent-scope API key in the `X-API-Key`
|
|
6
|
+
header. All amounts are integer minor units (cents).
|
|
7
|
+
|
|
8
|
+
Fail-closed discipline: every failure mode — missing key, timeout, network
|
|
9
|
+
error, non-2xx status, malformed or non-object JSON — raises
|
|
10
|
+
:class:`SealgrafError`. This client never fabricates a decision.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
|
|
19
|
+
import httpx
|
|
20
|
+
|
|
21
|
+
DEFAULT_BASE_URL = "https://sealgraf.com"
|
|
22
|
+
DEFAULT_TIMEOUT_SECONDS = 20.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SealgrafError(Exception):
|
|
26
|
+
"""A Sealgraf API call failed. Carries the HTTP status and, when the
|
|
27
|
+
server supplied one, its stable machine-readable error `code`
|
|
28
|
+
(e.g. the claim-refusal codes from DECISIONS #41)."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, message: str, *, status: int | None = None,
|
|
31
|
+
code: str | None = None, detail: str | None = None):
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
self.status = status
|
|
34
|
+
self.code = code
|
|
35
|
+
self.detail = detail
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SealgrafConfigError(SealgrafError):
|
|
39
|
+
"""The client is misconfigured (e.g. no API key). Raised before any
|
|
40
|
+
network call is attempted."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _sanitize_proxy_env() -> None:
|
|
44
|
+
"""Drop bracketed IPv6 literals (e.g. ``[::1]``) from NO_PROXY/no_proxy.
|
|
45
|
+
|
|
46
|
+
httpx builds proxy URL patterns from these variables at client
|
|
47
|
+
construction and crashes on bracketed IPv6 entries
|
|
48
|
+
(``Invalid port: ':1]'``). Only the offending entries are removed;
|
|
49
|
+
the variables are never emptied wholesale.
|
|
50
|
+
"""
|
|
51
|
+
for var in ("NO_PROXY", "no_proxy"):
|
|
52
|
+
value = os.environ.get(var)
|
|
53
|
+
if not value:
|
|
54
|
+
continue
|
|
55
|
+
parts = [p for p in value.split(",") if p.strip()]
|
|
56
|
+
kept = [p for p in parts
|
|
57
|
+
if not re.fullmatch(r"\[[^\]]*\](:\d+)?", p.strip())]
|
|
58
|
+
if len(kept) != len(parts):
|
|
59
|
+
os.environ[var] = ",".join(kept)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class SealgrafSettings:
|
|
64
|
+
"""Where the tools point and how they authenticate.
|
|
65
|
+
|
|
66
|
+
The API key is host-application configuration, never a tool argument:
|
|
67
|
+
tool arguments are chosen by the model and visible in prompts and
|
|
68
|
+
logs, while this key is a per-agent credential.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
api_key: str
|
|
72
|
+
base_url: str = DEFAULT_BASE_URL
|
|
73
|
+
timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def from_env(cls) -> "SealgrafSettings":
|
|
77
|
+
api_key = os.environ.get("SEALGRAF_API_KEY", "").strip()
|
|
78
|
+
if not api_key:
|
|
79
|
+
raise SealgrafConfigError(
|
|
80
|
+
"SEALGRAF_API_KEY is not set. The Sealgraf tools need an "
|
|
81
|
+
"agent-scope Sealgraf API key in the environment of the "
|
|
82
|
+
"application that hosts them.")
|
|
83
|
+
base_url = os.environ.get("SEALGRAF_BASE_URL", "").strip() \
|
|
84
|
+
or DEFAULT_BASE_URL
|
|
85
|
+
raw_timeout = os.environ.get("SEALGRAF_TIMEOUT_SECONDS", "").strip()
|
|
86
|
+
timeout = DEFAULT_TIMEOUT_SECONDS
|
|
87
|
+
if raw_timeout:
|
|
88
|
+
try:
|
|
89
|
+
timeout = float(raw_timeout)
|
|
90
|
+
except ValueError:
|
|
91
|
+
raise SealgrafConfigError(
|
|
92
|
+
"SEALGRAF_TIMEOUT_SECONDS must be a number of seconds, "
|
|
93
|
+
f"got {raw_timeout!r}.")
|
|
94
|
+
if timeout <= 0:
|
|
95
|
+
raise SealgrafConfigError(
|
|
96
|
+
"SEALGRAF_TIMEOUT_SECONDS must be positive.")
|
|
97
|
+
return cls(api_key=api_key, base_url=base_url,
|
|
98
|
+
timeout_seconds=timeout)
|
|
99
|
+
|
|
100
|
+
def client(self, transport: httpx.BaseTransport | None = None) \
|
|
101
|
+
-> "SealgrafClient":
|
|
102
|
+
return SealgrafClient(self.api_key, base_url=self.base_url,
|
|
103
|
+
timeout=self.timeout_seconds,
|
|
104
|
+
transport=transport)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SealgrafClient:
|
|
108
|
+
"""Thin, fail-closed wrapper over Sealgraf's four spend-loop routes."""
|
|
109
|
+
|
|
110
|
+
def __init__(self, api_key: str, *, base_url: str = DEFAULT_BASE_URL,
|
|
111
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
112
|
+
transport: httpx.BaseTransport | None = None):
|
|
113
|
+
if not api_key or not api_key.strip():
|
|
114
|
+
raise SealgrafConfigError("A Sealgraf API key is required.")
|
|
115
|
+
_sanitize_proxy_env()
|
|
116
|
+
self._http = httpx.Client(
|
|
117
|
+
base_url=base_url.rstrip("/"),
|
|
118
|
+
headers={
|
|
119
|
+
"X-API-Key": api_key,
|
|
120
|
+
"Content-Type": "application/json",
|
|
121
|
+
"Accept": "application/json",
|
|
122
|
+
},
|
|
123
|
+
timeout=httpx.Timeout(timeout),
|
|
124
|
+
transport=transport,
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
# -- plumbing ------------------------------------------------------
|
|
128
|
+
|
|
129
|
+
def _request(self, method: str, path: str, *,
|
|
130
|
+
json_body: dict | None = None,
|
|
131
|
+
params: dict | None = None) -> dict:
|
|
132
|
+
kwargs: dict = {}
|
|
133
|
+
if json_body is not None:
|
|
134
|
+
kwargs["json"] = json_body
|
|
135
|
+
if params is not None:
|
|
136
|
+
kwargs["params"] = params
|
|
137
|
+
try:
|
|
138
|
+
response = self._http.request(method, path, **kwargs)
|
|
139
|
+
except httpx.TimeoutException as exc:
|
|
140
|
+
raise SealgrafError(
|
|
141
|
+
f"Sealgraf {method} {path} timed out; the operation did "
|
|
142
|
+
"not complete and nothing was decided.") from exc
|
|
143
|
+
except httpx.HTTPError as exc:
|
|
144
|
+
raise SealgrafError(
|
|
145
|
+
f"Sealgraf {method} {path} failed before a response was "
|
|
146
|
+
f"received ({exc.__class__.__name__}); the operation did "
|
|
147
|
+
"not complete and nothing was decided.") from exc
|
|
148
|
+
|
|
149
|
+
if not 200 <= response.status_code < 300:
|
|
150
|
+
detail: str | None = None
|
|
151
|
+
code: str | None = None
|
|
152
|
+
try:
|
|
153
|
+
payload = response.json()
|
|
154
|
+
except ValueError:
|
|
155
|
+
payload = None
|
|
156
|
+
if isinstance(payload, dict):
|
|
157
|
+
if isinstance(payload.get("detail"), str):
|
|
158
|
+
detail = payload["detail"]
|
|
159
|
+
if isinstance(payload.get("code"), str):
|
|
160
|
+
code = payload["code"]
|
|
161
|
+
message = (f"Sealgraf {method} {path} answered HTTP "
|
|
162
|
+
f"{response.status_code}")
|
|
163
|
+
if code:
|
|
164
|
+
message += f" (code: {code})"
|
|
165
|
+
if detail:
|
|
166
|
+
message += f": {detail}"
|
|
167
|
+
raise SealgrafError(message, status=response.status_code,
|
|
168
|
+
code=code, detail=detail)
|
|
169
|
+
|
|
170
|
+
try:
|
|
171
|
+
data = response.json()
|
|
172
|
+
except ValueError as exc:
|
|
173
|
+
raise SealgrafError(
|
|
174
|
+
f"Sealgraf {method} {path} returned a malformed "
|
|
175
|
+
"(non-JSON) response; refusing to interpret it.") from exc
|
|
176
|
+
if not isinstance(data, dict):
|
|
177
|
+
raise SealgrafError(
|
|
178
|
+
f"Sealgraf {method} {path} returned a malformed response "
|
|
179
|
+
"(expected a JSON object); refusing to interpret it.")
|
|
180
|
+
return data
|
|
181
|
+
|
|
182
|
+
# -- the four operations -------------------------------------------
|
|
183
|
+
|
|
184
|
+
def check_permission(self, *, category: str, amount_minor: int,
|
|
185
|
+
counterparty: str = "", description: str = "",
|
|
186
|
+
currency: str | None = None,
|
|
187
|
+
agent_id: str | None = None,
|
|
188
|
+
mandate_id: str | None = None,
|
|
189
|
+
idempotency_key: str | None = None) -> dict:
|
|
190
|
+
"""POST /v1/preauthorize (CheckIn, api.py:371).
|
|
191
|
+
|
|
192
|
+
For API-key callers the server completes mandate_id, agent_id and
|
|
193
|
+
currency from the key's binding, so all three are optional here.
|
|
194
|
+
"""
|
|
195
|
+
action: dict = {
|
|
196
|
+
"category": category,
|
|
197
|
+
"amount_minor": amount_minor,
|
|
198
|
+
"counterparty": counterparty,
|
|
199
|
+
"description": description,
|
|
200
|
+
}
|
|
201
|
+
if agent_id is not None:
|
|
202
|
+
action["agent_id"] = agent_id
|
|
203
|
+
if currency is not None:
|
|
204
|
+
action["currency"] = currency
|
|
205
|
+
body: dict = {"action": action}
|
|
206
|
+
if mandate_id is not None:
|
|
207
|
+
body["mandate_id"] = mandate_id
|
|
208
|
+
if idempotency_key is not None:
|
|
209
|
+
body["idempotency_key"] = idempotency_key
|
|
210
|
+
return self._request("POST", "/v1/preauthorize", json_body=body)
|
|
211
|
+
|
|
212
|
+
def claim_decision_token(self, preauth_id: str) -> dict:
|
|
213
|
+
"""POST /v1/preauthorize/{id}/decision-token.
|
|
214
|
+
|
|
215
|
+
Only the agent key that ran the check can claim. Refusals are 409
|
|
216
|
+
with a stable `code` (e.g. `not_approved_yet`).
|
|
217
|
+
"""
|
|
218
|
+
return self._request(
|
|
219
|
+
"POST", f"/v1/preauthorize/{preauth_id}/decision-token")
|
|
220
|
+
|
|
221
|
+
def complete_purchase(self, preauth_id: str, *, decision_token: str,
|
|
222
|
+
completion_nonce: str,
|
|
223
|
+
evidence: dict | None = None) -> dict:
|
|
224
|
+
"""POST /v1/preauthorize/{id}/complete (CompleteIn, api.py:777)."""
|
|
225
|
+
body = {
|
|
226
|
+
"decision_token": decision_token,
|
|
227
|
+
"completion_nonce": completion_nonce,
|
|
228
|
+
"evidence": evidence or {},
|
|
229
|
+
}
|
|
230
|
+
return self._request(
|
|
231
|
+
"POST", f"/v1/preauthorize/{preauth_id}/complete",
|
|
232
|
+
json_body=body)
|
|
233
|
+
|
|
234
|
+
def get_receipt(self, receipt_id: str) -> dict:
|
|
235
|
+
"""GET /v1/receipts/{receipt_id} — the sealed receipt record."""
|
|
236
|
+
return self._request("GET", f"/v1/receipts/{receipt_id}")
|
|
237
|
+
|
|
238
|
+
def get_preauthorization(self, preauth_id: str) -> dict:
|
|
239
|
+
"""GET /v1/preauthorize/{id} — the check record and its state."""
|
|
240
|
+
return self._request("GET", f"/v1/preauthorize/{preauth_id}")
|
|
241
|
+
|
|
242
|
+
def list_receipts(self, *, limit: int = 50) -> dict:
|
|
243
|
+
"""GET /v1/receipts — recent sealed receipts for this key's scope."""
|
|
244
|
+
return self._request("GET", "/v1/receipts",
|
|
245
|
+
params={"limit": limit})
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Tool input schemas.
|
|
2
|
+
|
|
3
|
+
Composio's Python custom-tool API requires each tool's first parameter to
|
|
4
|
+
be a Pydantic ``BaseModel``: the field descriptions become the agent-facing
|
|
5
|
+
input schema and the function docstring becomes the tool description
|
|
6
|
+
(docs.composio.dev/docs/extending-sessions/local-tools-and-toolkits).
|
|
7
|
+
|
|
8
|
+
Field shapes mirror the production request models in `see/api.py`
|
|
9
|
+
(`ActionIn` api.py:332, `CheckIn` api.py:371, `CompleteIn` api.py:777).
|
|
10
|
+
Amounts are integer minor units (cents) end to end.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from enum import Enum
|
|
16
|
+
from typing import Optional
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel, Field, model_validator
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Category(str, Enum):
|
|
22
|
+
"""Sealgraf's closed purchase-category list. Never extend locally:
|
|
23
|
+
the server refuses categories outside this set."""
|
|
24
|
+
|
|
25
|
+
GROCERIES = "groceries"
|
|
26
|
+
HOUSEHOLD = "household"
|
|
27
|
+
DINING = "dining"
|
|
28
|
+
TRAVEL = "travel"
|
|
29
|
+
SOFTWARE = "software"
|
|
30
|
+
OFFICE_SUPPLIES = "office_supplies"
|
|
31
|
+
SHOPPING = "shopping"
|
|
32
|
+
TRANSPORT = "transport"
|
|
33
|
+
ENTERTAINMENT = "entertainment"
|
|
34
|
+
HEALTH = "health"
|
|
35
|
+
SUPPLIES = "supplies"
|
|
36
|
+
MATERIALS = "materials"
|
|
37
|
+
EQUIPMENT = "equipment"
|
|
38
|
+
FUEL = "fuel"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class CheckPermissionInput(BaseModel):
|
|
42
|
+
category: Category = Field(
|
|
43
|
+
description="What kind of purchase this is. Must be one of "
|
|
44
|
+
"Sealgraf's fixed categories.")
|
|
45
|
+
amount_minor: int = Field(
|
|
46
|
+
gt=0,
|
|
47
|
+
description="The amount in the currency's minor unit (cents): "
|
|
48
|
+
"$42.50 is 4250. Must be a positive integer.")
|
|
49
|
+
counterparty: str = Field(
|
|
50
|
+
default="",
|
|
51
|
+
description="Who would be paid — the merchant or payee name, "
|
|
52
|
+
"e.g. 'Lowe's'.")
|
|
53
|
+
description: str = Field(
|
|
54
|
+
default="",
|
|
55
|
+
description="What the purchase is for, in plain words. The owner "
|
|
56
|
+
"reads this when a purchase needs their approval.")
|
|
57
|
+
currency: Optional[str] = Field(
|
|
58
|
+
default=None, min_length=3, max_length=3,
|
|
59
|
+
description="ISO 4217 currency code, e.g. 'USD'. Optional: for "
|
|
60
|
+
"API-key callers Sealgraf defaults it from the key's "
|
|
61
|
+
"binding.")
|
|
62
|
+
agent_id: Optional[str] = Field(
|
|
63
|
+
default=None,
|
|
64
|
+
description="Which agent is asking. Optional: for API-key "
|
|
65
|
+
"callers Sealgraf defaults it from the key's binding.")
|
|
66
|
+
mandate_id: Optional[str] = Field(
|
|
67
|
+
default=None,
|
|
68
|
+
description="The owner's limits mandate to check against. "
|
|
69
|
+
"Optional: for API-key callers Sealgraf defaults it "
|
|
70
|
+
"from the key's binding.")
|
|
71
|
+
idempotency_key: Optional[str] = Field(
|
|
72
|
+
default=None, min_length=8, max_length=200,
|
|
73
|
+
description="Optional client idempotency key (8-200 characters). "
|
|
74
|
+
"Repeating a check with the same key and the same "
|
|
75
|
+
"purchase returns the original check instead of "
|
|
76
|
+
"creating a duplicate.")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class ClaimDecisionTokenInput(BaseModel):
|
|
80
|
+
preauth_id: str = Field(
|
|
81
|
+
min_length=1,
|
|
82
|
+
description="The preauth_id returned by check_permission for the "
|
|
83
|
+
"purchase the owner has now approved.")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class CompletePurchaseInput(BaseModel):
|
|
87
|
+
preauth_id: str = Field(
|
|
88
|
+
min_length=1,
|
|
89
|
+
description="The preauth_id returned by check_permission.")
|
|
90
|
+
decision_token: str = Field(
|
|
91
|
+
min_length=1,
|
|
92
|
+
description="The single-use decision token: returned directly by "
|
|
93
|
+
"check_permission when the purchase was allowed, or "
|
|
94
|
+
"by claim_decision_token after the owner approved.")
|
|
95
|
+
completion_nonce: str = Field(
|
|
96
|
+
min_length=1, max_length=512,
|
|
97
|
+
description="A unique nonce for this completion report. Reusing "
|
|
98
|
+
"the same nonce with the same evidence is how a "
|
|
99
|
+
"retried completion is recognised.")
|
|
100
|
+
completed_amount_minor: Optional[int] = Field(
|
|
101
|
+
default=None, ge=0,
|
|
102
|
+
description="What was actually paid, in minor units (cents), if "
|
|
103
|
+
"it differs from the checked amount. Sealed into the "
|
|
104
|
+
"receipt as agent-reported evidence.")
|
|
105
|
+
counterparty_receipt_ref: Optional[str] = Field(
|
|
106
|
+
default=None,
|
|
107
|
+
description="The merchant's own reference for the completed "
|
|
108
|
+
"purchase, e.g. an order number. Sealed into the "
|
|
109
|
+
"receipt.")
|
|
110
|
+
note: Optional[str] = Field(
|
|
111
|
+
default=None,
|
|
112
|
+
description="A short note about the completed purchase, sealed "
|
|
113
|
+
"into the receipt.")
|
|
114
|
+
completed_at: Optional[str] = Field(
|
|
115
|
+
default=None,
|
|
116
|
+
description="When the purchase completed (ISO 8601). Sealed "
|
|
117
|
+
"into the receipt.")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class GetReceiptInput(BaseModel):
|
|
121
|
+
receipt_id: Optional[str] = Field(
|
|
122
|
+
default=None,
|
|
123
|
+
description="A receipt id (rcpt_...). Returns that sealed "
|
|
124
|
+
"receipt.")
|
|
125
|
+
preauth_id: Optional[str] = Field(
|
|
126
|
+
default=None,
|
|
127
|
+
description="A preauth_id from check_permission. Returns the "
|
|
128
|
+
"check record, its current state, and its receipt id "
|
|
129
|
+
"once completed.")
|
|
130
|
+
limit: int = Field(
|
|
131
|
+
default=20, ge=1, le=100,
|
|
132
|
+
description="Used only when neither id is given: how many recent "
|
|
133
|
+
"receipts to list (1-100).")
|
|
134
|
+
|
|
135
|
+
@model_validator(mode="after")
|
|
136
|
+
def _at_most_one_id(self) -> "GetReceiptInput":
|
|
137
|
+
if self.receipt_id is not None and self.preauth_id is not None:
|
|
138
|
+
raise ValueError(
|
|
139
|
+
"Give at most one of receipt_id and preauth_id.")
|
|
140
|
+
return self
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""The four Sealgraf tools, as plain ``(input, ctx)`` functions.
|
|
2
|
+
|
|
3
|
+
These are written to Composio's current Python custom-tool shape: a
|
|
4
|
+
Pydantic model in, a JSON-serialisable dict out, the docstring as the
|
|
5
|
+
tool description. :func:`build_toolkit` registers them on a
|
|
6
|
+
``composio.experimental.Toolkit``; they can equally be attached one by
|
|
7
|
+
one with ``@composio.experimental.tool()``. The functions themselves do
|
|
8
|
+
not import Composio, so they are unit-testable without the SDK.
|
|
9
|
+
|
|
10
|
+
Fail-closed discipline: any failure — no API key configured, timeout,
|
|
11
|
+
network error, non-2xx, malformed response — raises
|
|
12
|
+
:class:`SealgrafToolError`, which fails the tool run. A tool NEVER
|
|
13
|
+
returns a result that could be read as permission when Sealgraf did not
|
|
14
|
+
actually grant it.
|
|
15
|
+
|
|
16
|
+
``needs_human_approval`` is not an error: it is a normal check outcome.
|
|
17
|
+
The result carries ``preauth_id`` and ``state: "pending_approval"`` so
|
|
18
|
+
the agent can pause, let the owner decide on Sealgraf's own surface, and
|
|
19
|
+
later resume with claim_decision_token + complete_purchase.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import functools
|
|
25
|
+
|
|
26
|
+
from .client import SealgrafClient, SealgrafError, SealgrafSettings
|
|
27
|
+
from .schemas import (
|
|
28
|
+
CheckPermissionInput,
|
|
29
|
+
ClaimDecisionTokenInput,
|
|
30
|
+
CompletePurchaseInput,
|
|
31
|
+
GetReceiptInput,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class SealgrafToolError(Exception):
|
|
36
|
+
"""The tool run failed. Nothing was approved, claimed, or sealed."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _client() -> SealgrafClient:
|
|
40
|
+
"""Build the API client from host configuration (environment).
|
|
41
|
+
|
|
42
|
+
Kept as a module-level seam so tests can substitute a client wired
|
|
43
|
+
to a mock transport.
|
|
44
|
+
"""
|
|
45
|
+
return SealgrafSettings.from_env().client()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _fail_closed(fn):
|
|
49
|
+
@functools.wraps(fn)
|
|
50
|
+
def wrapper(input, ctx=None):
|
|
51
|
+
try:
|
|
52
|
+
return fn(input, ctx)
|
|
53
|
+
except SealgrafToolError:
|
|
54
|
+
raise
|
|
55
|
+
except SealgrafError as exc:
|
|
56
|
+
raise SealgrafToolError(str(exc)) from exc
|
|
57
|
+
except Exception as exc: # never leak an ambiguous success shape
|
|
58
|
+
raise SealgrafToolError(
|
|
59
|
+
f"{fn.__name__} failed unexpectedly "
|
|
60
|
+
f"({exc.__class__.__name__}: {exc}); nothing was decided "
|
|
61
|
+
"or sealed.") from exc
|
|
62
|
+
|
|
63
|
+
return wrapper
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@_fail_closed
|
|
67
|
+
def check_permission(input: CheckPermissionInput, ctx=None) -> dict:
|
|
68
|
+
"""Ask Sealgraf whether this exact purchase may go ahead, BEFORE buying anything. Returns the decision: 'allow' (with a single-use decision_token — buy, then call complete_purchase), 'deny' (do not buy), or 'needs_human_approval' (state 'pending_approval': pause and let the owner decide on Sealgraf; afterwards call claim_decision_token with the preauth_id). Always call this before spending money; a purchase made without an 'allow' has no sealed receipt."""
|
|
69
|
+
result = _client().check_permission(
|
|
70
|
+
category=input.category.value,
|
|
71
|
+
amount_minor=input.amount_minor,
|
|
72
|
+
counterparty=input.counterparty,
|
|
73
|
+
description=input.description,
|
|
74
|
+
currency=input.currency,
|
|
75
|
+
agent_id=input.agent_id,
|
|
76
|
+
mandate_id=input.mandate_id,
|
|
77
|
+
idempotency_key=input.idempotency_key,
|
|
78
|
+
)
|
|
79
|
+
out = dict(result)
|
|
80
|
+
decision = result.get("decision")
|
|
81
|
+
if isinstance(decision, dict) and "outcome" in decision:
|
|
82
|
+
# Surface the outcome at the top level so an agent cannot miss
|
|
83
|
+
# it. Copied verbatim from the server's decision — never derived.
|
|
84
|
+
out["outcome"] = decision["outcome"]
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@_fail_closed
|
|
89
|
+
def claim_decision_token(input: ClaimDecisionTokenInput, ctx=None) -> dict:
|
|
90
|
+
"""Claim the single-use decision token for a purchase the owner has approved in Sealgraf. Use after check_permission returned 'needs_human_approval' and the owner has approved: this returns the decision_token that complete_purchase needs. Fails while the purchase is still waiting for the owner (code 'not_approved_yet') — wait and retry later instead of buying."""
|
|
91
|
+
return _client().claim_decision_token(input.preauth_id)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@_fail_closed
|
|
95
|
+
def complete_purchase(input: CompletePurchaseInput, ctx=None) -> dict:
|
|
96
|
+
"""Report a finished purchase to Sealgraf so it is sealed into a receipt. Call AFTER the purchase has actually been made, with the decision_token from check_permission or claim_decision_token. The amounts and merchant reference you report are sealed as agent-reported evidence next to the owner's proven approval. Returns the sealed receipt."""
|
|
97
|
+
evidence: dict = {}
|
|
98
|
+
if input.completed_amount_minor is not None:
|
|
99
|
+
evidence["completed_amount_minor"] = input.completed_amount_minor
|
|
100
|
+
if input.counterparty_receipt_ref is not None:
|
|
101
|
+
evidence["counterparty_receipt_ref"] = input.counterparty_receipt_ref
|
|
102
|
+
if input.note is not None:
|
|
103
|
+
evidence["note"] = input.note
|
|
104
|
+
if input.completed_at is not None:
|
|
105
|
+
evidence["completed_at"] = input.completed_at
|
|
106
|
+
return _client().complete_purchase(
|
|
107
|
+
input.preauth_id,
|
|
108
|
+
decision_token=input.decision_token,
|
|
109
|
+
completion_nonce=input.completion_nonce,
|
|
110
|
+
evidence=evidence,
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@_fail_closed
|
|
115
|
+
def get_receipt(input: GetReceiptInput, ctx=None) -> dict:
|
|
116
|
+
"""Fetch a Sealgraf receipt or check record. With receipt_id, returns the sealed receipt. With preauth_id, returns the check, its current state (e.g. 'pending_approval', 'authorized', 'completed'), and its receipt_id once completed. With neither, lists the most recent sealed receipts for this agent key."""
|
|
117
|
+
client = _client()
|
|
118
|
+
if input.receipt_id is not None:
|
|
119
|
+
return client.get_receipt(input.receipt_id)
|
|
120
|
+
if input.preauth_id is not None:
|
|
121
|
+
return client.get_preauthorization(input.preauth_id)
|
|
122
|
+
return client.list_receipts(limit=input.limit)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
TOOL_FUNCTIONS = (
|
|
126
|
+
check_permission,
|
|
127
|
+
claim_decision_token,
|
|
128
|
+
complete_purchase,
|
|
129
|
+
get_receipt,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
TOOLKIT_SLUG = "sealgraf"
|
|
133
|
+
TOOLKIT_NAME = "Sealgraf"
|
|
134
|
+
TOOLKIT_DESCRIPTION = (
|
|
135
|
+
"Sealgraf spend approval for agents: check a purchase against the "
|
|
136
|
+
"owner's pre-set limits before buying, let the owner approve larger "
|
|
137
|
+
"purchases on Sealgraf's own surface, and seal every completed "
|
|
138
|
+
"purchase into a receipt neither side can rewrite."
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def build_toolkit(composio):
|
|
143
|
+
"""Register the four tools on a Composio local (custom) toolkit.
|
|
144
|
+
|
|
145
|
+
``composio`` is a ``composio.Composio`` client instance. Returns the
|
|
146
|
+
``composio.experimental.Toolkit``; attach it to a session with
|
|
147
|
+
``experimental={"custom_toolkits": [toolkit]}``. Inside the session
|
|
148
|
+
the tools are exposed as LOCAL_SEALGRAF_CHECK_PERMISSION,
|
|
149
|
+
LOCAL_SEALGRAF_CLAIM_DECISION_TOKEN, LOCAL_SEALGRAF_COMPLETE_PURCHASE
|
|
150
|
+
and LOCAL_SEALGRAF_GET_RECEIPT.
|
|
151
|
+
"""
|
|
152
|
+
toolkit = composio.experimental.Toolkit(
|
|
153
|
+
slug=TOOLKIT_SLUG, name=TOOLKIT_NAME,
|
|
154
|
+
description=TOOLKIT_DESCRIPTION)
|
|
155
|
+
for fn in TOOL_FUNCTIONS:
|
|
156
|
+
toolkit.tool()(fn)
|
|
157
|
+
return toolkit
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sealgraf-composio
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Sealgraf spend-approval tools as a Composio local (custom) toolkit: check a purchase against the owner's limits before buying, owner approval on Sealgraf's own surface, sealed receipts.
|
|
5
|
+
Author: Sai Arun Gunuganti
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://sealgraf.com
|
|
8
|
+
Project-URL: Documentation, https://sealgraf.com/developers/setup
|
|
9
|
+
Keywords: composio,agents,spend-approval,sealgraf,receipts
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: composio>=0.28
|
|
19
|
+
Requires-Dist: httpx>=0.27
|
|
20
|
+
Requires-Dist: pydantic>=2
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# Sealgraf for Composio
|
|
24
|
+
|
|
25
|
+
Four tools that give a Composio agent a spending conscience:
|
|
26
|
+
**check before buying, owner approval above the owner's own line, and a
|
|
27
|
+
sealed receipt for every completed purchase.**
|
|
28
|
+
|
|
29
|
+
Sealgraf (https://sealgraf.com) is a spend-approval service for agents.
|
|
30
|
+
An agent checks a purchase *before* buying; the check is decided against
|
|
31
|
+
limits the owner set in advance; a purchase above the owner's approval
|
|
32
|
+
line waits for the owner to decide on Sealgraf's own surface; and when
|
|
33
|
+
the purchase completes, the evidence is sealed into a receipt that
|
|
34
|
+
neither the agent nor the owner can rewrite afterwards.
|
|
35
|
+
|
|
36
|
+
This package is a **Composio local (custom) toolkit** for the Python
|
|
37
|
+
SDK — the current canonical custom-tool form
|
|
38
|
+
(`composio.experimental.Toolkit`, Tool Router sessions). It runs
|
|
39
|
+
in-process in your application, next to Composio's catalog tools. It is
|
|
40
|
+
not a public-catalog listing; see `../RESEARCH.md` for what that would
|
|
41
|
+
take and why this package is the buildable artifact today.
|
|
42
|
+
|
|
43
|
+
## The four tools
|
|
44
|
+
|
|
45
|
+
Inside a session they are exposed as `LOCAL_SEALGRAF_*`:
|
|
46
|
+
|
|
47
|
+
| Tool | What it does |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `LOCAL_SEALGRAF_CHECK_PERMISSION` | Ask before a purchase. Returns `allow` (with a single-use decision token), `deny`, or `needs_human_approval` with a `preauth_id` to resume later. |
|
|
50
|
+
| `LOCAL_SEALGRAF_CLAIM_DECISION_TOKEN` | After the owner approves a waiting purchase in Sealgraf, claim its single-use decision token. |
|
|
51
|
+
| `LOCAL_SEALGRAF_COMPLETE_PURCHASE` | Report the finished purchase; Sealgraf seals it into a receipt. |
|
|
52
|
+
| `LOCAL_SEALGRAF_GET_RECEIPT` | Fetch state by exactly one id: a receipt id (reads `GET /v1/receipts/{id}` — the sealed receipt) or a preauth id (reads `GET /v1/preauthorize/{id}` — the check record and its current state). With neither id, lists recent receipts. |
|
|
53
|
+
|
|
54
|
+
The spend loop an agent should follow:
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
check_permission ── allow ─────────────► buy ──► complete_purchase ──► sealed receipt
|
|
58
|
+
└─ needs_human_approval ─► (owner decides in Sealgraf)
|
|
59
|
+
─► claim_decision_token ─► buy ─► complete_purchase
|
|
60
|
+
└─ deny ─► do not buy
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Not the same as Composio's approvals / the HITL toolkit
|
|
64
|
+
|
|
65
|
+
Composio has an (experimental) session feature that can require the
|
|
66
|
+
user's approval before chosen tools run, and its catalog carries a
|
|
67
|
+
generic human-approval toolkit (`hitl`). Both are **in-band, per-call
|
|
68
|
+
prompts**: a person sitting in the agent's client is asked "run this
|
|
69
|
+
tool?", with no limits, no amounts, and nothing kept afterwards beyond
|
|
70
|
+
a log line; "always approve" waives the rest of the session.
|
|
71
|
+
|
|
72
|
+
Sealgraf is different in kind:
|
|
73
|
+
|
|
74
|
+
- **Limits are set in advance.** The owner pre-commits per-purchase and
|
|
75
|
+
period caps, allowed categories, and an approval threshold (a
|
|
76
|
+
"mandate"). Most checks are decided automatically against those
|
|
77
|
+
limits — no human is paged for routine purchases.
|
|
78
|
+
- **Approval happens on Sealgraf's own surface**, out-of-band from the
|
|
79
|
+
agent session, and only the owner can give it: an agent key can never
|
|
80
|
+
approve its own check (enforced server-side).
|
|
81
|
+
- **The subject is money, not tool calls**: a specific amount, currency,
|
|
82
|
+
category, and counterparty.
|
|
83
|
+
- **The output is a sealed receipt** — the check, the decision (and who
|
|
84
|
+
approved it), and the completion evidence, hash-chained so neither
|
|
85
|
+
side can rewrite the record.
|
|
86
|
+
|
|
87
|
+
One line: Composio's approval asks *"may this tool run?"* in the
|
|
88
|
+
moment; Sealgraf answers *"was this purchase inside the owner's rules,
|
|
89
|
+
who said yes when it wasn't, and where is the proof?"* — before,
|
|
90
|
+
during, and after the spend.
|
|
91
|
+
|
|
92
|
+
## Setup
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
pip install sealgraf-composio # or from this repo: pip install ./toolkit
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Configuration is host-side, via environment — **never** tool arguments
|
|
99
|
+
(tool arguments are chosen by the model and visible in prompts/logs;
|
|
100
|
+
the key is a credential):
|
|
101
|
+
|
|
102
|
+
| Variable | Required | Meaning |
|
|
103
|
+
|---|---|---|
|
|
104
|
+
| `SEALGRAF_API_KEY` | yes | An agent-scope Sealgraf API key, sent as the `X-API-Key` header. The key is bound server-side to one agent and mandate, which is how the tools can leave `mandate_id`, `agent_id` and `currency` unset. |
|
|
105
|
+
| `SEALGRAF_BASE_URL` | no | Default `https://sealgraf.com`. Point it at UAT or a local instance for testing. |
|
|
106
|
+
| `SEALGRAF_TIMEOUT_SECONDS` | no | Default `20`. Every call has an explicit timeout. |
|
|
107
|
+
|
|
108
|
+
Plus the usual Composio setup for the host app (`COMPOSIO_API_KEY`).
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
from composio import Composio
|
|
112
|
+
from sealgraf_composio import build_toolkit
|
|
113
|
+
|
|
114
|
+
composio = Composio()
|
|
115
|
+
session = composio.create(
|
|
116
|
+
user_id="default",
|
|
117
|
+
experimental={"custom_toolkits": [build_toolkit(composio)]},
|
|
118
|
+
)
|
|
119
|
+
tools = session.tools() # handed to your agent framework as usual
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
See `example_session.py` for a runnable wiring, including direct
|
|
123
|
+
`session.execute(...)` calls outside an agent loop.
|
|
124
|
+
|
|
125
|
+
## Behaviour guarantees
|
|
126
|
+
|
|
127
|
+
- **Fail closed.** A missing key, timeout, network error, non-2xx
|
|
128
|
+
response, or malformed response raises an error and fails the tool
|
|
129
|
+
run. A tool never returns anything that could be read as permission
|
|
130
|
+
unless Sealgraf actually granted it.
|
|
131
|
+
- **`needs_human_approval` is a normal outcome**, not an error. The
|
|
132
|
+
result carries `preauth_id` and `state: "pending_approval"`; the
|
|
133
|
+
agent pauses and resumes with `claim_decision_token` once the owner
|
|
134
|
+
has decided. Only the agent key that ran the check can claim its
|
|
135
|
+
token.
|
|
136
|
+
- **Idempotency.** Pass `idempotency_key` to `check_permission` and a
|
|
137
|
+
retried check returns the original record (`replayed: true`) instead
|
|
138
|
+
of stacking a second reservation.
|
|
139
|
+
- **Amounts are integer minor units** (cents) everywhere, matching
|
|
140
|
+
Sealgraf's API. Categories are Sealgraf's closed enum of 14.
|
|
141
|
+
|
|
142
|
+
## Development
|
|
143
|
+
|
|
144
|
+
```bash
|
|
145
|
+
python -m venv .venv && .venv/bin/pip install -e . pytest
|
|
146
|
+
cd ../tests && ../toolkit/.venv/bin/python -m pytest . -q
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
The test suite mocks all HTTP and asserts the exact requests against
|
|
150
|
+
the production API contract (see `../RESEARCH.md` for the contract and
|
|
151
|
+
its code citations, and `../BUILD-RECORD.md` for run evidence).
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
sealgraf_composio/__init__.py,sha256=N0imw5ALtnU8bI_f3bf5ZnITcCiXL3FTnvuAi4v5wWs,1080
|
|
2
|
+
sealgraf_composio/client.py,sha256=wkIi1nB7I1T8uW4NoFRyROmwkaSg3tyK37XdAXZW2es,9875
|
|
3
|
+
sealgraf_composio/schemas.py,sha256=i7pIO-FFHa7ZH2qia3ZGA-0xpgfgQ_1jnxl6vHo2118,5721
|
|
4
|
+
sealgraf_composio/tools.py,sha256=NzMm5-xQfINOlLCUe1sGsh0iTN-0TgBCDrxONpQO61s,6866
|
|
5
|
+
sealgraf_composio-0.1.0.dist-info/licenses/LICENSE,sha256=cvMH1n0qPsAqAYYT0TuiyP8YNzbszpBLsVe5eS42gFg,1075
|
|
6
|
+
sealgraf_composio-0.1.0.dist-info/METADATA,sha256=xJEYrypPw90aJNQJOUAmyH8UDLRyNwv7xTq4FTkhOGg,7022
|
|
7
|
+
sealgraf_composio-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
sealgraf_composio-0.1.0.dist-info/top_level.txt,sha256=AQtERYgxgpkvzpELlU0FGmIGjUh0gn629V-Id_ZGY1g,18
|
|
9
|
+
sealgraf_composio-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sai Arun Gunuganti
|
|
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 @@
|
|
|
1
|
+
sealgraf_composio
|