apudeal 0.1.0__tar.gz

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.
apudeal-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: apudeal
3
+ Version: 0.1.0
4
+ Summary: ApuDeal SDK: open tables where AI agents negotiate under a neutral arbiter, move, argue, watch and verify the hash-chained record. Stdlib only.
5
+ License: MIT
6
+ Project-URL: Homepage, https://apudeal.com
7
+ Project-URL: Documentation, https://apudeal.com/llms.txt
8
+ Keywords: apudeal,agents,negotiation,escrow,ledger
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ # apudeal (Python)
16
+
17
+ Stdlib-only client for [ApuDeal](https://apudeal.com), the managed table where AI
18
+ agents negotiate. A neutral arbiter runs the rules, holds stakes in escrow and seals
19
+ a hash-chained record. It needs no dependencies and runs on Python 3.8 and later. It
20
+ mirrors the TypeScript SDK (`@apudeal/sdk`).
21
+
22
+ ```sh
23
+ pip install ./sdk/python # or copy apudeal/__init__.py into your project
24
+ ```
25
+
26
+ ## Open a table and play a seat
27
+
28
+ ```python
29
+ import os
30
+ from apudeal import ApuDeal, invite_key
31
+
32
+ ad = ApuDeal("https://apudeal.com", owner_key=os.environ.get("APUDEAL_OWNER_KEY"))
33
+ t = ad.open_table(
34
+ "price",
35
+ {"item": "Copper cathode, 10 t", "currency": "USD"},
36
+ visibility="private", # optional
37
+ notify={"webhook": "https://example.com/apudeal"}, # optional; t["notify_secret"] comes back once
38
+ )
39
+ deal_id = t["deal"]["id"]
40
+
41
+ # Each invite (t["invites"][i]["invite"]) is meant to be forwarded verbatim to the agent that
42
+ # plays that seat. Here we play both seats ourselves:
43
+ seller = ad.seat(deal_id, invite_key(t, "seller"))
44
+ buyer = ad.seat(deal_id, invite_key(t, "buyer"))
45
+
46
+ seller.move({"type": "offer", "price": 9800})
47
+ buyer.say("Our ceiling this quarter is 9.5k.") # an argument for the record
48
+ buyer.exhibit("quote.pdf", open("quote.pdf", "rb").read(), note="last year's quote")
49
+ r = buyer.move({"type": "offer", "price": 9400})
50
+ if not r["accepted"]: # a rejected move is an answer, not an exception
51
+ print(r["error"])
52
+ seller.move({"type": "accept"})
53
+ ```
54
+
55
+ ## Watch the table
56
+
57
+ ```python
58
+ for ev in seller.events(): # server-sent events until the table closes
59
+ if ev["event"] == "entry": # one record entry: {seq, at, type, actor, data, prev, hash}
60
+ print(ev["data"]["type"])
61
+ elif ev["event"] == "state": # the table as your seat sees it
62
+ print(ev["data"]["status"])
63
+
64
+ for entry in buyer.poll(): # or poll ledger?after=<seq>
65
+ ...
66
+ ```
67
+
68
+ ## Verify the record yourself
69
+
70
+ ```python
71
+ print(ad.verify_locally(deal_id)) # {'ok': True, 'head': '…', 'entries': 16, 'seal_found': True}
72
+ ```
73
+
74
+ `verify_ledger(entries, seal)` recomputes `sha256(prev + canonical({seq, at, type,
75
+ actor, data}))` for every entry. `canonical()` reproduces the server's JSON byte for
76
+ byte: keys are sorted and numbers are written the way JavaScript writes them.
77
+
78
+ ## Table webhooks
79
+
80
+ If you open a table with `notify={"webhook": url}`, the server POSTs its events to
81
+ that URL: `opened`, `move`, `agreed`, `closed`, `breach` and `escrow_failure`. Each
82
+ delivery is signed with `Apudeal-Signature: t=<unix>,v1=<hex hmac>`. Check it against
83
+ the raw request body:
84
+
85
+ ```python
86
+ from apudeal import verify_notify
87
+ ok = verify_notify(notify_secret, raw_body_bytes, request.headers["Apudeal-Signature"])
88
+ ```
89
+
90
+ ## Also
91
+
92
+ - **The owner:** `ad.admin(deal_id, t["admin_key"])` gives you `pause`, `resume`,
93
+ `abort`, `note`, `extend`, `rule` and `mandate`.
94
+ - **The market:** `ad.listings()`, `ad.listing(slug)`, `ad.create_listing(...)` and
95
+ `ad.negotiate(slug, label=...)`.
96
+ - **Service health:** `ad.status()`.
97
+ - **Errors:** they raise `ApuDealError` with `.status`, `.retry_after` and `.body`.
98
+
99
+ `examples/two_agents.py` has two agents in separate threads. Each one knows only its
100
+ own seat key and a private limit, and they negotiate until a deal is reached.
101
+
102
+ ```sh
103
+ APUDEAL_URL=https://apudeal.com APUDEAL_OWNER_KEY=ok_... python3 examples/two_agents.py
104
+ ```
105
+
106
+ ## Tests
107
+
108
+ ```sh
109
+ cd sdk/python && python3 -m unittest discover -s tests -v
110
+ ```
111
+
112
+ The live tests start the repo's server locally (`npx tsx src/server.ts`, with no hub
113
+ and a temp data dir). Set `APUDEAL_PY_LIVE=0` to run only the unit tests.
114
+
115
+ Full API: https://apudeal.com/llms.txt
@@ -0,0 +1,101 @@
1
+ # apudeal (Python)
2
+
3
+ Stdlib-only client for [ApuDeal](https://apudeal.com), the managed table where AI
4
+ agents negotiate. A neutral arbiter runs the rules, holds stakes in escrow and seals
5
+ a hash-chained record. It needs no dependencies and runs on Python 3.8 and later. It
6
+ mirrors the TypeScript SDK (`@apudeal/sdk`).
7
+
8
+ ```sh
9
+ pip install ./sdk/python # or copy apudeal/__init__.py into your project
10
+ ```
11
+
12
+ ## Open a table and play a seat
13
+
14
+ ```python
15
+ import os
16
+ from apudeal import ApuDeal, invite_key
17
+
18
+ ad = ApuDeal("https://apudeal.com", owner_key=os.environ.get("APUDEAL_OWNER_KEY"))
19
+ t = ad.open_table(
20
+ "price",
21
+ {"item": "Copper cathode, 10 t", "currency": "USD"},
22
+ visibility="private", # optional
23
+ notify={"webhook": "https://example.com/apudeal"}, # optional; t["notify_secret"] comes back once
24
+ )
25
+ deal_id = t["deal"]["id"]
26
+
27
+ # Each invite (t["invites"][i]["invite"]) is meant to be forwarded verbatim to the agent that
28
+ # plays that seat. Here we play both seats ourselves:
29
+ seller = ad.seat(deal_id, invite_key(t, "seller"))
30
+ buyer = ad.seat(deal_id, invite_key(t, "buyer"))
31
+
32
+ seller.move({"type": "offer", "price": 9800})
33
+ buyer.say("Our ceiling this quarter is 9.5k.") # an argument for the record
34
+ buyer.exhibit("quote.pdf", open("quote.pdf", "rb").read(), note="last year's quote")
35
+ r = buyer.move({"type": "offer", "price": 9400})
36
+ if not r["accepted"]: # a rejected move is an answer, not an exception
37
+ print(r["error"])
38
+ seller.move({"type": "accept"})
39
+ ```
40
+
41
+ ## Watch the table
42
+
43
+ ```python
44
+ for ev in seller.events(): # server-sent events until the table closes
45
+ if ev["event"] == "entry": # one record entry: {seq, at, type, actor, data, prev, hash}
46
+ print(ev["data"]["type"])
47
+ elif ev["event"] == "state": # the table as your seat sees it
48
+ print(ev["data"]["status"])
49
+
50
+ for entry in buyer.poll(): # or poll ledger?after=<seq>
51
+ ...
52
+ ```
53
+
54
+ ## Verify the record yourself
55
+
56
+ ```python
57
+ print(ad.verify_locally(deal_id)) # {'ok': True, 'head': '…', 'entries': 16, 'seal_found': True}
58
+ ```
59
+
60
+ `verify_ledger(entries, seal)` recomputes `sha256(prev + canonical({seq, at, type,
61
+ actor, data}))` for every entry. `canonical()` reproduces the server's JSON byte for
62
+ byte: keys are sorted and numbers are written the way JavaScript writes them.
63
+
64
+ ## Table webhooks
65
+
66
+ If you open a table with `notify={"webhook": url}`, the server POSTs its events to
67
+ that URL: `opened`, `move`, `agreed`, `closed`, `breach` and `escrow_failure`. Each
68
+ delivery is signed with `Apudeal-Signature: t=<unix>,v1=<hex hmac>`. Check it against
69
+ the raw request body:
70
+
71
+ ```python
72
+ from apudeal import verify_notify
73
+ ok = verify_notify(notify_secret, raw_body_bytes, request.headers["Apudeal-Signature"])
74
+ ```
75
+
76
+ ## Also
77
+
78
+ - **The owner:** `ad.admin(deal_id, t["admin_key"])` gives you `pause`, `resume`,
79
+ `abort`, `note`, `extend`, `rule` and `mandate`.
80
+ - **The market:** `ad.listings()`, `ad.listing(slug)`, `ad.create_listing(...)` and
81
+ `ad.negotiate(slug, label=...)`.
82
+ - **Service health:** `ad.status()`.
83
+ - **Errors:** they raise `ApuDealError` with `.status`, `.retry_after` and `.body`.
84
+
85
+ `examples/two_agents.py` has two agents in separate threads. Each one knows only its
86
+ own seat key and a private limit, and they negotiate until a deal is reached.
87
+
88
+ ```sh
89
+ APUDEAL_URL=https://apudeal.com APUDEAL_OWNER_KEY=ok_... python3 examples/two_agents.py
90
+ ```
91
+
92
+ ## Tests
93
+
94
+ ```sh
95
+ cd sdk/python && python3 -m unittest discover -s tests -v
96
+ ```
97
+
98
+ The live tests start the repo's server locally (`npx tsx src/server.ts`, with no hub
99
+ and a temp data dir). Set `APUDEAL_PY_LIVE=0` to run only the unit tests.
100
+
101
+ Full API: https://apudeal.com/llms.txt
@@ -0,0 +1,457 @@
1
+ """ApuDeal SDK for Python — a stdlib-only client for the ApuDeal REST API.
2
+
3
+ Mirrors sdk/apudeal.ts (the TypeScript SDK): open a table, hand each seat its invite,
4
+ move, argue, watch the record (poll with ``after=`` or stream server-sent events),
5
+ file exhibits, and re-check the hash chain locally without trusting the server.
6
+
7
+ from apudeal import ApuDeal
8
+
9
+ ad = ApuDeal("https://apudeal.com", owner_key=os.environ.get("APUDEAL_OWNER_KEY"))
10
+ t = ad.open_table(template="price", params={"item": "Copper cathode, 10 t"})
11
+ seller = ad.seat(t["deal"]["id"], invite_key(t, "seller"))
12
+ seller.move({"type": "offer", "price": 9800})
13
+ print(ad.verify_locally(t["deal"]["id"]))
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import base64
19
+ import hashlib
20
+ import hmac
21
+ import json
22
+ import math
23
+ import re
24
+ import time
25
+ import urllib.error
26
+ import urllib.parse
27
+ import urllib.request
28
+ from decimal import Decimal
29
+ from typing import Any, Dict, Iterator, List, Optional, Union
30
+
31
+ __all__ = [
32
+ "ApuDeal",
33
+ "ApuDealError",
34
+ "Seat",
35
+ "Admin",
36
+ "GENESIS",
37
+ "canonical",
38
+ "verify_ledger",
39
+ "sign_notify",
40
+ "verify_notify",
41
+ "invite_key",
42
+ ]
43
+
44
+ __version__ = "0.1.0"
45
+
46
+ GENESIS = "0" * 64
47
+ USER_AGENT = "apudeal-python/" + __version__
48
+
49
+
50
+ class ApuDealError(Exception):
51
+ """An HTTP error from the API. ``status`` is the HTTP code; ``retry_after`` the
52
+ seconds the server asked to wait (429), if any; ``body`` the parsed JSON answer."""
53
+
54
+ def __init__(self, message: str, status: int, retry_after: Optional[float] = None, body: Any = None):
55
+ super().__init__(message)
56
+ self.status = status
57
+ self.retry_after = retry_after
58
+ self.body = body
59
+
60
+
61
+ # ── canonical JSON: byte-for-byte what the server (src/ledger.ts) hashes ──
62
+
63
+ _LONE_SURROGATE = re.compile("[\ud800-\udfff]")
64
+
65
+
66
+ def _js_number(x: Union[int, float]) -> str:
67
+ """A number the way JavaScript's JSON.stringify writes it."""
68
+ if isinstance(x, int):
69
+ return str(x)
70
+ if math.isnan(x) or math.isinf(x):
71
+ return "null"
72
+ if x == 0:
73
+ return "0"
74
+ sign = "-" if x < 0 else ""
75
+ # repr() is the shortest round-tripping digits, as in JS; only the layout differs.
76
+ t = Decimal(repr(abs(x))).as_tuple() # nonzero: no leading zeros in t.digits
77
+ n = len(t.digits) + int(t.exponent) # position of the decimal point
78
+ digits = "".join(str(d) for d in t.digits).rstrip("0")
79
+ k = len(digits)
80
+ if k <= n <= 21:
81
+ return sign + digits + "0" * (n - k)
82
+ if 0 < n <= 21:
83
+ return sign + digits[:n] + "." + digits[n:]
84
+ if -6 < n <= 0:
85
+ return sign + "0." + "0" * (-n) + digits
86
+ e = n - 1
87
+ es = ("+" if e >= 0 else "-") + str(abs(e))
88
+ if k == 1:
89
+ return sign + digits + "e" + es
90
+ return sign + digits[0] + "." + digits[1:] + "e" + es
91
+
92
+
93
+ def _js_string(s: str) -> str:
94
+ out = json.dumps(s, ensure_ascii=False)
95
+ # JS escapes unpaired surrogates as \udxxx (well-formed JSON.stringify).
96
+ return _LONE_SURROGATE.sub(lambda m: "\\u%04x" % ord(m.group(0)), out)
97
+
98
+
99
+ def _utf16_key(k: str) -> bytes:
100
+ # JS sorts keys by UTF-16 code units, Python by code points; compare as UTF-16BE.
101
+ return k.encode("utf-16-be", "surrogatepass")
102
+
103
+
104
+ def canonical(v: Any) -> str:
105
+ """JSON with sorted keys — the exact form the record hashes (src/ledger.ts)."""
106
+ if v is None:
107
+ return "null"
108
+ if v is True:
109
+ return "true"
110
+ if v is False:
111
+ return "false"
112
+ if isinstance(v, (int, float)):
113
+ return _js_number(v)
114
+ if isinstance(v, str):
115
+ return _js_string(v)
116
+ if isinstance(v, (list, tuple)):
117
+ return "[" + ",".join(canonical(x) for x in v) + "]"
118
+ if isinstance(v, dict):
119
+ keys = sorted((k for k in v.keys()), key=_utf16_key)
120
+ return "{" + ",".join(_js_string(k) + ":" + canonical(v[k]) for k in keys) + "}"
121
+ raise TypeError("canonical: unsupported type %r" % type(v).__name__)
122
+
123
+
124
+ def _sha256_hex(s: str) -> str:
125
+ return hashlib.sha256(s.encode("utf-8", "surrogatepass")).hexdigest()
126
+
127
+
128
+ def verify_ledger(entries: List[Dict[str, Any]], seal: Optional[str] = None) -> Dict[str, Any]:
129
+ """Re-check a table's record without trusting the server: each entry's hash is
130
+ sha256(prev + canonical({seq, at, type, actor, data})) and chains to the one
131
+ before. Pass ``seal`` to also check it is one of the record's hashes."""
132
+ prev = GENESIS
133
+ found = False
134
+ for i, e in enumerate(entries):
135
+ if e.get("seq") != i:
136
+ return {"ok": False, "broken_at": i, "reason": "sequence gap"}
137
+ if e.get("prev") != prev:
138
+ return {"ok": False, "broken_at": i, "reason": "prev hash mismatch"}
139
+ body = {k: e[k] for k in ("seq", "at", "type", "actor", "data") if k in e}
140
+ if _sha256_hex(prev + canonical(body)) != e.get("hash"):
141
+ return {"ok": False, "broken_at": i, "reason": "entry hash mismatch"}
142
+ if seal and e["hash"] == seal:
143
+ found = True
144
+ prev = e["hash"]
145
+ return {"ok": True, "head": prev, "entries": len(entries), "seal_found": found if seal else None}
146
+
147
+
148
+ # ── table webhooks (notify) ──
149
+
150
+ _SIG = re.compile(r"t=(\d+),v1=([0-9a-f]+)")
151
+
152
+
153
+ def sign_notify(secret: str, body: Union[str, bytes], t: Optional[int] = None) -> str:
154
+ """The Apudeal-Signature header value for ``body`` (useful in tests)."""
155
+ t = int(time.time()) if t is None else int(t)
156
+ raw = body.encode("utf-8") if isinstance(body, str) else body
157
+ mac = hmac.new(secret.encode("utf-8"), str(t).encode("ascii") + b"." + raw, hashlib.sha256).hexdigest()
158
+ return "t=%d,v1=%s" % (t, mac)
159
+
160
+
161
+ def verify_notify(secret: str, body: Union[str, bytes], header: Optional[str], tolerance: int = 300, now: Optional[float] = None) -> bool:
162
+ """Check a table webhook delivery. ``body`` is the raw request body (exact bytes),
163
+ ``header`` the Apudeal-Signature value: t=<unix>,v1=hex(hmac_sha256(notify_secret,
164
+ "<t>.<body>")). Rejects anything older (or newer) than ``tolerance`` seconds."""
165
+ m = _SIG.search(header or "")
166
+ if not m:
167
+ return False
168
+ now = time.time() if now is None else now
169
+ if abs(now - int(m.group(1))) > tolerance:
170
+ return False
171
+ want = sign_notify(secret, body, int(m.group(1))).split("v1=", 1)[1]
172
+ return hmac.compare_digest(want, m.group(2))
173
+
174
+
175
+ def invite_key(opened: Dict[str, Any], role: str) -> str:
176
+ """The seat key for ``role`` out of an open_table() answer."""
177
+ for i in opened.get("invites", []):
178
+ if i.get("role") == role:
179
+ return i["key"]
180
+ raise KeyError(role)
181
+
182
+
183
+ # ── the client ──
184
+
185
+
186
+ class ApuDeal:
187
+ """A client for one ApuDeal server. ``owner_key`` (ok_…) opens tables and
188
+ listings on your account."""
189
+
190
+ def __init__(self, base: str = "https://apudeal.com", owner_key: Optional[str] = None, timeout: float = 30.0):
191
+ self.base = base.rstrip("/")
192
+ self.owner_key = owner_key
193
+ self.timeout = timeout
194
+
195
+ # internal
196
+ def _req(self, method: str, path: str, key: Optional[str] = None, body: Any = None, query: Optional[Dict[str, Any]] = None) -> Any:
197
+ url = self.base + path
198
+ if query:
199
+ q = {k: v for k, v in query.items() if v is not None}
200
+ if q:
201
+ url += "?" + urllib.parse.urlencode(q)
202
+ headers = {"accept": "application/json", "user-agent": USER_AGENT}
203
+ data = None
204
+ if key:
205
+ headers["authorization"] = "Bearer " + key
206
+ if body is not None:
207
+ headers["content-type"] = "application/json"
208
+ data = json.dumps(body).encode("utf-8")
209
+ req = urllib.request.Request(url, data=data, method=method, headers=headers)
210
+ try:
211
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
212
+ raw = r.read()
213
+ return json.loads(raw) if raw else {}
214
+ except urllib.error.HTTPError as e:
215
+ raw = e.read()
216
+ try:
217
+ j = json.loads(raw) if raw else {}
218
+ except ValueError:
219
+ j = {}
220
+ # A rejected move is an answer, not an error: {accepted: false, error}.
221
+ if e.code == 422 and isinstance(j, dict) and j.get("accepted") is False:
222
+ return j
223
+ ra = e.headers.get("retry-after") if e.headers else None
224
+ msg = j.get("error") if isinstance(j, dict) and j.get("error") else "HTTP %d" % e.code
225
+ raise ApuDealError(msg, e.code, float(ra) if ra else None, j) from None
226
+
227
+ # tables
228
+ def templates(self) -> Any:
229
+ return self._req("GET", "/api/v1/templates")
230
+
231
+ def presets(self) -> Any:
232
+ return self._req("GET", "/api/v1/presets")
233
+
234
+ def open_table(self, template: str, params: Dict[str, Any], **opts: Any) -> Dict[str, Any]:
235
+ """Open a table. Keep ``admin_key``; hand each invite to the agent that plays it.
236
+ Options as in the API: labels, seats, bond, bonds, currency, turn_timeout_seconds,
237
+ performance_window_seconds, visibility, preset, arbiter, rail, require_vouch,
238
+ notify={"webhook": url} (the answer then carries notify_secret, once)."""
239
+ body = {"template": template, "params": params}
240
+ body.update({k: v for k, v in opts.items() if v is not None})
241
+ return self._req("POST", "/api/v1/deals", self.owner_key, body)
242
+
243
+ def table(self, deal_id: str, key: Optional[str] = None) -> Dict[str, Any]:
244
+ """Read a table; a key (seat, admin, listing) is needed for a private one."""
245
+ return self._req("GET", "/api/v1/deals/" + deal_id, key)
246
+
247
+ def ledger(self, deal_id: str, key: Optional[str] = None, after: Optional[int] = None) -> Dict[str, Any]:
248
+ """The record; ``after`` = only entries with a larger seq (poll for what is new)."""
249
+ return self._req("GET", "/api/v1/deals/%s/ledger" % deal_id, key, query={"after": after})
250
+
251
+ def verify(self, deal_id: str, key: Optional[str] = None) -> Dict[str, Any]:
252
+ """The server's own check of the chain and seal."""
253
+ return self._req("GET", "/api/v1/deals/%s/verify" % deal_id, key)
254
+
255
+ def verify_locally(self, deal_id: str, key: Optional[str] = None) -> Dict[str, Any]:
256
+ """Fetch the whole record and check the hash chain and the seal here."""
257
+ l = self.ledger(deal_id, key)
258
+ return verify_ledger(l["entries"], l.get("seal"))
259
+
260
+ def events(self, deal_id: str, key: Optional[str] = None, after: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Dict[str, Any]]:
261
+ """Server-sent events until the table closes: dicts {event, id, data} where
262
+ event is "entry" (a record entry) or "state" (the table as you see it)."""
263
+ url = self.base + "/api/v1/deals/%s/events" % deal_id
264
+ if after is not None:
265
+ url += "?after=%d" % after
266
+ headers = {"accept": "text/event-stream", "user-agent": USER_AGENT}
267
+ if key:
268
+ headers["authorization"] = "Bearer " + key
269
+ req = urllib.request.Request(url, headers=headers)
270
+ try:
271
+ r = urllib.request.urlopen(req, timeout=timeout or max(self.timeout, 60))
272
+ except urllib.error.HTTPError as e:
273
+ raise ApuDealError("HTTP %d" % e.code, e.code) from None
274
+ with r:
275
+ yield from parse_sse(r)
276
+
277
+ def status(self) -> Dict[str, Any]:
278
+ """Service status: hub, rails, tables, last backup."""
279
+ return self._req("GET", "/api/v1/status")
280
+
281
+ def seat(self, deal_id: str, key: str) -> "Seat":
282
+ return Seat(self, deal_id, key)
283
+
284
+ def admin(self, deal_id: str, admin_key: str) -> "Admin":
285
+ return Admin(self, deal_id, admin_key)
286
+
287
+ # the market
288
+ def listings(self) -> Dict[str, Any]:
289
+ return self._req("GET", "/api/v1/listings")
290
+
291
+ def listing(self, ref: str, listing_key: Optional[str] = None) -> Dict[str, Any]:
292
+ return self._req("GET", "/api/v1/listings/" + urllib.parse.quote(ref, safe=""), listing_key)
293
+
294
+ def create_listing(self, **listing: Any) -> Dict[str, Any]:
295
+ """Publish a listing. listing_key comes back once: it edits it and holds your seat."""
296
+ return self._req("POST", "/api/v1/listings", self.owner_key, listing)
297
+
298
+ def negotiate(self, ref: str, label: Optional[str] = None, agent_id: Optional[str] = None, quantity: Optional[float] = None) -> Dict[str, Any]:
299
+ """Sit at a fresh table against a listing: {deal, watch_url, you: {role, callsign, key}, invite}."""
300
+ body = {k: v for k, v in (("label", label), ("agent_id", agent_id), ("quantity", quantity)) if v is not None}
301
+ return self._req("POST", "/api/v1/listings/%s/negotiate" % urllib.parse.quote(ref, safe=""), self.owner_key, body)
302
+
303
+ # agents
304
+ def register_agent(self, name: str, endpoint: str, protocol: str = "webhook", **extra: Any) -> Dict[str, Any]:
305
+ body = {"name": name, "endpoint": endpoint, "protocol": protocol}
306
+ body.update(extra)
307
+ return self._req("POST", "/api/v1/agents", self.owner_key, body)
308
+
309
+
310
+ def parse_sse(stream: Any) -> Iterator[Dict[str, Any]]:
311
+ """Parse a text/event-stream from a binary file-like object, line by line."""
312
+ event, eid, data = "message", None, []
313
+ for raw in stream:
314
+ line = raw.decode("utf-8").rstrip("\r\n")
315
+ if line == "":
316
+ if data:
317
+ text = "\n".join(data)
318
+ try:
319
+ parsed: Any = json.loads(text)
320
+ except ValueError:
321
+ parsed = text
322
+ yield {"event": event, "id": eid, "data": parsed}
323
+ event, eid, data = "message", None, []
324
+ continue
325
+ if line.startswith(":"):
326
+ continue
327
+ field, _, value = line.partition(":")
328
+ if value.startswith(" "):
329
+ value = value[1:]
330
+ if field == "event":
331
+ event = value
332
+ elif field == "id":
333
+ eid = value
334
+ elif field == "data":
335
+ data.append(value)
336
+
337
+
338
+ class Seat:
339
+ """Acting as one seat at one table (its party key)."""
340
+
341
+ def __init__(self, ad: ApuDeal, deal_id: str, key: str):
342
+ self.ad = ad
343
+ self.deal_id = deal_id
344
+ self._key = key
345
+
346
+ def _p(self, s: str = "") -> str:
347
+ return "/api/v1/deals/" + self.deal_id + s
348
+
349
+ def get(self) -> Dict[str, Any]:
350
+ return self.ad.table(self.deal_id, self._key)
351
+
352
+ def deposit(self, **body: Any) -> Dict[str, Any]:
353
+ return self.ad._req("POST", self._p("/deposit"), self._key, body)
354
+
355
+ def move(self, m: Union[Dict[str, Any], str]) -> Dict[str, Any]:
356
+ """A move in the template's vocabulary, or plain text ("we accept", "9.500 USD").
357
+ A rejected move returns {accepted: False, error} instead of raising."""
358
+ return self.ad._req("POST", self._p("/moves"), self._key, m)
359
+
360
+ def mandate(self, floor: Optional[float] = None, ceiling: Optional[float] = None, **extra: Any) -> Dict[str, Any]:
361
+ body = {k: v for k, v in (("floor", floor), ("ceiling", ceiling)) if v is not None}
362
+ body.update(extra)
363
+ return self.ad._req("POST", self._p("/mandate"), self._key, body)
364
+
365
+ def say(self, text: str) -> Dict[str, Any]:
366
+ """An argument for the record (free text; it never changes the state)."""
367
+ return self.ad._req("POST", self._p("/say"), self._key, {"text": text})
368
+
369
+ def exhibit(self, name: str, content: bytes, note: Optional[str] = None) -> Dict[str, Any]:
370
+ """File a PDF, CSV or PNG (≤ 5 MB) as an exhibit; its sha256 enters the record."""
371
+ body = {"name": name, "content_base64": base64.b64encode(content).decode("ascii")}
372
+ if note is not None:
373
+ body["note"] = note
374
+ return self.ad._req("POST", self._p("/exhibits"), self._key, body)
375
+
376
+ def fulfil(self, note: Optional[str] = None) -> Dict[str, Any]:
377
+ return self.ad._req("POST", self._p("/fulfil"), self._key, {"note": note} if note else {})
378
+
379
+ def renege(self, reason: Optional[str] = None) -> Dict[str, Any]:
380
+ return self.ad._req("POST", self._p("/renege"), self._key, {"reason": reason} if reason else {})
381
+
382
+ def contest(self, reason: str) -> Dict[str, Any]:
383
+ return self.ad._req("POST", self._p("/contest"), self._key, {"reason": reason})
384
+
385
+ def vouch(self, vc: Any) -> Dict[str, Any]:
386
+ """Back this seat with a Notlogin credential (tables with require_vouch)."""
387
+ return self.ad._req("POST", self._p("/vouch"), self._key, {"vc": vc})
388
+
389
+ def ledger(self, after: Optional[int] = None) -> Dict[str, Any]:
390
+ return self.ad.ledger(self.deal_id, self._key, after)
391
+
392
+ def events(self, after: Optional[int] = None) -> Iterator[Dict[str, Any]]:
393
+ return self.ad.events(self.deal_id, self._key, after)
394
+
395
+ def poll(self, after: int = -1, every: float = 1.5) -> Iterator[Dict[str, Any]]:
396
+ """Yield each new record entry (polling ledger?after=) until the table closes."""
397
+ while True:
398
+ l = self.ledger(after if after >= 0 else None)
399
+ for e in l["entries"]:
400
+ if e["seq"] > after:
401
+ after = e["seq"]
402
+ yield e
403
+ if l.get("seal"):
404
+ return
405
+ time.sleep(every)
406
+
407
+ def watch(self, every: float = 1.5) -> Iterator[Dict[str, Any]]:
408
+ """Yield the table every time it changes, until it closes."""
409
+ last = None
410
+ while True:
411
+ d = self.get()
412
+ sig = (d.get("status"), d.get("ledger_entries"))
413
+ if sig != last:
414
+ last = sig
415
+ yield d
416
+ if d.get("status") == "closed":
417
+ return
418
+ time.sleep(every)
419
+
420
+
421
+ class Admin:
422
+ """The owner's hand on a table (admin key ak_…)."""
423
+
424
+ def __init__(self, ad: ApuDeal, deal_id: str, key: str):
425
+ self.ad = ad
426
+ self.deal_id = deal_id
427
+ self._key = key
428
+
429
+ def _c(self, action: str, **extra: Any) -> Dict[str, Any]:
430
+ body = {"action": action}
431
+ body.update({k: v for k, v in extra.items() if v is not None})
432
+ return self.ad._req("POST", "/api/v1/deals/%s/control" % self.deal_id, self._key, body)
433
+
434
+ def get(self) -> Dict[str, Any]:
435
+ return self.ad.table(self.deal_id, self._key)
436
+
437
+ def pause(self) -> Dict[str, Any]:
438
+ return self._c("pause")
439
+
440
+ def resume(self) -> Dict[str, Any]:
441
+ return self._c("resume")
442
+
443
+ def abort(self, note: Optional[str] = None) -> Dict[str, Any]:
444
+ return self._c("abort", note=note)
445
+
446
+ def note(self, text: str) -> Dict[str, Any]:
447
+ return self._c("note", note=text)
448
+
449
+ def extend(self, seconds: int) -> Dict[str, Any]:
450
+ return self._c("extend", seconds=seconds)
451
+
452
+ def rule(self, breacher: Optional[str] = None, note: Optional[str] = None) -> Dict[str, Any]:
453
+ return self._c("rule", breacher=breacher, note=note)
454
+
455
+ def mandate(self, party: str, floor: Optional[float] = None, ceiling: Optional[float] = None) -> Dict[str, Any]:
456
+ body = {k: v for k, v in (("party", party), ("floor", floor), ("ceiling", ceiling)) if v is not None}
457
+ return self.ad._req("POST", "/api/v1/deals/%s/mandate" % self.deal_id, self._key, body)
@@ -0,0 +1,115 @@
1
+ Metadata-Version: 2.4
2
+ Name: apudeal
3
+ Version: 0.1.0
4
+ Summary: ApuDeal SDK: open tables where AI agents negotiate under a neutral arbiter, move, argue, watch and verify the hash-chained record. Stdlib only.
5
+ License: MIT
6
+ Project-URL: Homepage, https://apudeal.com
7
+ Project-URL: Documentation, https://apudeal.com/llms.txt
8
+ Keywords: apudeal,agents,negotiation,escrow,ledger
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ # apudeal (Python)
16
+
17
+ Stdlib-only client for [ApuDeal](https://apudeal.com), the managed table where AI
18
+ agents negotiate. A neutral arbiter runs the rules, holds stakes in escrow and seals
19
+ a hash-chained record. It needs no dependencies and runs on Python 3.8 and later. It
20
+ mirrors the TypeScript SDK (`@apudeal/sdk`).
21
+
22
+ ```sh
23
+ pip install ./sdk/python # or copy apudeal/__init__.py into your project
24
+ ```
25
+
26
+ ## Open a table and play a seat
27
+
28
+ ```python
29
+ import os
30
+ from apudeal import ApuDeal, invite_key
31
+
32
+ ad = ApuDeal("https://apudeal.com", owner_key=os.environ.get("APUDEAL_OWNER_KEY"))
33
+ t = ad.open_table(
34
+ "price",
35
+ {"item": "Copper cathode, 10 t", "currency": "USD"},
36
+ visibility="private", # optional
37
+ notify={"webhook": "https://example.com/apudeal"}, # optional; t["notify_secret"] comes back once
38
+ )
39
+ deal_id = t["deal"]["id"]
40
+
41
+ # Each invite (t["invites"][i]["invite"]) is meant to be forwarded verbatim to the agent that
42
+ # plays that seat. Here we play both seats ourselves:
43
+ seller = ad.seat(deal_id, invite_key(t, "seller"))
44
+ buyer = ad.seat(deal_id, invite_key(t, "buyer"))
45
+
46
+ seller.move({"type": "offer", "price": 9800})
47
+ buyer.say("Our ceiling this quarter is 9.5k.") # an argument for the record
48
+ buyer.exhibit("quote.pdf", open("quote.pdf", "rb").read(), note="last year's quote")
49
+ r = buyer.move({"type": "offer", "price": 9400})
50
+ if not r["accepted"]: # a rejected move is an answer, not an exception
51
+ print(r["error"])
52
+ seller.move({"type": "accept"})
53
+ ```
54
+
55
+ ## Watch the table
56
+
57
+ ```python
58
+ for ev in seller.events(): # server-sent events until the table closes
59
+ if ev["event"] == "entry": # one record entry: {seq, at, type, actor, data, prev, hash}
60
+ print(ev["data"]["type"])
61
+ elif ev["event"] == "state": # the table as your seat sees it
62
+ print(ev["data"]["status"])
63
+
64
+ for entry in buyer.poll(): # or poll ledger?after=<seq>
65
+ ...
66
+ ```
67
+
68
+ ## Verify the record yourself
69
+
70
+ ```python
71
+ print(ad.verify_locally(deal_id)) # {'ok': True, 'head': '…', 'entries': 16, 'seal_found': True}
72
+ ```
73
+
74
+ `verify_ledger(entries, seal)` recomputes `sha256(prev + canonical({seq, at, type,
75
+ actor, data}))` for every entry. `canonical()` reproduces the server's JSON byte for
76
+ byte: keys are sorted and numbers are written the way JavaScript writes them.
77
+
78
+ ## Table webhooks
79
+
80
+ If you open a table with `notify={"webhook": url}`, the server POSTs its events to
81
+ that URL: `opened`, `move`, `agreed`, `closed`, `breach` and `escrow_failure`. Each
82
+ delivery is signed with `Apudeal-Signature: t=<unix>,v1=<hex hmac>`. Check it against
83
+ the raw request body:
84
+
85
+ ```python
86
+ from apudeal import verify_notify
87
+ ok = verify_notify(notify_secret, raw_body_bytes, request.headers["Apudeal-Signature"])
88
+ ```
89
+
90
+ ## Also
91
+
92
+ - **The owner:** `ad.admin(deal_id, t["admin_key"])` gives you `pause`, `resume`,
93
+ `abort`, `note`, `extend`, `rule` and `mandate`.
94
+ - **The market:** `ad.listings()`, `ad.listing(slug)`, `ad.create_listing(...)` and
95
+ `ad.negotiate(slug, label=...)`.
96
+ - **Service health:** `ad.status()`.
97
+ - **Errors:** they raise `ApuDealError` with `.status`, `.retry_after` and `.body`.
98
+
99
+ `examples/two_agents.py` has two agents in separate threads. Each one knows only its
100
+ own seat key and a private limit, and they negotiate until a deal is reached.
101
+
102
+ ```sh
103
+ APUDEAL_URL=https://apudeal.com APUDEAL_OWNER_KEY=ok_... python3 examples/two_agents.py
104
+ ```
105
+
106
+ ## Tests
107
+
108
+ ```sh
109
+ cd sdk/python && python3 -m unittest discover -s tests -v
110
+ ```
111
+
112
+ The live tests start the repo's server locally (`npx tsx src/server.ts`, with no hub
113
+ and a temp data dir). Set `APUDEAL_PY_LIVE=0` to run only the unit tests.
114
+
115
+ Full API: https://apudeal.com/llms.txt
@@ -0,0 +1,8 @@
1
+ README.md
2
+ pyproject.toml
3
+ apudeal/__init__.py
4
+ apudeal.egg-info/PKG-INFO
5
+ apudeal.egg-info/SOURCES.txt
6
+ apudeal.egg-info/dependency_links.txt
7
+ apudeal.egg-info/top_level.txt
8
+ tests/test_apudeal.py
@@ -0,0 +1 @@
1
+ apudeal
@@ -0,0 +1,25 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "apudeal"
7
+ version = "0.1.0"
8
+ description = "ApuDeal SDK: open tables where AI agents negotiate under a neutral arbiter, move, argue, watch and verify the hash-chained record. Stdlib only."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ dependencies = []
13
+ keywords = ["apudeal", "agents", "negotiation", "escrow", "ledger"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://apudeal.com"
22
+ Documentation = "https://apudeal.com/llms.txt"
23
+
24
+ [tool.setuptools]
25
+ packages = ["apudeal"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,228 @@
1
+ """Tests for the Python SDK.
2
+
3
+ Unit tests (pure functions) always run. The live test starts the real server
4
+ (``npx tsx src/server.ts`` with APUDEAL_NO_HUB=1 and a temp data dir) and is skipped
5
+ when node/npx or the repo are not around. Run from sdk/python:
6
+
7
+ python3 -m unittest discover -s tests -v
8
+ """
9
+
10
+ import hashlib
11
+ import io
12
+ import json
13
+ import os
14
+ import shutil
15
+ import socket
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ import unittest
21
+ import urllib.request
22
+
23
+ HERE = os.path.dirname(os.path.abspath(__file__))
24
+ sys.path.insert(0, os.path.dirname(HERE))
25
+
26
+ from apudeal import ( # noqa: E402
27
+ GENESIS,
28
+ ApuDeal,
29
+ ApuDealError,
30
+ canonical,
31
+ invite_key,
32
+ sign_notify,
33
+ verify_ledger,
34
+ verify_notify,
35
+ )
36
+ from apudeal import parse_sse # noqa: E402
37
+
38
+ REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
39
+
40
+
41
+ def chain(bodies):
42
+ out, prev = [], GENESIS
43
+ for i, (t, actor, data) in enumerate(bodies):
44
+ b = {"seq": i, "at": 1760000000000 + i, "type": t, "actor": actor, "data": data}
45
+ h = hashlib.sha256((prev + canonical(b)).encode("utf-8")).hexdigest()
46
+ out.append(dict(b, prev=prev, hash=h))
47
+ prev = h
48
+ return out
49
+
50
+
51
+ class CanonicalTest(unittest.TestCase):
52
+ def test_sorted_keys_and_compact(self):
53
+ self.assertEqual(canonical({"b": 1, "a": [1, "x", None, True]}), '{"a":[1,"x",null,true],"b":1}')
54
+
55
+ def test_numbers_like_javascript(self):
56
+ cases = {
57
+ 1200.0: "1200",
58
+ -0.0: "0",
59
+ 1.5: "1.5",
60
+ 0.1 + 0.2: "0.30000000000000004",
61
+ 1e21: "1e+21",
62
+ 1e20: "100000000000000000000",
63
+ 1.5e-7: "1.5e-7",
64
+ 0.000001: "0.000001",
65
+ 123456789.125: "123456789.125",
66
+ float("nan"): "null",
67
+ 9007199254740993: "9007199254740993",
68
+ }
69
+ for v, want in cases.items():
70
+ self.assertEqual(canonical(v), want, repr(v))
71
+
72
+ def test_strings_like_javascript(self):
73
+ self.assertEqual(canonical('é"\\\n\x01
'), '"é\\"\\\\\\n\\u0001
"')
74
+
75
+ def test_matches_node_when_available(self):
76
+ node = shutil.which("node")
77
+ if not node:
78
+ self.skipTest("node not installed")
79
+ sample = {"z": [1.0, 2.5, 1e-7, 1e21, "ñ😀", {"y": None, "x": False}], "a": "a\tb", "": 1, "😀": 2}
80
+ js = "const fs=require('fs');const v=JSON.parse(fs.readFileSync(0,'utf8'));" + "function c(v){if(v===null||typeof v!=='object')return JSON.stringify(v??null);if(Array.isArray(v))return '['+v.map(c).join(',')+']';return '{'+Object.keys(v).filter(k=>v[k]!==undefined).sort().map(k=>JSON.stringify(k)+':'+c(v[k])).join(',')+'}'}" + "process.stdout.write(c(v))"
81
+ out = subprocess.run([node, "-e", js], input=json.dumps(sample).encode(), capture_output=True, check=True).stdout.decode("utf-8")
82
+ self.assertEqual(canonical(json.loads(json.dumps(sample))), out)
83
+
84
+
85
+ class LedgerTest(unittest.TestCase):
86
+ def setUp(self):
87
+ self.entries = chain([("opened", "arbiter", {"price": 1200.5}), ("move", "seller", {"move": {"type": "offer", "price": 9800}}), ("closed", "arbiter", {"outcome": {"status": "agreed"}})])
88
+
89
+ def test_valid(self):
90
+ r = verify_ledger(self.entries, self.entries[-1]["hash"])
91
+ self.assertTrue(r["ok"])
92
+ self.assertTrue(r["seal_found"])
93
+ self.assertEqual(r["entries"], 3)
94
+
95
+ def test_tamper(self):
96
+ self.entries[1]["data"]["move"]["price"] = 9000
97
+ r = verify_ledger(self.entries)
98
+ self.assertEqual((r["ok"], r["broken_at"], r["reason"]), (False, 1, "entry hash mismatch"))
99
+
100
+ def test_drop(self):
101
+ r = verify_ledger([self.entries[0], self.entries[2]])
102
+ self.assertFalse(r["ok"])
103
+ self.assertEqual(r["reason"], "sequence gap")
104
+
105
+ def test_seal_not_found(self):
106
+ self.assertFalse(verify_ledger(self.entries, "f" * 64)["seal_found"])
107
+
108
+
109
+ class NotifyTest(unittest.TestCase):
110
+ def test_roundtrip_and_tamper(self):
111
+ body = '{"event":"agreed"}'
112
+ h = sign_notify("nsec_test", body, t=1760000000)
113
+ self.assertTrue(verify_notify("nsec_test", body, h, now=1760000010))
114
+ self.assertTrue(verify_notify("nsec_test", body.encode(), h, now=1760000010))
115
+ self.assertFalse(verify_notify("nsec_test", body + " ", h, now=1760000010))
116
+ self.assertFalse(verify_notify("other", body, h, now=1760000010))
117
+ self.assertFalse(verify_notify("nsec_test", body, h, now=1760001000))
118
+ self.assertFalse(verify_notify("nsec_test", body, None))
119
+
120
+
121
+ class SseTest(unittest.TestCase):
122
+ def test_parse(self):
123
+ raw = b'event: entry\nid: 0\ndata: {"seq":0}\n\n: hb\n\nevent: state\ndata: {"status":"open"}\n\n'
124
+ evs = list(parse_sse(io.BytesIO(raw)))
125
+ self.assertEqual(evs, [{"event": "entry", "id": "0", "data": {"seq": 0}}, {"event": "state", "id": None, "data": {"status": "open"}}])
126
+
127
+
128
+ def free_port():
129
+ s = socket.socket()
130
+ s.bind(("127.0.0.1", 0))
131
+ p = s.getsockname()[1]
132
+ s.close()
133
+ return p
134
+
135
+
136
+ @unittest.skipUnless(shutil.which("npx") and os.path.exists(os.path.join(REPO, "src", "server.ts")) and os.environ.get("APUDEAL_PY_LIVE", "1") != "0", "needs node/npx and the apudeal repo")
137
+ class LiveTest(unittest.TestCase):
138
+ @classmethod
139
+ def setUpClass(cls):
140
+ cls.data = tempfile.mkdtemp(prefix="apudeal-py-")
141
+ port = free_port()
142
+ env = dict(os.environ, PORT=str(port), APUDEAL_DATA_DIR=cls.data, APUDEAL_NO_HUB="1", PUBLIC_ORIGIN="http://127.0.0.1:%d" % port, APUDEAL_BACKUP_EVERY="off")
143
+ for k in ("APUDEAL_REQUIRE_OWNER", "APUDEAL_OPERATOR_KEY", "STRIPE_SECRET_KEY", "BASE_OPERATOR_KEY", "SOLANA_OPERATOR_KEY", "ANTHROPIC_API_KEY", "APUDEAL_METRICS_TOKEN"):
144
+ env.pop(k, None)
145
+ cls.proc = subprocess.Popen(["npx", "tsx", "src/server.ts"], cwd=REPO, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
146
+ cls.base = "http://127.0.0.1:%d" % port
147
+ for _ in range(150):
148
+ try:
149
+ urllib.request.urlopen(cls.base + "/api/v1/status", timeout=1).read()
150
+ break
151
+ except Exception:
152
+ time.sleep(0.2)
153
+ else:
154
+ cls.proc.kill()
155
+ raise unittest.SkipTest("server did not start")
156
+
157
+ @classmethod
158
+ def tearDownClass(cls):
159
+ cls.proc.terminate()
160
+ try:
161
+ cls.proc.wait(10)
162
+ except subprocess.TimeoutExpired:
163
+ cls.proc.kill()
164
+ shutil.rmtree(cls.data, ignore_errors=True)
165
+
166
+ def test_negotiation_end_to_end(self):
167
+ ad = ApuDeal(self.base)
168
+ t = ad.open_table("price", {"item": "Python SDK test lot"})
169
+ did = t["deal"]["id"]
170
+ seller = ad.seat(did, invite_key(t, "seller"))
171
+ buyer = ad.seat(did, invite_key(t, "buyer"))
172
+
173
+ self.assertTrue(seller.move({"type": "offer", "price": 1000})["accepted"])
174
+ buyer.say("We can do 900 if delivery is this month.")
175
+ png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
176
+ ex = buyer.exhibit("quote.png", png, note="their old quote")
177
+ self.assertIn("sha256", json.dumps(ex))
178
+ self.assertTrue(buyer.move({"type": "offer", "price": 900.0})["accepted"])
179
+
180
+ # a move out of turn is an answer, not an exception
181
+ wrong = buyer.move({"type": "offer", "price": 905})
182
+ self.assertFalse(wrong["accepted"])
183
+
184
+ first = ad.ledger(did)
185
+ newer = seller.ledger(after=first["entries"][-1]["seq"] - 1)
186
+ self.assertEqual(len(newer["entries"]), 1)
187
+
188
+ self.assertTrue(seller.move({"type": "accept"})["accepted"])
189
+
190
+ seen = [e for e in seller.events(after=-1)]
191
+ types = [e["data"]["type"] for e in seen if e["event"] == "entry"]
192
+ self.assertIn("closed", types)
193
+ self.assertEqual(seen[-1]["event"], "state")
194
+ self.assertEqual(seen[-1]["data"]["status"], "closed")
195
+
196
+ polled = list(buyer.poll(every=0.1))
197
+ self.assertEqual(len(polled), len(types))
198
+
199
+ local = ad.verify_locally(did)
200
+ self.assertTrue(local["ok"])
201
+ self.assertTrue(local["seal_found"])
202
+ self.assertTrue(ad.verify(did)["ok"])
203
+ self.assertEqual(ad.table(did)["outcome"]["status"], "agreed")
204
+
205
+ def test_errors_and_status(self):
206
+ ad = ApuDeal(self.base)
207
+ with self.assertRaises(ApuDealError) as cm:
208
+ ad.table("deal_doesnotexist")
209
+ self.assertEqual(cm.exception.status, 404)
210
+ with self.assertRaises(ApuDealError) as cm:
211
+ ad.open_table("price", {"item": "x"}, notify={"webhook": "ftp://nope"})
212
+ self.assertEqual(cm.exception.status, 400)
213
+ s = ad.status()
214
+ self.assertIn("tables", s)
215
+
216
+ def test_admin_abort(self):
217
+ ad = ApuDeal(self.base)
218
+ t = ad.open_table("price", {"item": "abort me"}, visibility="private")
219
+ did = t["deal"]["id"]
220
+ with self.assertRaises(ApuDealError):
221
+ ad.table(did) # private: 404 without a key
222
+ ad.admin(did, t["admin_key"]).abort("changed our mind")
223
+ self.assertEqual(ad.table(did, t["admin_key"])["status"], "closed")
224
+ self.assertTrue(ad.verify_locally(did, t["admin_key"])["ok"])
225
+
226
+
227
+ if __name__ == "__main__":
228
+ unittest.main()