getaccord 0.6.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.
getaccord/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """Accord for Python: let AI agents spend within limits you set.
2
+
3
+ from getaccord import Accord
4
+
5
+ accord = Accord() # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
6
+ intent = accord.intent(budget=4500) # cents; or budget_micros= for exact sub-cent amounts
7
+ intent.hold("skyfare", 3000)
8
+ intent.hold("stayco", 1500)
9
+ result = intent.commit() # everyone is paid, or no one is
10
+ """
11
+
12
+ from .aio import AsyncAccord, AsyncIntent
13
+ from .client import Accord, CommitResult, HoldSpec, Intent, PlacedHold
14
+ from .errors import AccordError
15
+ from .keys import AgentKey, agent_id
16
+ from .money import micros, usd
17
+ from .seller import Handler, verify_signature
18
+ from .settings import DEFAULT_URL
19
+
20
+ __version__ = "0.6.0"
21
+
22
+ __all__ = [
23
+ "Accord",
24
+ "AccordError",
25
+ "AgentKey",
26
+ "AsyncAccord",
27
+ "AsyncIntent",
28
+ "CommitResult",
29
+ "DEFAULT_URL",
30
+ "Handler",
31
+ "HoldSpec",
32
+ "Intent",
33
+ "PlacedHold",
34
+ "agent_id",
35
+ "micros",
36
+ "usd",
37
+ "verify_signature",
38
+ ]
getaccord/aio.py ADDED
@@ -0,0 +1,44 @@
1
+ """Async versions: the same methods, run in a worker thread so they don't block the event loop.
2
+
3
+ accord = AsyncAccord()
4
+ intent = await accord.intent(budget=4500)
5
+ await intent.hold("skyfare", 3000)
6
+ result = await intent.commit()
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import functools
13
+ from typing import Any, Callable, Optional
14
+
15
+ from .client import Accord, Intent
16
+
17
+
18
+ def _run(f: Callable[..., Any]) -> Callable[..., Any]:
19
+ @functools.wraps(f)
20
+ async def wrapper(*args: Any, **kwargs: Any) -> Any:
21
+ return await asyncio.to_thread(f, *args, **kwargs)
22
+
23
+ return wrapper
24
+
25
+
26
+ class AsyncIntent:
27
+ def __init__(self, intent: Intent):
28
+ self._i = intent
29
+ for name in ("hold", "holds", "results", "accept", "reject", "commit", "abort", "state"):
30
+ setattr(self, name, _run(getattr(intent, name)))
31
+
32
+ @property
33
+ def id(self) -> Optional[str]:
34
+ return self._i.id
35
+
36
+
37
+ class AsyncAccord:
38
+ def __init__(self, url: Optional[str] = None, **kwargs: Any):
39
+ self.sync = Accord(url, **kwargs)
40
+ self.get = _run(self.sync.get)
41
+ self.balance = _run(self.sync.balance)
42
+
43
+ async def intent(self, *args: Any, **kwargs: Any) -> AsyncIntent:
44
+ return AsyncIntent(await asyncio.to_thread(self.sync.intent, *args, **kwargs))
getaccord/client.py ADDED
@@ -0,0 +1,348 @@
1
+ """The buyer side: an agent opens a purchase (an intent), holds money with sellers, then commits or aborts.
2
+
3
+ Mirrors @getaccord/sdk 0.6.0. Every money-moving step is prepared by Accord, signed here with the
4
+ agent key, and executed with Accord paying the network fee; the chain enforces the key's limits.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import json
11
+ import time
12
+ import urllib.error
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Union
16
+
17
+ from .errors import AccordError
18
+ from .keys import AgentKey, load_key
19
+ from .money import MICROS_PER_CENT, amount_field, duration_ms, to_micros
20
+ from .settings import DEFAULT_URL, setting
21
+
22
+ #: (method, url, headers, body bytes or None) -> (status, body bytes). Replace it in tests.
23
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes]], "tuple[int, bytes]"]
24
+
25
+ POLL_SECONDS = 0.4
26
+ _NEEDS_SIGN_OFF = "This purchase needs a person's sign-off."
27
+
28
+
29
+ def urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes]) -> "tuple[int, bytes]":
30
+ req = urllib.request.Request(url, data=body, method=method, headers={"user-agent": "getaccord-python/0.6.0", **headers})
31
+ try:
32
+ with urllib.request.urlopen(req, timeout=60) as res:
33
+ return res.status, res.read()
34
+ except urllib.error.HTTPError as e:
35
+ return e.code, e.read()
36
+ except urllib.error.URLError as e:
37
+ raise AccordError("network_error", f"Couldn't reach {url}: {e.reason}") from None
38
+
39
+
40
+ @dataclass
41
+ class PlacedHold:
42
+ index: int
43
+ seller: str
44
+ amount: int
45
+ """Whole cents (rounded down)."""
46
+ amount_micros: int
47
+ """Exact."""
48
+ status: str = "placed"
49
+
50
+
51
+ @dataclass
52
+ class CommitResult:
53
+ status: str
54
+ """committed, aborted, expired or awaiting_approval."""
55
+ paid: int
56
+ intent: Dict[str, Any]
57
+ digest: Optional[str] = None
58
+ reason: Optional[str] = None
59
+
60
+
61
+ @dataclass
62
+ class HoldSpec:
63
+ """One hold for ``Intent.holds([...])``."""
64
+
65
+ seller: str
66
+ amount: Optional[int] = None
67
+ amount_micros: Optional[Union[int, str]] = None
68
+ ref: str = ""
69
+ type: str = "reserve"
70
+
71
+
72
+ class Accord:
73
+ """The Accord client. ``Accord()`` reads ACCORD_URL from the environment or ./.env."""
74
+
75
+ def __init__(self, url: Optional[str] = None, transport: Optional[Transport] = None):
76
+ self.url = (url or setting("ACCORD_URL") or DEFAULT_URL).rstrip("/")
77
+ self._transport = transport or urllib_transport
78
+ self.test = _Test(self)
79
+ self.sellers = _Sellers(self)
80
+ self.owner = _Owner(self)
81
+
82
+ def intent(
83
+ self,
84
+ budget: Optional[int] = None,
85
+ *,
86
+ budget_micros: Optional[Union[int, str]] = None,
87
+ coin: Optional[str] = None,
88
+ mode: str = "all",
89
+ expires_in: str = "15m",
90
+ key: Optional[str] = None,
91
+ ) -> "Intent":
92
+ """Opens a purchase within the agent key's limits. ``budget`` is whole cents; ``budget_micros`` is exact.
93
+ ``coin``: the usual dollar coin (default) or "USDC". ``mode``: "all" (everyone or no one is paid) or "each"."""
94
+ if mode not in ("all", "each"):
95
+ raise AccordError("invalid_mode", 'mode is "all" or "each".')
96
+ amount_field("budget", budget, budget_micros) # checks now, not at the first hold
97
+ return Intent(self, load_key(key), budget, budget_micros, coin, mode, expires_in)
98
+
99
+ def get(self, intent_id: str) -> Dict[str, Any]:
100
+ return self.call("GET", f"/v1/intents/{intent_id}")
101
+
102
+ def balance(self, key: Optional[str] = None) -> Dict[str, Any]:
103
+ """What the key's owner has available, and what's left of the key's weekly budget."""
104
+ return self.call("POST", "/v1/balance", {"agent": load_key(key).address})
105
+
106
+ @staticmethod
107
+ def agent_id(key: str) -> str:
108
+ """The public ID of an agent key (what sellers see as ``buyer``)."""
109
+ return AgentKey.from_secret(key).address
110
+
111
+ # --- internal ---
112
+
113
+ def call(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, bearer: Optional[str] = None) -> Dict[str, Any]:
114
+ headers: Dict[str, str] = {}
115
+ data = None
116
+ if body is not None:
117
+ headers["content-type"] = "application/json"
118
+ data = json.dumps(body).encode()
119
+ if bearer:
120
+ headers["authorization"] = f"Bearer {bearer}"
121
+ status, raw = self._transport(method, self.url + path, headers, data)
122
+ try:
123
+ out = json.loads(raw or b"{}")
124
+ except ValueError:
125
+ out = {}
126
+ if status >= 400:
127
+ err = out.get("error") or {} if isinstance(out, dict) else {}
128
+ raise AccordError(err.get("code") or f"http_{status}", err.get("message"))
129
+ return out
130
+
131
+ def signed(self, key: AgentKey, path: str, body: Dict[str, Any]) -> Dict[str, Any]:
132
+ """Prepare -> sign with the agent key -> Accord adds the network fee and executes."""
133
+ prepared = self.call("POST", path, {**body, "agent": key.address})
134
+ tx_bytes = prepared.pop("txBytes")
135
+ signature = key.sign_transaction(base64.b64decode(tx_bytes))
136
+ out = self.call("POST", "/v1/tx/execute", {"txBytes": tx_bytes, "signature": signature})
137
+ return {**prepared, **out}
138
+
139
+
140
+ class Intent:
141
+ """One purchase. Place holds, then ``commit()`` (everyone is paid) or ``abort()`` (every hold comes back)."""
142
+
143
+ def __init__(self, accord: Accord, key: AgentKey, budget, budget_micros, coin, mode, expires_in):
144
+ self.id: Optional[str] = None
145
+ self._accord = accord
146
+ self._key = key
147
+ self._budget = budget
148
+ self._budget_micros = budget_micros
149
+ self._coin = coin
150
+ self._mode = mode
151
+ self._ttl_ms = duration_ms(expires_in)
152
+ self._awaiting = False
153
+ self._approval_reason: Optional[str] = None
154
+
155
+ @property
156
+ def key(self) -> AgentKey:
157
+ return self._key
158
+
159
+ def hold(self, seller: str, amount: Optional[int] = None, *, amount_micros: Optional[Union[int, str]] = None, ref: str = "", type: str = "reserve") -> PlacedHold:
160
+ """Locks money with a seller. ``amount`` is whole cents; ``amount_micros`` is exact."""
161
+ return self.holds([HoldSpec(seller, amount, amount_micros, ref, type)])[0]
162
+
163
+ def holds(self, holds: Sequence[Union[HoldSpec, Dict[str, Any]]]) -> List[PlacedHold]:
164
+ """Places several holds in one step (one transaction), like holds placed together in the TypeScript SDK."""
165
+ specs = [h if isinstance(h, HoldSpec) else HoldSpec(**h) for h in holds]
166
+ if not specs:
167
+ return []
168
+ wire = []
169
+ for h in specs:
170
+ if h.type not in ("reserve", "deliver"):
171
+ raise AccordError("invalid_hold_type", 'type is "reserve" or "deliver".')
172
+ wire.append({"seller": h.seller, **amount_field("amount", h.amount, h.amount_micros), "ref": h.ref, "type": h.type})
173
+ if self.id is None:
174
+ body: Dict[str, Any] = {
175
+ **amount_field("budget", self._budget, self._budget_micros),
176
+ "mode": self._mode,
177
+ "ttlMs": self._ttl_ms,
178
+ "holds": wire,
179
+ }
180
+ if self._coin:
181
+ body["coin"] = self._coin
182
+ out = self._accord.signed(self._key, "/v1/intents/prepare", body)
183
+ self.id = out["intentId"]
184
+ self._awaiting = bool(out.get("awaitingApproval"))
185
+ self._approval_reason = out.get("approvalReason")
186
+ else:
187
+ if self._awaiting:
188
+ # A person may have approved it since.
189
+ self._awaiting = self._accord.get(self.id)["status"] == "awaiting_approval"
190
+ if not self._awaiting:
191
+ out = self._accord.signed(self._key, f"/v1/intents/{self.id}/holds/prepare", {"holds": wire})
192
+ if self._awaiting:
193
+ raise AccordError(
194
+ "awaiting_approval",
195
+ f"{self._approval_reason or _NEEDS_SIGN_OFF} No money is locked until then. "
196
+ "Place holds again after it is approved (in test mode: accord.test.approve(intent.id)).",
197
+ )
198
+ placed = []
199
+ for h, got in zip(specs, out["holds"]):
200
+ m = to_micros(h.amount, h.amount_micros)
201
+ placed.append(PlacedHold(index=got["index"], seller=h.seller, amount=m // MICROS_PER_CENT, amount_micros=m))
202
+ return placed
203
+
204
+ def results(self, wait: str = "60s") -> List[Dict[str, Any]]:
205
+ """Deliver holds: waits until each seller has delivered (or declined), then returns the delivered work.
206
+ Check each one, then ``accept(index)`` or ``reject(index)``."""
207
+ intent_id = self._opened()
208
+ until = time.monotonic() + duration_ms(wait) / 1000
209
+ while True:
210
+ state = self._accord.get(intent_id)
211
+ working = [h for h in state["holds"] if h["type"] == "deliver" and h["state"] == "placed"]
212
+ if not working or time.monotonic() > until or state["status"] != "open":
213
+ return [h for h in state["holds"] if h["type"] == "deliver" and h["state"] == "submitted"]
214
+ time.sleep(POLL_SECONDS)
215
+
216
+ def accept(self, index: int) -> Dict[str, Any]:
217
+ """Accepts delivered work: that seller is paid at commit."""
218
+ return {"digest": self._accord.signed(self._key, f"/v1/intents/{self._opened()}/accept/prepare", {"index": index})["digest"]}
219
+
220
+ def reject(self, index: int) -> Dict[str, Any]:
221
+ """Rejects delivered work: that seller's hold comes back and they aren't paid."""
222
+ return {"digest": self._accord.signed(self._key, f"/v1/intents/{self._opened()}/reject/prepare", {"index": index})["digest"]}
223
+
224
+ def commit(self, wait: str = "60s") -> CommitResult:
225
+ """Waits for every seller to answer, then pays everyone at once. In "all" mode a decline or a timeout
226
+ aborts the purchase and releases every hold. Delivered work must be accepted or rejected first."""
227
+ if self.id is None:
228
+ raise AccordError("no_holds", "Place at least one hold before commit")
229
+ until = time.monotonic() + duration_ms(wait) / 1000
230
+ while True:
231
+ state = self._accord.get(self.id)
232
+ if state["status"] == "awaiting_approval":
233
+ return CommitResult(status=state["status"], paid=0, intent=state)
234
+ if state["status"] != "open":
235
+ return CommitResult(status=state["status"], paid=state.get("paid", 0), intent=state)
236
+ undecided = [h["seller"] for h in state["holds"] if h["state"] == "submitted"]
237
+ if undecided:
238
+ raise AccordError(
239
+ "results_pending",
240
+ f"{', '.join(undecided)} delivered work that isn't accepted or rejected yet. "
241
+ "Use intent.results(), then intent.accept(i) or intent.reject(i).",
242
+ )
243
+ pending = [h["seller"] for h in state["holds"] if h["state"] == "placed"]
244
+ declined = [h["seller"] for h in state["holds"] if h["state"] in ("declined", "rejected")]
245
+ if self._mode == "all" and declined:
246
+ return self._abort(f"{', '.join(declined)} declined")
247
+ if not pending:
248
+ break
249
+ if time.monotonic() > until:
250
+ if self._mode == "all":
251
+ return self._abort(f"{', '.join(pending)} did not confirm in time")
252
+ break # "each": pay whoever is ready
253
+ time.sleep(POLL_SECONDS)
254
+ out = self._accord.signed(self._key, f"/v1/intents/{self.id}/commit/prepare", {})
255
+ intent = self._accord.get(self.id)
256
+ return CommitResult(status=intent["status"], paid=intent.get("paid", 0), digest=out.get("digest"), intent=intent)
257
+
258
+ def abort(self) -> CommitResult:
259
+ """Calls the purchase off. Every held dollar goes back."""
260
+ return self._abort("aborted by the agent")
261
+
262
+ def state(self) -> Dict[str, Any]:
263
+ return self._accord.get(self._opened())
264
+
265
+ def _abort(self, reason: str) -> CommitResult:
266
+ out = self._accord.signed(self._key, f"/v1/intents/{self._opened()}/abort/prepare", {})
267
+ intent = self._accord.get(self._opened())
268
+ return CommitResult(status=intent["status"], paid=0, reason=reason, digest=out.get("digest"), intent=intent)
269
+
270
+ def _opened(self) -> str:
271
+ if self.id is None:
272
+ raise AccordError("not_opened")
273
+ return self.id
274
+
275
+
276
+ class _Test:
277
+ """Test mode only."""
278
+
279
+ def __init__(self, accord: Accord):
280
+ self._a = accord
281
+
282
+ def fail_seller(self, seller: str, fail: bool = True, key: Optional[str] = None) -> Dict[str, Any]:
283
+ """Makes a demo seller decline every hold from this agent key (or stop doing so)."""
284
+ return self._a.call("POST", f"/v1/test/sellers/{seller}/fail", {"agent": load_key(key).address, "fail": fail})
285
+
286
+ def new_agent_key(self, name: str = "test-agent", weekly_budget: Optional[int] = None, approval_above: Optional[int] = None) -> Dict[str, Any]:
287
+ """A new test agent key with its own test balance. The key is made here; Accord gets only its public ID."""
288
+ kp = AgentKey.generate()
289
+ body: Dict[str, Any] = {"agent": kp.address, "name": name}
290
+ if weekly_budget is not None:
291
+ body["weeklyBudget"] = weekly_budget
292
+ if approval_above is not None:
293
+ body["approvalAbove"] = approval_above
294
+ out = self._a.call("POST", "/v1/test/signup", body)
295
+ return {"key": kp.secret(), "id": out["agent"], "owner_token": out.get("ownerToken"), "limits": out.get("limits")}
296
+
297
+ def approve(self, intent_id: str) -> Dict[str, Any]:
298
+ """Approves a purchase waiting for a person, as the owner would in the dashboard."""
299
+ return self._a.call("POST", f"/v1/intents/{intent_id}/approve", {})
300
+
301
+
302
+ class _Sellers:
303
+ """Seller side: sign up once, then manage the seller with its seller token (stk_...)."""
304
+
305
+ def __init__(self, accord: Accord):
306
+ self._a = accord
307
+
308
+ def register(self, name: str, webhook_url: str, payout: str, display_name: Optional[str] = None) -> Dict[str, Any]:
309
+ body = {"name": name, "webhookUrl": webhook_url, "payout": payout}
310
+ if display_name:
311
+ body["displayName"] = display_name
312
+ return self._a.call("POST", "/v1/sellers", body)
313
+
314
+ def get(self, name: str, seller_token: str) -> Dict[str, Any]:
315
+ return self._a.call("GET", f"/v1/sellers/{name}", None, seller_token)
316
+
317
+ def update(self, name: str, seller_token: str, webhook_url: Optional[str] = None, display_name: Optional[str] = None, payout: Optional[str] = None) -> Dict[str, Any]:
318
+ changes = {k: v for k, v in {"webhookUrl": webhook_url, "displayName": display_name, "payout": payout}.items() if v is not None}
319
+ return self._a.call("POST", f"/v1/sellers/{name}", changes, seller_token)
320
+
321
+ def rotate_secret(self, name: str, seller_token: str) -> Dict[str, Any]:
322
+ """A new webhook secret. The old one keeps working for 24 hours."""
323
+ return self._a.call("POST", f"/v1/sellers/{name}/rotate-secret", {}, seller_token)
324
+
325
+ def ping(self, name: str, seller_token: str) -> Dict[str, Any]:
326
+ return self._a.call("POST", f"/v1/sellers/{name}/ping", {}, seller_token)
327
+
328
+ def deactivate(self, name: str, seller_token: str) -> Dict[str, Any]:
329
+ return self._a.call("POST", f"/v1/sellers/{name}/deactivate", {}, seller_token)
330
+
331
+ def reactivate(self, name: str, seller_token: str) -> Dict[str, Any]:
332
+ return self._a.call("POST", f"/v1/sellers/{name}/reactivate", {}, seller_token)
333
+
334
+ def deliveries(self, name: str, seller_token: str) -> Dict[str, Any]:
335
+ return self._a.call("GET", f"/v1/sellers/{name}/deliveries", None, seller_token)
336
+
337
+
338
+ class _Owner:
339
+ """Owner-only changes, authorized by the owner token that ``init`` saved. Never give that token to an agent."""
340
+
341
+ def __init__(self, accord: Accord):
342
+ self._a = accord
343
+
344
+ def allow_seller(self, owner_token: str, agent: str, seller: str, allowed: bool = True) -> Dict[str, Any]:
345
+ return self._a.call("POST", "/v1/keys/sellers", {"agent": agent, "seller": seller, "allowed": allowed}, owner_token)
346
+
347
+ def revoke_key(self, owner_token: str, agent: str) -> Dict[str, Any]:
348
+ return self._a.call("POST", "/v1/keys/revoke", {"agent": agent}, owner_token)
getaccord/errors.py ADDED
@@ -0,0 +1,15 @@
1
+ """Errors from Accord, with the same codes as the TypeScript SDK and the service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Optional
6
+
7
+
8
+ class AccordError(Exception):
9
+ """An Accord error. ``code`` is stable (``limit_exceeded``, ``insufficient_balance``, ``too_many_holds``...);
10
+ the message is for people and says what to do."""
11
+
12
+ def __init__(self, code: str, message: Optional[str] = None):
13
+ super().__init__(f"{code}: {message}" if message else code)
14
+ self.code = code
15
+ self.detail = message
getaccord/keys.py ADDED
@@ -0,0 +1,176 @@
1
+ """Agent keys: the format the Accord CLI writes, the account ID, and Sui signatures.
2
+
3
+ An agent key is an Ed25519 key in Sui's bech32 form (``suiprivkey1...``), exactly what
4
+ ``npx @getaccord/cli init`` saves to ``.env``. It signs locally; Accord only ever sees
5
+ its public ID and its signatures.
6
+
7
+ Sui signatures, as the TypeScript SDK makes them:
8
+ transaction ed25519(blake2b-256([0, 0, 0] || tx_bytes))
9
+ personal message ed25519(blake2b-256([3, 0, 0] || uleb128(len(msg)) || msg))
10
+ serialized base64(0x00 || signature(64) || public key(32))
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import base64
16
+ import hashlib
17
+ import os
18
+ from typing import List, Optional
19
+
20
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
21
+ from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
22
+
23
+ from .errors import AccordError
24
+
25
+ PRIVATE_KEY_PREFIX = "suiprivkey"
26
+ ED25519_FLAG = 0x00
27
+ _CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
28
+
29
+
30
+ # --- bech32 (BIP-173, the variant Sui uses for private keys) ---
31
+
32
+
33
+ def _polymod(values: List[int]) -> int:
34
+ gen = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3]
35
+ chk = 1
36
+ for v in values:
37
+ top = chk >> 25
38
+ chk = (chk & 0x1FFFFFF) << 5 ^ v
39
+ for i in range(5):
40
+ chk ^= gen[i] if ((top >> i) & 1) else 0
41
+ return chk
42
+
43
+
44
+ def _hrp_expand(hrp: str) -> List[int]:
45
+ return [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
46
+
47
+
48
+ def _convert(data: List[int], frm: int, to: int, pad: bool) -> List[int]:
49
+ acc = bits = 0
50
+ out: List[int] = []
51
+ maxv = (1 << to) - 1
52
+ for v in data:
53
+ acc = (acc << frm) | v
54
+ bits += frm
55
+ while bits >= to:
56
+ bits -= to
57
+ out.append((acc >> bits) & maxv)
58
+ if pad and bits:
59
+ out.append((acc << (to - bits)) & maxv)
60
+ elif not pad and (bits >= frm or ((acc << (to - bits)) & maxv)):
61
+ raise ValueError("invalid padding")
62
+ return out
63
+
64
+
65
+ def _bech32_decode(s: str) -> "tuple[str, bytes]":
66
+ if s.lower() != s and s.upper() != s:
67
+ raise ValueError("mixed case")
68
+ s = s.lower()
69
+ pos = s.rfind("1")
70
+ if pos < 1 or pos + 7 > len(s):
71
+ raise ValueError("bad separator")
72
+ hrp, data = s[:pos], s[pos + 1 :]
73
+ try:
74
+ values = [_CHARSET.index(c) for c in data]
75
+ except ValueError:
76
+ raise ValueError("bad character") from None
77
+ if _polymod(_hrp_expand(hrp) + values) != 1:
78
+ raise ValueError("bad checksum")
79
+ return hrp, bytes(_convert(values[:-6], 5, 8, False))
80
+
81
+
82
+ def _bech32_encode(hrp: str, data: bytes) -> str:
83
+ values = _convert(list(data), 8, 5, True)
84
+ poly = _polymod(_hrp_expand(hrp) + values + [0] * 6) ^ 1
85
+ checksum = [(poly >> 5 * (5 - i)) & 31 for i in range(6)]
86
+ return hrp + "1" + "".join(_CHARSET[v] for v in values + checksum)
87
+
88
+
89
+ # --- Sui encoding ---
90
+
91
+
92
+ def blake2b256(data: bytes) -> bytes:
93
+ return hashlib.blake2b(data, digest_size=32).digest()
94
+
95
+
96
+ def uleb128(n: int) -> bytes:
97
+ out = bytearray()
98
+ while True:
99
+ b = n & 0x7F
100
+ n >>= 7
101
+ if n:
102
+ out.append(b | 0x80)
103
+ else:
104
+ out.append(b)
105
+ return bytes(out)
106
+
107
+
108
+ TRANSACTION_INTENT = bytes([0, 0, 0])
109
+ PERSONAL_MESSAGE_INTENT = bytes([3, 0, 0])
110
+
111
+
112
+ class AgentKey:
113
+ """An Ed25519 agent key. Make one with ``AgentKey.generate()`` or read one with ``AgentKey.from_secret(...)``."""
114
+
115
+ def __init__(self, seed: bytes):
116
+ if len(seed) != 32:
117
+ raise AccordError("invalid_key", "An agent key is 32 bytes.")
118
+ self._sk = Ed25519PrivateKey.from_private_bytes(seed)
119
+ self._seed = seed
120
+ self.public_key = self._sk.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)
121
+
122
+ @classmethod
123
+ def generate(cls) -> "AgentKey":
124
+ return cls(os.urandom(32))
125
+
126
+ @classmethod
127
+ def from_secret(cls, secret: str) -> "AgentKey":
128
+ """Reads ``suiprivkey1...`` (what ``accord init`` writes)."""
129
+ s = (secret or "").strip().strip("\"'")
130
+ try:
131
+ hrp, data = _bech32_decode(s)
132
+ except ValueError as e:
133
+ raise AccordError("invalid_key", f"That isn't an agent key ({e}). Run: npx @getaccord/cli init") from None
134
+ if hrp != PRIVATE_KEY_PREFIX or len(data) != 33:
135
+ raise AccordError("invalid_key", "That isn't an agent key. Run: npx @getaccord/cli init")
136
+ if data[0] != ED25519_FLAG:
137
+ raise AccordError("invalid_key", "Accord agent keys are Ed25519 keys.")
138
+ return cls(data[1:])
139
+
140
+ def secret(self) -> str:
141
+ """The key in the CLI's format (``suiprivkey1...``). Keep it secret."""
142
+ return _bech32_encode(PRIVATE_KEY_PREFIX, bytes([ED25519_FLAG]) + self._seed)
143
+
144
+ @property
145
+ def address(self) -> str:
146
+ """The key's public ID (what sellers see as ``buyer``)."""
147
+ return "0x" + blake2b256(bytes([ED25519_FLAG]) + self.public_key).hex()
148
+
149
+ def _serialize(self, signature: bytes) -> str:
150
+ return base64.b64encode(bytes([ED25519_FLAG]) + signature + self.public_key).decode()
151
+
152
+ def sign_transaction(self, tx_bytes: bytes) -> str:
153
+ """Signs transaction bytes; returns Sui's serialized signature (base64)."""
154
+ return self._serialize(self._sk.sign(blake2b256(TRANSACTION_INTENT + tx_bytes)))
155
+
156
+ def sign_personal_message(self, message: bytes) -> str:
157
+ """Signs a personal message; returns Sui's serialized signature (base64)."""
158
+ return self._serialize(self._sk.sign(blake2b256(PERSONAL_MESSAGE_INTENT + uleb128(len(message)) + message)))
159
+
160
+ def __repr__(self) -> str: # never print the secret
161
+ return f"AgentKey({self.address})"
162
+
163
+
164
+ def agent_id(secret: str) -> str:
165
+ """The public ID of an agent key."""
166
+ return AgentKey.from_secret(secret).address
167
+
168
+
169
+ def load_key(key: Optional[str] = None) -> AgentKey:
170
+ """The agent key: the argument, ACCORD_AGENT_KEY, or ./.env (as written by ``accord init``)."""
171
+ from .settings import setting
172
+
173
+ k = key or setting("ACCORD_AGENT_KEY")
174
+ if not k:
175
+ raise AccordError("missing_key", "Pass key, set ACCORD_AGENT_KEY, or run: npx @getaccord/cli init")
176
+ return AgentKey.from_secret(k)
getaccord/money.py ADDED
@@ -0,0 +1,62 @@
1
+ """Exact money: whole cents, or micros (millionths of a dollar). Never floats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Dict, Optional, Union
7
+
8
+ from .errors import AccordError
9
+
10
+ MICROS_PER_CENT = 10_000
11
+ MICROS_PER_DOLLAR = 1_000_000
12
+
13
+
14
+ def _int(value: object, what: str) -> int:
15
+ # bool is an int in Python; a float would lose cents. Both are refused.
16
+ if isinstance(value, bool) or not isinstance(value, int):
17
+ raise AccordError("invalid_amount", f"{what} must be a whole number (int), not {type(value).__name__}.")
18
+ if value < 0:
19
+ raise AccordError("invalid_amount", f"{what} can't be negative.")
20
+ return value
21
+
22
+
23
+ def amount_field(field: str, cents: Optional[int], micros: Optional[Union[int, str]]) -> Dict[str, Union[int, str]]:
24
+ """``{field: cents}`` or ``{fieldMicros: "micros"}``: exactly one of the two."""
25
+ if (cents is None) == (micros is None):
26
+ raise AccordError("invalid_amount", f"Give {field} (cents) or {field}_micros, one of the two.")
27
+ if micros is not None:
28
+ m = int(micros) if isinstance(micros, str) and micros.isdigit() else _int(micros, f"{field}_micros")
29
+ return {f"{field}Micros": str(m)}
30
+ return {field: _int(cents, field)}
31
+
32
+
33
+ def to_micros(cents: Optional[int], micros: Optional[Union[int, str]]) -> int:
34
+ if micros is not None:
35
+ return int(micros)
36
+ return _int(cents, "amount") * MICROS_PER_CENT
37
+
38
+
39
+ def usd(micros: Union[int, str]) -> str:
40
+ """Exact dollars for people: "$0.0001", "$12.50", "$1,234.00"."""
41
+ m = int(micros)
42
+ frac = str(m % MICROS_PER_DOLLAR).rjust(6, "0").rstrip("0")
43
+ if len(frac) < 2:
44
+ frac = frac.ljust(2, "0")
45
+ return f"${m // MICROS_PER_DOLLAR:,}.{frac}"
46
+
47
+
48
+ def micros(dollars: str) -> int:
49
+ """ "0.0001", "$12.50" -> micros (exact; up to 6 decimals)."""
50
+ m = re.fullmatch(r"\$?(\d+)(?:\.(\d{1,6}))?", dollars.strip().replace(",", ""))
51
+ if not m:
52
+ raise AccordError("invalid_amount", f'"{dollars}" is not a dollar amount (up to 6 decimals).')
53
+ return int(m.group(1)) * MICROS_PER_DOLLAR + int((m.group(2) or "").ljust(6, "0"))
54
+
55
+
56
+ def duration_ms(s: str) -> int:
57
+ """ "15m", "60s", "500ms", "2h" -> milliseconds."""
58
+ m = re.fullmatch(r"(\d+)(ms|s|m|h)", s.strip())
59
+ if not m:
60
+ raise AccordError("invalid_duration", s)
61
+ n, unit = int(m.group(1)), m.group(2)
62
+ return n * {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000}[unit]
getaccord/py.typed ADDED
File without changes
getaccord/seller.py ADDED
@@ -0,0 +1,106 @@
1
+ """Seller side: check Accord's signed webhooks and answer them.
2
+
3
+ Framework-free core: ``Handler.handle(raw_body, headers) -> (status, json_body)``. Wire it into Flask,
4
+ FastAPI or anything else with a few lines (see the README). Always give it the raw request body.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import hmac
11
+ import json
12
+ import os
13
+ import time
14
+ from typing import Any, Callable, Dict, Iterable, Mapping, Optional, Tuple, Union
15
+
16
+ SIGNATURE_HEADER = "accord-signature"
17
+
18
+ Answer = Union[Dict[str, Any], bool]
19
+
20
+
21
+ def verify_signature(raw_body: Union[bytes, str], header: Optional[str], secrets: Union[str, Iterable[str]], tolerance_seconds: int = 300, now: Optional[float] = None) -> bool:
22
+ """``Accord-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "t.body">``. Several secrets work during a rotation;
23
+ anything older (or newer) than ``tolerance_seconds`` is refused, so a captured event can't be replayed later."""
24
+ if not header:
25
+ return False
26
+ parts = [p.strip().split("=", 1) for p in header.split(",")]
27
+ t = next((v for k, *rest in parts for v in rest if k == "t"), None)
28
+ try:
29
+ ts = int(t) if t is not None else None
30
+ except ValueError:
31
+ return False
32
+ if ts is None or abs((now if now is not None else time.time()) - ts) > tolerance_seconds:
33
+ return False
34
+ given = []
35
+ for k, *rest in parts:
36
+ if k == "v1" and rest:
37
+ try:
38
+ given.append(bytes.fromhex(rest[0]))
39
+ except ValueError:
40
+ pass
41
+ body = raw_body if isinstance(raw_body, bytes) else raw_body.encode("utf-8")
42
+ for secret in [secrets] if isinstance(secrets, str) else list(secrets):
43
+ expected = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).digest()
44
+ if any(hmac.compare_digest(g, expected) for g in given):
45
+ return True
46
+ return False
47
+
48
+
49
+ class Handler:
50
+ """Answers Accord's webhooks.
51
+
52
+ on_hold(event) -> True (ready), False (declined) or {"ready": True} / {"declined": "why"}
53
+ on_work(event) -> {"result": "..."} or {"declined": "why"} (deliver holds)
54
+ on_commit(event), on_abort(event), on_key_rotated(event) (no answer needed)
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ on_hold: Optional[Callable[[Dict[str, Any]], Answer]] = None,
60
+ on_work: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
61
+ on_commit: Optional[Callable[[Dict[str, Any]], None]] = None,
62
+ on_abort: Optional[Callable[[Dict[str, Any]], None]] = None,
63
+ on_key_rotated: Optional[Callable[[Dict[str, Any]], None]] = None,
64
+ secret: Optional[Union[str, Iterable[str]]] = None,
65
+ tolerance_seconds: int = 300,
66
+ verify: bool = True,
67
+ ):
68
+ self.on_hold, self.on_work, self.on_commit, self.on_abort, self.on_key_rotated = on_hold, on_work, on_commit, on_abort, on_key_rotated
69
+ self.secret = secret if secret is not None else os.environ.get("ACCORD_WEBHOOK_SECRET")
70
+ if verify and not self.secret:
71
+ raise ValueError("Set ACCORD_WEBHOOK_SECRET (the whsec_... from seller sign-up) or pass secret=. Unsigned events are refused.")
72
+ self.verify = verify
73
+ self.tolerance_seconds = tolerance_seconds
74
+ self._seen: Dict[str, Any] = {}
75
+
76
+ def handle(self, raw_body: Union[bytes, str], headers: Mapping[str, str]) -> Tuple[int, Dict[str, Any]]:
77
+ """Returns (HTTP status, JSON body) to send back."""
78
+ try:
79
+ header = next((v for k, v in headers.items() if k.lower() == SIGNATURE_HEADER), None)
80
+ if self.verify and not verify_signature(raw_body, header, self.secret, self.tolerance_seconds): # type: ignore[arg-type]
81
+ return 401, {"error": "bad or stale signature"}
82
+ event = json.loads(raw_body)
83
+ if event.get("eventId") in self._seen:
84
+ return 200, self._seen[event["eventId"]]
85
+ answer: Dict[str, Any] = {}
86
+ kind = str(event.get("type"))
87
+ if kind == "seller.ping":
88
+ answer = {"ok": True}
89
+ elif kind == "key.rotated":
90
+ if self.on_key_rotated:
91
+ self.on_key_rotated(event)
92
+ elif kind == "hold.placed" and event.get("holdType") == "deliver":
93
+ answer = self.on_work(event) if self.on_work else {"declined": "this seller does not take deliver holds"}
94
+ elif kind == "hold.placed":
95
+ out = self.on_hold(event) if self.on_hold else {"declined": "this seller does not take reserve holds"}
96
+ answer = {"ready": True} if out is True else {"declined": "declined"} if out is False else out
97
+ elif kind == "intent.committed" and event.get("paid"):
98
+ if self.on_commit:
99
+ self.on_commit(event)
100
+ elif kind.startswith("intent."):
101
+ if self.on_abort:
102
+ self.on_abort(event)
103
+ self._seen[event.get("eventId")] = answer
104
+ return 200, answer
105
+ except Exception as e: # a handler error is the seller's 500, not a crash
106
+ return 500, {"error": str(e)}
getaccord/settings.py ADDED
@@ -0,0 +1,27 @@
1
+ """ACCORD_* settings: the environment first, then ./.env as written by ``accord init``.
2
+
3
+ Only ACCORD_* lines are read from .env, and os.environ is not changed (like the TypeScript SDK).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ from typing import Optional
10
+
11
+ DEFAULT_URL = "https://api.useaccord.ai"
12
+
13
+
14
+ def setting(name: str, env_file: str = ".env") -> Optional[str]:
15
+ if os.environ.get(name):
16
+ return os.environ[name]
17
+ try:
18
+ with open(env_file, encoding="utf-8") as f:
19
+ for line in f:
20
+ if line.startswith(f"{name}="):
21
+ value = line[len(name) + 1 :].strip()
22
+ if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
23
+ value = value[1:-1]
24
+ return value or None
25
+ except OSError:
26
+ return None
27
+ return None
getaccord/x402.py ADDED
@@ -0,0 +1,237 @@
1
+ """Paying for URLs that answer 402 Payment Required (x402), through Accord.
2
+
3
+ Buyer: quote(url) -> Offer; hold(intent, offer); intent.commit(); fetch_paid(...) — or pay(url) for one seller.
4
+ Seller: accord_requirement(pay_to=..., usd_cents=...) for your 402; verify_accord_payment(header, expected).
5
+
6
+ The proof the agent key signs is built byte-for-byte like the TypeScript SDK's (``proof_message``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import json
13
+ import os
14
+ import urllib.error
15
+ import urllib.request
16
+ from dataclasses import dataclass
17
+ from typing import Any, Dict, List, Mapping, Optional
18
+
19
+ from .client import Accord, Intent
20
+ from .errors import AccordError
21
+ from .keys import load_key
22
+ from .settings import DEFAULT_URL, setting
23
+
24
+ X402_SCHEME = "accord"
25
+ X402_VERSION = 2
26
+
27
+
28
+ @dataclass
29
+ class Response:
30
+ status: int
31
+ headers: Dict[str, str]
32
+ body: bytes
33
+
34
+ def json(self) -> Any:
35
+ return json.loads(self.body)
36
+
37
+ @property
38
+ def text(self) -> str:
39
+ return self.body.decode("utf-8", "replace")
40
+
41
+
42
+ def _fetch(url: str, method: str = "GET", headers: Optional[Mapping[str, str]] = None, body: Optional[bytes] = None) -> Response:
43
+ req = urllib.request.Request(url, data=body, method=method, headers={"user-agent": "getaccord-python/0.6.0", **(headers or {})})
44
+ try:
45
+ with urllib.request.urlopen(req, timeout=60) as res:
46
+ return Response(res.status, {k.lower(): v for k, v in res.headers.items()}, res.read())
47
+ except urllib.error.HTTPError as e:
48
+ return Response(e.code, {k.lower(): v for k, v in e.headers.items()}, e.read())
49
+ except urllib.error.URLError as e:
50
+ raise AccordError("network_error", f"Couldn't reach {url}: {e.reason}") from None
51
+
52
+
53
+ def _compact(value: Any) -> str:
54
+ """JSON exactly as JavaScript's JSON.stringify writes it (no spaces, keys in order, non-ASCII as is)."""
55
+ return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
56
+
57
+
58
+ def facilitator_url(service: Optional[str] = None) -> str:
59
+ return f"{(service or setting('ACCORD_URL') or DEFAULT_URL).rstrip('/')}/x402"
60
+
61
+
62
+ @dataclass
63
+ class OfferHold:
64
+ seller: str
65
+ """``x402:<payTo>``."""
66
+ micros: int
67
+ cents: int
68
+ """Rounded up, for display."""
69
+
70
+
71
+ @dataclass
72
+ class Offer:
73
+ url: str
74
+ requirements: Dict[str, Any]
75
+ payment_required: Dict[str, Any]
76
+ holds: List[OfferHold]
77
+ micros: int
78
+ cents: int
79
+ coin: str
80
+
81
+
82
+ def _outputs(r: Mapping[str, Any]) -> List[Dict[str, str]]:
83
+ outs = (r.get("extra") or {}).get("outputs")
84
+ if isinstance(outs, list) and outs:
85
+ return [{"payTo": str(o["payTo"]), "amount": str(o["amount"])} for o in outs]
86
+ return [{"payTo": r["payTo"], "amount": r["amount"]}]
87
+
88
+
89
+ def _payment_required(res: Response) -> Optional[Dict[str, Any]]:
90
+ header = res.headers.get("payment-required")
91
+ if header:
92
+ try:
93
+ return json.loads(base64.b64decode(header))
94
+ except ValueError:
95
+ pass
96
+ try:
97
+ body = json.loads(res.body)
98
+ if isinstance(body, dict) and isinstance(body.get("accepts"), list):
99
+ return body
100
+ except ValueError:
101
+ pass
102
+ return None
103
+
104
+
105
+ def quote(url: str, headers: Optional[Mapping[str, str]] = None) -> Optional[Offer]:
106
+ """Asks a URL what it costs. None if it didn't ask for payment. Raises x402_no_accord_option if its 402
107
+ has no Accord option: nothing is paid."""
108
+ res = _fetch(url, headers=headers)
109
+ if res.status != 402:
110
+ return None
111
+ pr = _payment_required(res)
112
+ req = next((a for a in (pr or {}).get("accepts", []) if a.get("scheme") == X402_SCHEME), None)
113
+ if not pr or not req:
114
+ offered = ", ".join(a.get("scheme", "?") for a in (pr or {}).get("accepts", [])) or "none"
115
+ raise AccordError(
116
+ "x402_no_accord_option",
117
+ f"This seller doesn't accept Accord payments (its 402 offers: {offered}). Nothing was paid; "
118
+ "Accord never pays with another scheme from your own funds.",
119
+ )
120
+ decimals = int((req.get("extra") or {}).get("decimals", 6))
121
+ if decimals != 6:
122
+ raise AccordError(
123
+ "x402_unsupported_asset",
124
+ f"This seller asks for a coin with {decimals} decimals; Accord pays in 6-decimal dollar coins only. Nothing was paid.",
125
+ )
126
+ holds = [OfferHold(f"x402:{o['payTo']}", int(o["amount"]), (int(o["amount"]) + 9_999) // 10_000) for o in _outputs(req)]
127
+ return Offer(url, req, pr, holds, sum(h.micros for h in holds), sum(h.cents for h in holds), str(req["asset"]))
128
+
129
+
130
+ def hold(intent: Intent, offer: Offer) -> List[int]:
131
+ """Places this offer's holds in your intent (one step). Returns their hold indexes."""
132
+ placed = intent.holds([{"seller": h.seller, "amount_micros": h.micros, "ref": offer.url} for h in offer.holds])
133
+ return [p.index for p in placed]
134
+
135
+
136
+ def proof_message(intent_id: str, digest: str, indexes: List[int], resource: str, nonce: str, accepted: Mapping[str, Any]) -> bytes:
137
+ """The bytes the agent key signs (as a Sui personal message). Identical to the TypeScript SDK's."""
138
+ acc = {
139
+ "scheme": accepted["scheme"],
140
+ "network": accepted["network"],
141
+ "asset": accepted["asset"],
142
+ "amount": accepted["amount"],
143
+ "payTo": accepted["payTo"],
144
+ "outputs": (accepted.get("extra") or {}).get("outputs"),
145
+ }
146
+ payload = {"intentId": intent_id, "digest": digest, "indexes": list(indexes), "resource": resource, "nonce": nonce, "accepted": acc}
147
+ return ("accord-x402-proof:" + _compact(payload)).encode("utf-8")
148
+
149
+
150
+ def payment_header(offer: Offer, intent_id: str, digest: str, indexes: List[int], key: Optional[str] = None, nonce: Optional[str] = None) -> str:
151
+ """The PAYMENT-SIGNATURE header value: the commit's facts and a proof signed by the agent key."""
152
+ n = nonce or os.urandom(16).hex()
153
+ signature = load_key(key).sign_personal_message(proof_message(intent_id, digest, indexes, offer.url, n, offer.requirements))
154
+ payload = {
155
+ "x402Version": X402_VERSION,
156
+ "resource": offer.payment_required.get("resource") or {"url": offer.url},
157
+ "accepted": offer.requirements,
158
+ "payload": {"intentId": intent_id, "digest": digest, "indexes": list(indexes), "resource": offer.url, "nonce": n, "signature": signature},
159
+ }
160
+ return base64.b64encode(_compact(payload).encode("utf-8")).decode()
161
+
162
+
163
+ def fetch_paid(offer: Offer, intent_id: str, digest: str, indexes: List[int], headers: Optional[Mapping[str, str]] = None, key: Optional[str] = None) -> Response:
164
+ """After the intent committed: fetches the resource with the payment proof."""
165
+ return _fetch(offer.url, headers={**(headers or {}), "PAYMENT-SIGNATURE": payment_header(offer, intent_id, digest, indexes, key)})
166
+
167
+
168
+ def pay(url: str, key: Optional[str] = None, accord: Optional[Accord] = None, headers: Optional[Mapping[str, str]] = None) -> Response:
169
+ """Pays an x402 URL through Accord on its own (one seller) and returns the response."""
170
+ a = accord or Accord()
171
+ offer = quote(url, headers)
172
+ if offer is None:
173
+ return _fetch(url, headers=headers)
174
+ intent = a.intent(budget_micros=offer.micros, coin=offer.coin, key=key)
175
+ indexes = hold(intent, offer)
176
+ result = intent.commit()
177
+ if result.status != "committed" or not result.digest:
178
+ raise AccordError("x402_not_paid", f"Not paid ({result.status}{': ' + result.reason if result.reason else ''}).")
179
+ return fetch_paid(offer, intent.id or "", result.digest, indexes, headers, key)
180
+
181
+
182
+ # --- Seller side ---
183
+
184
+
185
+ def accord_terms(facilitator: Optional[str] = None) -> Dict[str, Any]:
186
+ """What the facilitator settles in: network, asset, decimals."""
187
+ f = facilitator or facilitator_url()
188
+ res = _fetch(f"{f}/supported")
189
+ if res.status != 200:
190
+ raise AccordError("facilitator_unreachable", f"{f}/supported answered {res.status}")
191
+ kind = next((k for k in res.json().get("kinds", []) if k.get("scheme") == X402_SCHEME), None)
192
+ if not kind:
193
+ raise AccordError("facilitator_unsupported", f'{f} does not settle the "{X402_SCHEME}" scheme.')
194
+ extra = kind.get("extra") or {}
195
+ return {"network": kind["network"], "asset": str(extra.get("asset")), "decimals": int(extra.get("decimals", 6)), "facilitator": f}
196
+
197
+
198
+ def accord_requirement(pay_to: str, usd_cents: Optional[int] = None, amount: Optional[str] = None, max_timeout_seconds: int = 300, facilitator: Optional[str] = None) -> Dict[str, Any]:
199
+ """The entry to add to your 402's ``accepts``. Price in whole cents (``usd_cents``) or atomic units (``amount``)."""
200
+ t = accord_terms(facilitator)
201
+ if amount is None:
202
+ if usd_cents is None or isinstance(usd_cents, bool) or not isinstance(usd_cents, int):
203
+ raise AccordError("invalid_price", "Give the price as usd_cents (int) or amount.")
204
+ amount = str(usd_cents * 10 ** (t["decimals"] - 2))
205
+ return {
206
+ "scheme": X402_SCHEME,
207
+ "network": t["network"],
208
+ "asset": t["asset"],
209
+ "amount": amount,
210
+ "payTo": pay_to,
211
+ "maxTimeoutSeconds": max_timeout_seconds,
212
+ "extra": {"facilitator": t["facilitator"], "decimals": t["decimals"]},
213
+ }
214
+
215
+
216
+ def verify_accord_payment(payment_header_value: Optional[str], expected: Mapping[str, Any], resource: Optional[str] = None, facilitator: Optional[str] = None) -> Dict[str, Any]:
217
+ """Checks a buyer's PAYMENT-SIGNATURE against what you asked for, then settles it so it pays for this request only.
218
+ Serve the request only when the result's ``ok`` is True."""
219
+ if not payment_header_value:
220
+ return {"ok": False, "reason": "missing_payment"}
221
+ try:
222
+ payload = json.loads(base64.b64decode(payment_header_value))
223
+ except ValueError:
224
+ return {"ok": False, "reason": "invalid_payload", "message": "The payment header is not base64 JSON."}
225
+ if (payload.get("accepted") or {}).get("scheme") != X402_SCHEME:
226
+ return {"ok": False, "reason": "invalid_scheme"}
227
+ if resource and (payload.get("payload") or {}).get("resource") != resource:
228
+ return {"ok": False, "reason": "wrong_resource", "message": "That payment was made for a different URL."}
229
+ f = facilitator or str((expected.get("extra") or {}).get("facilitator") or facilitator_url())
230
+ body = _compact({"x402Version": X402_VERSION, "paymentPayload": payload, "paymentRequirements": dict(expected)}).encode()
231
+ v = _fetch(f"{f}/verify", "POST", {"content-type": "application/json"}, body).json()
232
+ if not v.get("isValid"):
233
+ return {"ok": False, "reason": v.get("invalidReason", "invalid"), "message": v.get("invalidMessage")}
234
+ s = _fetch(f"{f}/settle", "POST", {"content-type": "application/json"}, body).json()
235
+ if not s.get("success"):
236
+ return {"ok": False, "reason": s.get("errorReason", "settle_failed"), "message": s.get("errorMessage")}
237
+ return {"ok": True, "digest": s.get("transaction"), "payer": s.get("payer")}
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.5
2
+ Name: getaccord
3
+ Version: 0.6.0
4
+ Summary: Let AI agents spend within limits you set: holds, sign-off and exact payments, enforced on chain.
5
+ Project-URL: Homepage, https://useaccord.ai
6
+ Author: Accord
7
+ License-Expression: Apache-2.0
8
+ Keywords: ai agents,payments,sui,x402
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Typing :: Typed
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: cryptography>=42
14
+ Provides-Extra: dev
15
+ Requires-Dist: pytest>=8; extra == 'dev'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # getaccord (Python)
19
+
20
+ Let AI agents spend within limits you set. An agent holds money with sellers, then pays everyone at once or no one; the limits are enforced on chain. The same API as [`@getaccord/sdk`](https://www.npmjs.com/package/@getaccord/sdk), for Python 3.9+.
21
+
22
+ Test mode: test dollars only.
23
+
24
+ ## Quickstart
25
+
26
+ 1. Make an agent key in your project folder. It's created on your machine and never leaves it:
27
+
28
+ ```bash
29
+ npx @getaccord/cli init
30
+ ```
31
+
32
+ This writes `ACCORD_AGENT_KEY` to `.env`, which the Python SDK reads as is.
33
+
34
+ 2. Install:
35
+
36
+ ```bash
37
+ pip install getaccord
38
+ ```
39
+
40
+ 3. Buy something: hold money with each seller, then commit.
41
+
42
+ ```python
43
+ from getaccord import Accord
44
+
45
+ accord = Accord() # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
46
+ intent = accord.intent(budget=4500) # whole cents; budget_micros= for exact sub-cent amounts
47
+ intent.hold("skyfare", 3000, ref="SFO to JFK")
48
+ intent.hold("stayco", 1500, ref="2 nights")
49
+ result = intent.commit() # everyone is paid, or no one is
50
+ print(result.status, result.intent["proofUrl"])
51
+ ```
52
+
53
+ Amounts are whole cents (`int`) or exact micros (`amount_micros=`, millionths of a dollar). Floats are refused, so no amount is ever rounded.
54
+
55
+ ## Buying
56
+
57
+ | | |
58
+ |---|---|
59
+ | `accord.intent(budget, *, budget_micros, coin, mode, expires_in, key)` | Opens a purchase. `coin`: the usual dollar coin or `"USDC"`. `mode`: `"all"` (everyone or no one) or `"each"`. |
60
+ | `intent.hold(seller, amount, *, amount_micros, ref, type)` | Locks money with one seller. `type`: `"reserve"` or `"deliver"`. |
61
+ | `intent.holds([...])` | Several holds in one step (one transaction). |
62
+ | `intent.commit(wait="60s")` | Waits for every seller to confirm, then pays them all. In `"all"` mode a decline or timeout releases everything. |
63
+ | `intent.abort()` | Calls it off; every held dollar comes back. |
64
+ | `intent.results()`, `intent.accept(i)`, `intent.reject(i)` | Deliver holds: check the work before anyone is paid. |
65
+ | `accord.balance()` | What's available, and what's left of the key's weekly budget. |
66
+
67
+ Errors are `AccordError` with a stable `.code` (`limit_exceeded`, `seller_not_allowed`, `insufficient_balance`, `awaiting_approval`, `too_many_holds`, ...) and a message that says what to do.
68
+
69
+ A purchase over the key's sign-off limit waits for a person: `hold()` raises `awaiting_approval` and no money is locked. In test mode, `accord.test.approve(intent.id)` approves it as the owner would.
70
+
71
+ Async: `AsyncAccord` has the same methods, awaitable.
72
+
73
+ ```python
74
+ from getaccord import AsyncAccord
75
+
76
+ accord = AsyncAccord()
77
+ intent = await accord.intent(budget=4500)
78
+ await intent.hold("skyfare", 3000)
79
+ result = await intent.commit()
80
+ ```
81
+
82
+ ## Paying x402 sellers
83
+
84
+ Sellers that charge per request with [x402](https://www.x402.org) can add an Accord option to their 402.
85
+
86
+ ```python
87
+ from getaccord.x402 import pay
88
+
89
+ response = pay("https://seller.example/report") # quote, hold, commit, fetch with the proof
90
+ print(response.status, response.json())
91
+ ```
92
+
93
+ Several sellers in one purchase: `quote(url)`, `hold(intent, offer)` for each, `intent.commit()`, then `fetch_paid(offer, intent.id, result.digest, indexes)`.
94
+
95
+ Selling with x402: add `accord_requirement(pay_to=..., usd_cents=25)` to your 402's `accepts`, then check each paid request with `verify_accord_payment(header, requirement, resource=url)`. See `examples/x402_gateway.py`.
96
+
97
+ ## Selling (webhooks)
98
+
99
+ Accord tells your server about each hold with a signed webhook. Answer whether you can deliver:
100
+
101
+ ```python
102
+ from getaccord import Handler
103
+
104
+ handler = Handler(
105
+ on_hold=lambda event: True, # ready (or False, or {"declined": "why"})
106
+ on_commit=lambda event: print("paid", event["intentId"]),
107
+ ) # reads ACCORD_WEBHOOK_SECRET
108
+
109
+ # Flask
110
+ @app.post("/accord")
111
+ def accord_webhook():
112
+ status, body = handler.handle(request.get_data(), request.headers)
113
+ return body, status
114
+ ```
115
+
116
+ `handle()` checks the `Accord-Signature` header (HMAC-SHA256, a 5-minute window against replays, old and new secrets during a rotation) and answers each event once. Give it the raw request body. `verify_signature(raw, header, secret)` is there on its own too.
117
+
118
+ ## Examples
119
+
120
+ - `examples/trip_booker.py`: a flight, a hotel and a car, all paid or none (`--fail ridenow` to see a decline release everything).
121
+ - `examples/seller_webhook.py`: a seller answering webhooks with no framework.
122
+ - `examples/x402_gateway.py`: an x402 gateway paid through Accord.
123
+
124
+ ## Tests
125
+
126
+ ```bash
127
+ pip install -e '.[dev]'
128
+ pytest # unit tests
129
+ ACCORD_LIVE=1 ACCORD_URL=https://api.useaccord.ai pytest # plus a live test-mode purchase
130
+ ```
131
+
132
+ Signatures are checked byte-for-byte against the TypeScript SDK's.
133
+
134
+ ## License
135
+
136
+ Apache-2.0
@@ -0,0 +1,13 @@
1
+ getaccord/__init__.py,sha256=HBnzFyLdGPJJURCbiN5uOHqex9YkG1wDkJ3Pg1je5ps,1034
2
+ getaccord/aio.py,sha256=VoI66OTDYz2_ppKN45p-JH0CPr5gHMm3WO2XD7Unke4,1307
3
+ getaccord/client.py,sha256=SFR3j4BcJM-Tephj6ttQ4kf00mzt2vh_sEtpj1rk1-I,16307
4
+ getaccord/errors.py,sha256=Ush0J23EPNW9v-R3H4QQX-G18uuyeRE5bTLK3w8bkHc,540
5
+ getaccord/keys.py,sha256=cyY6m8vT8vePpyUyIWVzVb_VY5OwobS_Y-xEF57xBd8,6149
6
+ getaccord/money.py,sha256=Uv3atQRpznNylSO_TAVvBdE2Vo6GjVaUPDXR1SgbLtw,2429
7
+ getaccord/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ getaccord/seller.py,sha256=EbW0b8V5d274-l56_YcyOMLeDhE3quDz1o1KOv03oTo,5138
9
+ getaccord/settings.py,sha256=3efN-OCRE1OgkiTAZWtNYLkVWWPzSy0Cbo4TdWBz13c,858
10
+ getaccord/x402.py,sha256=V1kkOxb3Mqv_-bjbMSLmIXY1AQZ6DbMNrsmHnX1bG_4,10907
11
+ getaccord-0.6.0.dist-info/METADATA,sha256=JDJbbR_XAB80NDD_94hntFNZ-L7lJVpW5EU0ZjQS3J4,5432
12
+ getaccord-0.6.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
13
+ getaccord-0.6.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any