agent-mediate 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3353 @@
1
+ """
2
+ Agent-Mediate Python client (`AgentMediateClient`) and optional x402 EIP-3009 USDC payer.
3
+
4
+ Zero required third-party dependencies (`urllib.request` transport). Handles:
5
+ - RFC 9421 Ed25519 signing on every request
6
+ - Single `Idempotency-Key` reused across network/429/5xx retries and x402 paid retries
7
+ - Out-of-band `platform_did` pinning (mandatory on Base mainnet `eip155:8453`)
8
+ - SEC3-8 outcome verification (`disputeId`, `expectedEnvironment`, `parties` membership, Ed25519 signature)
9
+ - Compact (`?view=compact`) and full dispute views
10
+ - Webhook signature, tag, recipient, and dispute verification (`AgentMediateClient.verify_webhook`)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import base64
15
+ import copy
16
+ import datetime
17
+ import email.utils
18
+ import hashlib
19
+ import http.client
20
+ import ipaddress
21
+ import json
22
+ import math
23
+ import os
24
+ import re
25
+ import socket
26
+ import ssl
27
+ import threading
28
+ import time
29
+ import urllib.error
30
+ import urllib.parse
31
+ import urllib.request
32
+ import uuid
33
+ from dataclasses import dataclass
34
+ from encodings import idna as _stdlib_idna
35
+ from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
36
+
37
+ from .crypto import AgentKey, is_did_key
38
+ from .jcs import canonical_json, loads_jcs_json, sha256_hex
39
+ from .protocol import (
40
+ DEFAULT_KEY_HISTORY_TTL_MS,
41
+ DISPUTE_INVITE_TYPE,
42
+ HONOURS_ATTESTATION_TYPE,
43
+ WEBHOOK_SIGNATURE_TAG,
44
+ compute_outcome_hash,
45
+ compute_terms_hash,
46
+ did_key_from_ed25519_jwk,
47
+ did_web_document_authorizes_key,
48
+ did_web_from_url,
49
+ encode_base_anchor_calldata,
50
+ sign_mandate,
51
+ sign_request,
52
+ url_from_did_web,
53
+ verify_agent_card_signature,
54
+ verify_checkpoint_inclusion,
55
+ verify_document,
56
+ verify_document_with_key_history,
57
+ verify_key_history,
58
+ verify_public_audit_chain,
59
+ verify_request,
60
+ verify_request_proof,
61
+ )
62
+
63
+ _SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
64
+ _TX_HASH_RE = re.compile(r"^0x[0-9a-fA-F]{64}$")
65
+ _EVM_ADDR_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
66
+ _UTS46_DOTS_RE = re.compile(r"[\.\u3002\uff0e\uff61]")
67
+ _UTS46_DEVIATIONS = ("\u00df", "\u03c2", "\u200c", "\u200d")
68
+ _MAX_SAFE_INT = 9007199254740991
69
+ _MAX_RETRY_AFTER_SECONDS = 30.0
70
+ _MAX_RESPONSE_BYTES = 4 * 1024 * 1024
71
+ _SETTLEMENT_METHODS = ("PROPOSAL_ACCEPTED", "OVERLAP_MIDPOINT", "FINAL_OFFER_DETERMINATION")
72
+
73
+ PRODUCTION_API_URL = "https://api.ai-agents-mediation.com"
74
+ PRODUCTION_APEX_URL = "https://ai-agents-mediation.com"
75
+ # Out-of-band pinned production platform signing DIDs by normalised API base URL (SEC3-8 / H-1 / P1-1).
76
+ DEFAULT_PRODUCTION_PLATFORM_DIDS: Dict[str, str] = {
77
+ PRODUCTION_API_URL: "did:key:z6Mkg7r4aHyPrNKYy1gbWGXu15VgyN9fCbhqKVwftdhHxJ3W",
78
+ }
79
+
80
+
81
+ def normalize_base_url(raw_url: str) -> str:
82
+ """Canonicalise an HTTP(S) API base_url (`P1-2`): lowercases scheme/host, strips default :443/:80 & trailing slashes, and rewrites bare production apex to PRODUCTION_API_URL."""
83
+ if not isinstance(raw_url, str) or not raw_url.strip():
84
+ raise ValueError("base_url must be a non-empty http(s) URL")
85
+ trimmed = raw_url.strip()
86
+ if re.search(r"[\x00-\x20\x7f\\]", trimmed):
87
+ raise ValueError(f"base_url contains invalid characters: {raw_url}")
88
+ parsed = urllib.parse.urlsplit(trimmed)
89
+ scheme = parsed.scheme.lower()
90
+ if scheme not in ("http", "https"):
91
+ raise ValueError(f"base_url must use http:// or https://, got {parsed.scheme!r}")
92
+ if parsed.username is not None or parsed.password is not None or parsed.query != "" or parsed.fragment != "":
93
+ raise ValueError("base_url must not contain credentials, query parameters, or fragments")
94
+ try:
95
+ port = parsed.port
96
+ except ValueError as exc:
97
+ raise ValueError(f"base_url has invalid port: {raw_url}") from exc
98
+ raw_host = parsed.hostname
99
+ if not raw_host:
100
+ raise ValueError(f"base_url is missing hostname: {raw_url}")
101
+ if ":" in raw_host:
102
+ try:
103
+ addr = ipaddress.ip_address(raw_host)
104
+ except ValueError as exc:
105
+ raise ValueError(f"base_url has invalid IPv6 host: {raw_url}") from exc
106
+ host_str = f"[{addr.compressed}]"
107
+ elif _is_ip_host(raw_host):
108
+ host_str = str(ipaddress.ip_address(raw_host))
109
+ else:
110
+ try:
111
+ host_str = _uts46_to_ascii(raw_host) if not raw_host.isascii() else raw_host.lower()
112
+ except UnicodeError as exc:
113
+ raise ValueError(f"base_url has invalid domain host: {raw_url}") from exc
114
+ default_port = 443 if scheme == "https" else 80
115
+ netloc = f"{host_str}:{port}" if (port is not None and port != default_port) else host_str
116
+ clean_path = "" if parsed.path in ("", "/") else parsed.path.rstrip("/")
117
+ normalized = f"{scheme}://{netloc}{clean_path}"
118
+ return PRODUCTION_API_URL if normalized == PRODUCTION_APEX_URL else normalized
119
+
120
+
121
+ def _uts46_to_ascii(host: str) -> str:
122
+ """CR-SDK-L3: UTS #46 non-transitional domain ToASCII matching Node/WHATWG URL (preserves ß, ς, ZWNJ, ZWJ)."""
123
+ try:
124
+ import idna # type: ignore[import-not-found]
125
+
126
+ return str(idna.encode(host, uts46=True).decode("ascii")).lower()
127
+ except ImportError:
128
+ pass
129
+ except Exception as exc:
130
+ raise UnicodeError(str(exc)) from exc
131
+ if not host:
132
+ raise UnicodeError("empty host")
133
+ out: List[str] = []
134
+ for raw_label in _UTS46_DOTS_RE.split(host):
135
+ if not raw_label:
136
+ raise UnicodeError("empty label")
137
+ if raw_label.isascii():
138
+ low = raw_label.lower()
139
+ if len(low) > 63 or low.startswith("-") or low.endswith("-"):
140
+ raise UnicodeError("invalid ASCII label")
141
+ out.append(low)
142
+ continue
143
+ folded = raw_label.replace("\u1e9e", "\u00df")
144
+ if not any(d in folded for d in _UTS46_DEVIATIONS):
145
+ out.append(_stdlib_idna.ToASCII(folded).decode("ascii").lower())
146
+ continue
147
+ parts: List[str] = []
148
+ buf: List[str] = []
149
+ for ch in folded:
150
+ if ch in _UTS46_DEVIATIONS:
151
+ if buf:
152
+ parts.append(_stdlib_idna.nameprep("".join(buf)))
153
+ buf = []
154
+ parts.append(ch)
155
+ else:
156
+ buf.append(ch)
157
+ if buf:
158
+ parts.append(_stdlib_idna.nameprep("".join(buf)))
159
+ prepped = "".join(parts)
160
+ if prepped.startswith("-") or prepped.endswith("-"):
161
+ raise UnicodeError("label starts or ends with hyphen")
162
+ ace = "xn--" + prepped.encode("punycode").decode("ascii").lower()
163
+ if len(ace) > 63:
164
+ raise UnicodeError("ACE label exceeds 63 bytes")
165
+ out.append(ace)
166
+ res = ".".join(out)
167
+ if len(res) > 253:
168
+ raise UnicodeError("domain exceeds 253 bytes")
169
+ return res
170
+
171
+
172
+ def _parse_retry_after_seconds(header: Optional[str], now_ms: int) -> float:
173
+ if not header:
174
+ return 0.0
175
+ trimmed = header.strip()
176
+ if re.fullmatch(r"^\d+$", trimmed):
177
+ return min(float(int(trimmed)), _MAX_RETRY_AFTER_SECONDS)
178
+ try:
179
+ dt = email.utils.parsedate_to_datetime(trimmed)
180
+ if dt.tzinfo is None:
181
+ dt = dt.replace(tzinfo=datetime.timezone.utc)
182
+ delta = dt.timestamp() - (now_ms / 1000.0)
183
+ return min(max(0.0, delta), _MAX_RETRY_AFTER_SECONDS)
184
+ except Exception:
185
+ return 0.0
186
+
187
+ BASE_SEPOLIA = "eip155:84532"
188
+ BASE_MAINNET = "eip155:8453"
189
+
190
+ USDC_ON_BASE: Dict[str, Dict[str, Any]] = {
191
+ BASE_SEPOLIA: {"asset": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "name": "USDC", "version": "2", "chainId": 84532},
192
+ BASE_MAINNET: {"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", "name": "USD Coin", "version": "2", "chainId": 8453},
193
+ }
194
+
195
+
196
+ class AgentMediateError(Exception):
197
+ def __init__(
198
+ self,
199
+ status: int,
200
+ code: str,
201
+ message: str,
202
+ body: Any = None,
203
+ *,
204
+ idempotency_key: Optional[str] = None,
205
+ payment_sent: bool = False,
206
+ ) -> None:
207
+ super().__init__(message)
208
+ self.status = status
209
+ self.code = code
210
+ self.body = body
211
+ self.hint: Optional[str] = body.get("hint") if isinstance(body, Mapping) and isinstance(body.get("hint"), str) else None
212
+ self.docs: Optional[str] = body.get("docs") if isinstance(body, Mapping) and isinstance(body.get("docs"), str) else None
213
+ # CR-SDK-M1: retry a failed mutating call with this exact key; the server then replays/resumes the original
214
+ # request (and the SDK resends the identical paid request) instead of charging a second fee.
215
+ self.idempotency_key: Optional[str] = idempotency_key
216
+ self.payment_sent: bool = payment_sent
217
+
218
+
219
+ # CR-SDK-M1: ambiguous paid failures are remembered for a byte-identical same-key retry (server idempotency window).
220
+ _PENDING_PAID_TTL_MS = 24 * 3_600_000
221
+ _PENDING_PAID_MAX = 256
222
+ _PLATFORM_INFO_CACHE_TTL_MS = 60_000
223
+ _KEY_HISTORY_CACHE_TTL_MS = 60_000
224
+ _KEY_HISTORY_REFRESH_COOLDOWN_MS = 10_000
225
+ _LOCAL_HONOURS_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})
226
+ _AMBIGUOUS_PAYMENT_CODES = frozenset({"PAYMENT_UNCONFIRMED", "FACILITATOR_UNAVAILABLE", "FACILITATOR_BUSY", "CONCURRENT_REQUEST"})
227
+
228
+
229
+ def _is_ip_host(host: str) -> bool:
230
+ try:
231
+ ipaddress.ip_address(host)
232
+ return True
233
+ except ValueError:
234
+ return False
235
+
236
+
237
+ def _merge_prior_determination_bounds(
238
+ *,
239
+ bounds: Optional[Mapping[str, Mapping[str, float]]],
240
+ determination_consent: Optional[bool],
241
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]],
242
+ ctx: Optional[Mapping[str, Any]],
243
+ ) -> tuple[Optional[bool], Optional[Dict[str, Dict[str, float]]]]:
244
+ effective_consent = (
245
+ True
246
+ if (ctx is not None and determination_consent is None and ctx.get("prevDeterminationConsent") is True)
247
+ else determination_consent
248
+ )
249
+ if determination_bounds is not None:
250
+ return effective_consent, {k: dict(v) for k, v in determination_bounds.items()}
251
+ prev_db_map = ctx.get("prevDeterminationBounds") if ctx is not None else None
252
+ prev_b_map = ctx.get("prevBounds") if ctx is not None else None
253
+ if isinstance(prev_db_map, Mapping) and bounds is not None:
254
+ merged: Dict[str, Dict[str, float]] = {}
255
+ for issue_id, next_b in bounds.items():
256
+ prev_db = prev_db_map.get(issue_id)
257
+ prev_b = prev_b_map.get(issue_id) if isinstance(prev_b_map, Mapping) else None
258
+ if not isinstance(prev_db, Mapping):
259
+ merged[issue_id] = {"min": next_b["min"], "max": next_b["max"]}
260
+ elif (
261
+ isinstance(prev_b, Mapping)
262
+ and float(prev_db["min"]) <= float(prev_b["min"])
263
+ and float(prev_db["max"]) >= float(prev_b["max"])
264
+ ):
265
+ merged[issue_id] = {
266
+ "min": min(prev_db["min"], next_b["min"]),
267
+ "max": max(prev_db["max"], next_b["max"]),
268
+ }
269
+ else:
270
+ merged[issue_id] = {"min": prev_db["min"], "max": prev_db["max"]}
271
+ return effective_consent, merged
272
+ return effective_consent, None
273
+
274
+
275
+ class PaymentRequiredError(AgentMediateError):
276
+ def __init__(self, payment_required: Mapping[str, Any], body: Any = None, *, idempotency_key: Optional[str] = None) -> None:
277
+ super().__init__(
278
+ 402,
279
+ "PAYMENT_REQUIRED",
280
+ "a fee is due and no payer is configured",
281
+ body,
282
+ idempotency_key=idempotency_key,
283
+ payment_sent=False,
284
+ )
285
+ self.payment_required = dict(payment_required)
286
+
287
+
288
+ class PaymentPolicyError(AgentMediateError, ValueError):
289
+ def __init__(self, message: str) -> None:
290
+ AgentMediateError.__init__(self, 0, "PAYMENT_POLICY_ERROR", message)
291
+
292
+
293
+ def content_hash(content: str | bytes) -> str:
294
+ raw = content.encode("utf-8") if isinstance(content, str) else content
295
+ return hashlib.sha256(raw).hexdigest()
296
+
297
+
298
+ @dataclass
299
+ class HttpResponse:
300
+ status: int
301
+ headers: Dict[str, str]
302
+ body: str
303
+
304
+
305
+ TransportLike = Callable[[str, str, Mapping[str, str], Optional[bytes]], HttpResponse]
306
+
307
+
308
+ class _NoRedirectHandler(urllib.request.HTTPRedirectHandler):
309
+ def redirect_request(
310
+ self,
311
+ req: urllib.request.Request,
312
+ fp: Any,
313
+ code: int,
314
+ msg: str,
315
+ headers: Any,
316
+ newurl: str,
317
+ ) -> Optional[urllib.request.Request]:
318
+ return None
319
+
320
+
321
+ def _make_default_transport(timeout_seconds: Optional[float]) -> TransportLike:
322
+ opener = urllib.request.build_opener(_NoRedirectHandler())
323
+
324
+ def _transport(method: str, url: str, headers: Mapping[str, str], body: Optional[bytes]) -> HttpResponse:
325
+ req = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
326
+ try:
327
+ with opener.open(req, timeout=timeout_seconds) as resp:
328
+ resp_headers = {k.lower(): v for k, v in resp.headers.items()}
329
+ raw_resp = resp.read(_MAX_RESPONSE_BYTES + 1)
330
+ if len(raw_resp) > _MAX_RESPONSE_BYTES:
331
+ raise AgentMediateError(
332
+ resp.status,
333
+ "RESPONSE_TOO_LARGE",
334
+ f"response body exceeds {_MAX_RESPONSE_BYTES} bytes",
335
+ )
336
+ return HttpResponse(status=resp.status, headers=resp_headers, body=raw_resp.decode("utf-8"))
337
+ except urllib.error.HTTPError as err:
338
+ try:
339
+ resp_headers = {k.lower(): v for k, v in err.headers.items()} if err.headers else {}
340
+ if 300 <= err.code < 400:
341
+ return HttpResponse(status=err.code, headers=resp_headers, body="")
342
+ raw_err = err.read(_MAX_RESPONSE_BYTES + 1)
343
+ if len(raw_err) > _MAX_RESPONSE_BYTES:
344
+ raise AgentMediateError(
345
+ err.code,
346
+ "RESPONSE_TOO_LARGE",
347
+ f"response body exceeds {_MAX_RESPONSE_BYTES} bytes",
348
+ ) from None
349
+ err_body = raw_err.decode("utf-8", errors="replace")
350
+ return HttpResponse(status=err.code, headers=resp_headers, body=err_body)
351
+ finally:
352
+ try:
353
+ err.close()
354
+ except Exception:
355
+ pass
356
+
357
+ return _transport
358
+
359
+
360
+ _default_transport = _make_default_transport(30.0)
361
+
362
+
363
+ def _normalize_evm_address(raw: str, *, strict_checksum: bool = False) -> str:
364
+ if not isinstance(raw, str) or not _EVM_ADDR_RE.fullmatch(raw):
365
+ raise PaymentPolicyError("pay_to must be a 0x-prefixed 20-byte address")
366
+ try:
367
+ from eth_utils import is_checksum_address, to_checksum_address # type: ignore[import-not-found]
368
+ except ImportError:
369
+ return raw
370
+ hex_part = raw[2:]
371
+ if strict_checksum and hex_part != hex_part.lower() and hex_part != hex_part.upper() and not is_checksum_address(raw):
372
+ raise PaymentPolicyError("pay_to has an invalid EIP-55 address checksum")
373
+ return str(to_checksum_address(raw.lower()))
374
+
375
+
376
+ class X402Payer:
377
+ """
378
+ Optional EIP-3009 USDC payer on Base (`pip install "agent-mediate[x402]"`).
379
+ Enforces pinned `network`, `asset`, `pay_to` (required on mainnet), per-payment cap, cumulative budget,
380
+ and short authorization validity.
381
+ """
382
+
383
+ def __init__(
384
+ self,
385
+ *,
386
+ private_key: str,
387
+ max_amount_atomic: int,
388
+ budget_atomic: Optional[int] = None,
389
+ network: str = BASE_SEPOLIA,
390
+ pay_to: Optional[str] = None,
391
+ asset: Optional[str] = None,
392
+ validity_seconds: int = 120,
393
+ now_ms: Optional[Callable[[], int]] = None,
394
+ ) -> None:
395
+ if network not in USDC_ON_BASE:
396
+ raise PaymentPolicyError(f"unsupported network {network}; expected {BASE_SEPOLIA} or {BASE_MAINNET}")
397
+ usdc = USDC_ON_BASE[network]
398
+ if asset is not None and str(asset).lower() != str(usdc["asset"]).lower():
399
+ raise PaymentPolicyError(f"asset {asset} is not USDC on {network} ({usdc['asset']})")
400
+ if not isinstance(max_amount_atomic, int) or isinstance(max_amount_atomic, bool) or max_amount_atomic <= 0:
401
+ raise PaymentPolicyError("max_amount_atomic must be a positive integer")
402
+ resolved_budget = budget_atomic if budget_atomic is not None else max_amount_atomic * 2
403
+ if not isinstance(resolved_budget, int) or isinstance(resolved_budget, bool) or resolved_budget <= 0:
404
+ raise PaymentPolicyError("budget_atomic must be a positive integer")
405
+ if not isinstance(validity_seconds, int) or isinstance(validity_seconds, bool) or validity_seconds < 10:
406
+ raise PaymentPolicyError("validity_seconds must be an integer >= 10")
407
+ try:
408
+ from eth_account import Account # type: ignore[import-not-found]
409
+ except ImportError as exc:
410
+ raise ImportError('install eth-account for x402 payments: pip install "agent-mediate[x402]"') from exc
411
+ pinned_pay_to = _normalize_evm_address(pay_to, strict_checksum=True) if pay_to is not None else None
412
+ if network == BASE_MAINNET and not pinned_pay_to:
413
+ raise PaymentPolicyError("on Base mainnet, pay_to must be pinned out of band")
414
+
415
+ self._account = Account.from_key(private_key)
416
+ self.address: str = self._account.address
417
+ self.network = network
418
+ self._pinned_pay_to = pinned_pay_to
419
+ self._max_amount = max_amount_atomic
420
+ self._budget = resolved_budget
421
+ self._spent = 0
422
+ self._issued: Dict[str, tuple[int, int]] = {}
423
+ self._pending_reclaims: List[tuple[int, int]] = []
424
+ self._lock = threading.Lock()
425
+ self._validity_seconds = validity_seconds
426
+ self._now_ms = now_ms or (lambda: int(time.time() * 1000))
427
+
428
+ def _reclaim_expired_locked(self) -> None:
429
+ if not self._pending_reclaims:
430
+ return
431
+ now_sec = self._now_ms() // 1000
432
+ remaining: List[tuple[int, int]] = []
433
+ for amt, reclaim_at in self._pending_reclaims:
434
+ if now_sec > reclaim_at:
435
+ self._spent = max(0, self._spent - amt)
436
+ else:
437
+ remaining.append((amt, reclaim_at))
438
+ self._pending_reclaims = remaining
439
+
440
+ @property
441
+ def spent_atomic(self) -> int:
442
+ with self._lock:
443
+ self._reclaim_expired_locked()
444
+ return self._spent
445
+
446
+ def release_unsettled(self, payment_header: str) -> None:
447
+ """Mark an issued PAYMENT-SIGNATURE header as definitively unsettled (`RESPONDENT_UNREACHABLE`) so its budget reclaims after `validBefore + 60s` (`CR3-SDK-M3`)."""
448
+ with self._lock:
449
+ entry = self._issued.pop(payment_header, None)
450
+ if entry is not None:
451
+ amt, valid_before = entry
452
+ self._pending_reclaims.append((amt, valid_before + 60))
453
+ self._reclaim_expired_locked()
454
+
455
+ def pay(self, challenge: Mapping[str, Any], *, operation: str, expected_pay_to: Optional[str] = None) -> str:
456
+ if operation != "file":
457
+ raise PaymentPolicyError(f"refusing to pay for unknown operation {operation}")
458
+ if not isinstance(challenge, Mapping) or challenge.get("x402Version") != 2 or not isinstance(challenge.get("accepts"), list):
459
+ raise PaymentPolicyError(f"unsupported x402 version {challenge.get('x402Version') if isinstance(challenge, Mapping) else None}")
460
+
461
+ usdc = USDC_ON_BASE[self.network]
462
+ accepts = challenge["accepts"]
463
+ req = next(
464
+ (
465
+ a
466
+ for a in accepts
467
+ if isinstance(a, Mapping)
468
+ and a.get("scheme") == "exact"
469
+ and a.get("network") == self.network
470
+ and isinstance(a.get("asset"), str)
471
+ and a["asset"].lower() == str(usdc["asset"]).lower()
472
+ ),
473
+ None,
474
+ )
475
+ if req is None:
476
+ raise PaymentPolicyError(f"challenge offers no exact USDC payment on {self.network}")
477
+
478
+ raw_target_pay_to = self._pinned_pay_to or expected_pay_to
479
+ if not raw_target_pay_to:
480
+ raise PaymentPolicyError("no pay_to pinned and the platform publishes none")
481
+ target_pay_to = self._pinned_pay_to or _normalize_evm_address(raw_target_pay_to, strict_checksum=False)
482
+ req_pay_to = req.get("payTo")
483
+ if not isinstance(req_pay_to, str) or not _EVM_ADDR_RE.fullmatch(req_pay_to) or req_pay_to.lower() != target_pay_to.lower():
484
+ raise PaymentPolicyError(f"payTo {req_pay_to} does not match expected {target_pay_to}")
485
+
486
+ extra = req.get("extra")
487
+ if extra is not None:
488
+ if not isinstance(extra, Mapping):
489
+ raise PaymentPolicyError("invalid extra EIP-712 domain metadata")
490
+ if extra.get("name") is not None and extra.get("name") != usdc["name"]:
491
+ raise PaymentPolicyError(f"unexpected EIP-712 domain name {extra.get('name')}")
492
+ if extra.get("version") is not None and extra.get("version") != usdc["version"]:
493
+ raise PaymentPolicyError(f"unexpected EIP-712 domain version {extra.get('version')}")
494
+
495
+ raw_amount = req.get("amount")
496
+ if not isinstance(raw_amount, str) or not re.fullmatch(r"^\d+$", raw_amount):
497
+ raise PaymentPolicyError("invalid amount")
498
+ amount = int(raw_amount)
499
+ if amount <= 0:
500
+ raise PaymentPolicyError("invalid amount")
501
+ if amount > self._max_amount:
502
+ raise PaymentPolicyError(f"fee {amount} exceeds per-payment cap {self._max_amount}")
503
+
504
+ raw_timeout = req.get("maxTimeoutSeconds")
505
+ if not isinstance(raw_timeout, int) or isinstance(raw_timeout, bool) or raw_timeout <= 0:
506
+ raise PaymentPolicyError("maxTimeoutSeconds must be a positive integer")
507
+ validity = min(raw_timeout, self._validity_seconds)
508
+
509
+ with self._lock:
510
+ self._reclaim_expired_locked()
511
+ if self._spent + amount > self._budget:
512
+ raise PaymentPolicyError(
513
+ f"fee {amount} would exceed remaining budget {self._budget - self._spent} of {self._budget}"
514
+ )
515
+ self._spent += amount
516
+
517
+ now_sec = self._now_ms() // 1000
518
+ valid_after = max(0, now_sec - 600)
519
+ valid_before = now_sec + validity
520
+ nonce_hex = "0x" + os.urandom(32).hex()
521
+
522
+ typed_data = {
523
+ "types": {
524
+ "EIP712Domain": [
525
+ {"name": "name", "type": "string"},
526
+ {"name": "version", "type": "string"},
527
+ {"name": "chainId", "type": "uint256"},
528
+ {"name": "verifyingContract", "type": "address"},
529
+ ],
530
+ "TransferWithAuthorization": [
531
+ {"name": "from", "type": "address"},
532
+ {"name": "to", "type": "address"},
533
+ {"name": "value", "type": "uint256"},
534
+ {"name": "validAfter", "type": "uint256"},
535
+ {"name": "validBefore", "type": "uint256"},
536
+ {"name": "nonce", "type": "bytes32"},
537
+ ],
538
+ },
539
+ "primaryType": "TransferWithAuthorization",
540
+ "domain": {
541
+ "name": usdc["name"],
542
+ "version": usdc["version"],
543
+ "chainId": usdc["chainId"],
544
+ "verifyingContract": usdc["asset"],
545
+ },
546
+ "message": {
547
+ "from": self.address,
548
+ "to": target_pay_to,
549
+ "value": amount,
550
+ "validAfter": valid_after,
551
+ "validBefore": valid_before,
552
+ "nonce": bytes.fromhex(nonce_hex[2:]),
553
+ },
554
+ }
555
+ try:
556
+ signed = self._account.sign_typed_data(full_message=typed_data)
557
+ raw_sig_hex = (
558
+ bytes(signed.signature).hex()
559
+ if isinstance(signed.signature, (bytes, bytearray, memoryview))
560
+ else str(signed.signature.hex())
561
+ )
562
+ sig_hex = "0x" + (raw_sig_hex[2:] if raw_sig_hex.startswith(("0x", "0X")) else raw_sig_hex)
563
+ except Exception:
564
+ with self._lock:
565
+ self._spent -= amount
566
+ raise
567
+
568
+ accepted: Dict[str, Any] = {
569
+ "scheme": "exact",
570
+ "network": self.network,
571
+ "amount": raw_amount,
572
+ "asset": req["asset"],
573
+ "payTo": req_pay_to,
574
+ "maxTimeoutSeconds": raw_timeout,
575
+ "extra": {"name": usdc["name"], "version": usdc["version"]},
576
+ }
577
+ payload: Dict[str, Any] = {
578
+ "x402Version": 2,
579
+ **({"resource": challenge["resource"]} if "resource" in challenge and challenge["resource"] is not None else {}),
580
+ "accepted": accepted,
581
+ "payload": {
582
+ "signature": sig_hex,
583
+ "authorization": {
584
+ "from": self.address,
585
+ "to": target_pay_to,
586
+ "value": str(amount),
587
+ "validAfter": str(valid_after),
588
+ "validBefore": str(valid_before),
589
+ "nonce": nonce_hex,
590
+ },
591
+ },
592
+ }
593
+ encoded = base64.b64encode(json.dumps(payload).encode("utf-8")).decode("ascii")
594
+ with self._lock:
595
+ if encoded not in self._issued and len(self._issued) >= _PENDING_PAID_MAX:
596
+ self._issued.pop(next(iter(self._issued)), None)
597
+ self._issued[encoded] = (amount, valid_before)
598
+ return encoded
599
+
600
+
601
+ def create_x402_payer(**kwargs: Any) -> X402Payer:
602
+ return X402Payer(**kwargs)
603
+
604
+
605
+ class AgentMediateClient:
606
+ def __init__(
607
+ self,
608
+ *,
609
+ base_url: str,
610
+ agent_key: AgentKey,
611
+ platform_did: Optional[str] = None,
612
+ allow_unpinned_platform_did: bool = False,
613
+ expected_environment: Optional[str] = None,
614
+ expected_rules_hash: Optional[str] = None,
615
+ default_view: str = "full",
616
+ payer: Optional[X402Payer] = None,
617
+ transport: Optional[TransportLike] = None,
618
+ now_ms: Optional[Callable[[], int]] = None,
619
+ max_retries: int = 3,
620
+ timeout_ms: int = 30_000,
621
+ ) -> None:
622
+ norm_base_url = normalize_base_url(base_url)
623
+ effective_platform_did = platform_did if platform_did is not None else DEFAULT_PRODUCTION_PLATFORM_DIDS.get(norm_base_url)
624
+ effective_expected_env = expected_environment if expected_environment is not None else (
625
+ "production" if norm_base_url == PRODUCTION_API_URL else None
626
+ )
627
+ allow_unpinned = bool(allow_unpinned_platform_did)
628
+ if effective_platform_did is not None and not is_did_key(effective_platform_did):
629
+ raise ValueError("platform_did must be a valid Ed25519 did:key")
630
+ if payer is not None and getattr(payer, "network", None) == BASE_MAINNET and not effective_platform_did and not allow_unpinned:
631
+ raise ValueError("on Base mainnet, platform_did must be pinned out of band")
632
+ if effective_expected_env == "production" and not effective_platform_did and not allow_unpinned:
633
+ raise ValueError("in production (expected_environment='production'), platform_did must be pinned out of band")
634
+ if default_view not in ("full", "compact"):
635
+ raise ValueError("default_view must be 'full' or 'compact'")
636
+ if isinstance(timeout_ms, bool) or not isinstance(timeout_ms, (int, float)) or not math.isfinite(timeout_ms) or timeout_ms < 0:
637
+ raise ValueError("timeout_ms must be a non-negative finite number")
638
+
639
+ self.base_url = norm_base_url
640
+ self.agent_key = agent_key
641
+ self.default_view = default_view
642
+ self._pinned_platform_did = effective_platform_did
643
+ self._allow_unpinned_platform_did = allow_unpinned
644
+ self._expected_environment = effective_expected_env
645
+ self._expected_rules_hash = expected_rules_hash
646
+ self._payer = payer
647
+ self._timeout_ms = int(timeout_ms)
648
+ self._custom_transport = transport
649
+ self._transport = transport or _make_default_transport((timeout_ms / 1000.0) if timeout_ms > 0 else None)
650
+ self._now_ms = now_ms or (lambda: int(time.time() * 1000))
651
+ self._max_retries = max_retries
652
+ self._platform_info: Optional[Dict[str, Any]] = None
653
+ self._platform_info_fetched_at: int = 0
654
+ self._verified_active_platform_did: Optional[str] = None
655
+ self._verified_pay_to: Optional[str] = None
656
+ self._key_history_cache: Optional[Dict[str, Any]] = None
657
+ self._key_history_refresh_at: int = 0
658
+ self._key_history_state: Dict[str, int] = {"min_updated_at": 0}
659
+ self._pending_paid: Dict[str, Dict[str, Any]] = {}
660
+ self._mandate_cache: Dict[str, Dict[str, Any]] = {}
661
+ self._scope_cache: Dict[str, Dict[str, Any]] = {}
662
+ self._pending_lock = threading.Lock()
663
+
664
+ @property
665
+ def did(self) -> str:
666
+ return self.agent_key.did
667
+
668
+ def with_default_view(self, default_view: str) -> "AgentMediateClient":
669
+ if default_view == self.default_view:
670
+ return self
671
+ clone = AgentMediateClient(
672
+ base_url=self.base_url,
673
+ agent_key=self.agent_key,
674
+ platform_did=self._pinned_platform_did,
675
+ allow_unpinned_platform_did=self._allow_unpinned_platform_did,
676
+ expected_environment=self._expected_environment,
677
+ expected_rules_hash=self._expected_rules_hash,
678
+ default_view=default_view,
679
+ payer=self._payer,
680
+ transport=self._custom_transport,
681
+ now_ms=self._now_ms,
682
+ max_retries=self._max_retries,
683
+ timeout_ms=self._timeout_ms,
684
+ )
685
+ clone._platform_info = self._platform_info
686
+ clone._platform_info_fetched_at = self._platform_info_fetched_at
687
+ clone._verified_active_platform_did = self._verified_active_platform_did
688
+ clone._verified_pay_to = self._verified_pay_to
689
+ clone._key_history_cache = self._key_history_cache
690
+ clone._key_history_refresh_at = self._key_history_refresh_at
691
+ clone._key_history_state = self._key_history_state
692
+ clone._pending_paid = self._pending_paid
693
+ clone._mandate_cache = self._mandate_cache
694
+ clone._scope_cache = self._scope_cache
695
+ clone._pending_lock = self._pending_lock
696
+ return clone
697
+
698
+ def _view_path(self, path: str, view: Optional[str] = None) -> str:
699
+ mode = view or self.default_view
700
+ if mode != "compact":
701
+ return path
702
+ sep = "&" if "?" in path else "?"
703
+ return f"{path}{sep}view=compact"
704
+
705
+ def mandate(
706
+ self,
707
+ bounds: Mapping[str, Mapping[str, float]],
708
+ *,
709
+ expires_in_ms: int = 7 * 24 * 3_600_000,
710
+ scope: Optional[Mapping[str, str]] = None,
711
+ determination_consent: Optional[bool] = None,
712
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
713
+ min_issued_at: Optional[int] = None,
714
+ min_expires_at: Optional[int] = None,
715
+ ) -> Dict[str, Any]:
716
+ now = self._now_ms()
717
+ issued_at = max(now, int(min_issued_at)) if min_issued_at is not None else now
718
+ expires_at = max(now + expires_in_ms, int(min_expires_at)) if min_expires_at is not None else now + expires_in_ms
719
+ unsigned: Dict[str, Any] = {
720
+ "id": f"mnd_{uuid.uuid4()}",
721
+ "principalId": self.did,
722
+ "agentId": self.did,
723
+ "bounds": {k: dict(v) for k, v in bounds.items()},
724
+ "expiresAt": expires_at,
725
+ "issuedAt": issued_at,
726
+ }
727
+ if determination_consent is not None:
728
+ unsigned["determinationConsent"] = determination_consent
729
+ if determination_bounds is not None:
730
+ unsigned["determinationBounds"] = {k: dict(v) for k, v in determination_bounds.items()}
731
+ if scope is not None:
732
+ unsigned["scope"] = {"contractHash": str(scope["contractHash"]), "counterpartyId": str(scope["counterpartyId"])}
733
+ return sign_mandate(unsigned, self.agent_key)
734
+
735
+ def platform(self) -> Dict[str, Any]:
736
+ now = self._now_ms()
737
+ with self._pending_lock:
738
+ cached = self._platform_info
739
+ fetched_at = self._platform_info_fetched_at
740
+ verified_active = self._verified_active_platform_did
741
+ if cached is None or (now - fetched_at >= _PLATFORM_INFO_CACHE_TTL_MS):
742
+ info = self._get_public("/v1/platform", error_code="PLATFORM_UNAVAILABLE", error_detail="could not read /v1/platform")
743
+ if self._pinned_platform_did and info.get("did") != self._pinned_platform_did and info.get("did") != verified_active:
744
+ rotated_ok = False
745
+ try:
746
+ hist = self.key_history(force=True)
747
+ rotated_ok = ((hist.get("document") or {}).get("activeDid")) == info.get("did")
748
+ except Exception:
749
+ rotated_ok = False
750
+ if not rotated_ok:
751
+ raise AgentMediateError(
752
+ 0,
753
+ "PLATFORM_DID_MISMATCH",
754
+ f"/v1/platform reported {info.get('did')}, expected pinned {self._pinned_platform_did}",
755
+ )
756
+ if self._expected_rules_hash and info.get("rulesHash") != self._expected_rules_hash:
757
+ raise AgentMediateError(
758
+ 0,
759
+ "RULES_HASH_MISMATCH",
760
+ f"/v1/platform reported rulesHash {info.get('rulesHash')}, expected {self._expected_rules_hash}",
761
+ )
762
+ with self._pending_lock:
763
+ self._platform_info = info
764
+ self._platform_info_fetched_at = now
765
+ cached = info
766
+ return dict(cached)
767
+
768
+ def rules(self) -> Dict[str, Any]:
769
+ info = self._get_public("/v1/rules", error_detail="could not read /v1/rules")
770
+ if self._expected_rules_hash and info.get("rulesHash") != self._expected_rules_hash:
771
+ raise AgentMediateError(0, "RULES_HASH_MISMATCH", f"/v1/rules reported rulesHash {info.get('rulesHash')}, expected {self._expected_rules_hash}")
772
+ return info
773
+
774
+ def key_history(self, force: bool = False) -> Dict[str, Any]:
775
+ now = self._now_ms()
776
+ expected_did = self._pinned_platform_did or self.platform()["did"]
777
+ with self._pending_lock:
778
+ cached = self._key_history_cache
779
+ min_upd = self._key_history_state["min_updated_at"] or None
780
+ if not force and cached is not None and now - cached["fetched_at"] < _KEY_HISTORY_CACHE_TTL_MS:
781
+ if verify_key_history(
782
+ cached["doc"],
783
+ expected_active_did=expected_did,
784
+ now_ms=now,
785
+ max_age_ms=DEFAULT_KEY_HISTORY_TTL_MS,
786
+ min_updated_at=min_upd,
787
+ ).get("ok"):
788
+ if self._pinned_platform_did:
789
+ active_did = ((cached["doc"].get("document") or {}).get("activeDid")) if isinstance(cached["doc"], Mapping) else None
790
+ if isinstance(active_did, str):
791
+ with self._pending_lock:
792
+ self._verified_active_platform_did = active_did
793
+ return copy.deepcopy(cached["doc"])
794
+ with self._pending_lock:
795
+ self._key_history_cache = None
796
+ doc = self._get_public("/.well-known/key-history.json", error_detail="could not read /.well-known/key-history.json")
797
+ verdict = verify_key_history(
798
+ doc,
799
+ expected_active_did=expected_did,
800
+ now_ms=now,
801
+ max_age_ms=DEFAULT_KEY_HISTORY_TTL_MS,
802
+ min_updated_at=min_upd,
803
+ )
804
+ if not verdict.get("ok"):
805
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", f"key-history.json failed verification: {verdict.get('reason')}")
806
+ with self._pending_lock:
807
+ doc_upd = ((doc.get("document") or {}).get("updatedAt")) if isinstance(doc, Mapping) else None
808
+ if isinstance(doc_upd, int) and not isinstance(doc_upd, bool) and doc_upd > self._key_history_state["min_updated_at"]:
809
+ self._key_history_state["min_updated_at"] = doc_upd
810
+ if self._pinned_platform_did:
811
+ active_did = ((doc.get("document") or {}).get("activeDid")) if isinstance(doc, Mapping) else None
812
+ if isinstance(active_did, str):
813
+ self._verified_active_platform_did = active_did
814
+ self._key_history_cache = {"doc": doc, "fetched_at": now}
815
+ return doc
816
+
817
+ def _verify_checkpoint_envelope(self, cp: Any, mismatch_code: str) -> None:
818
+ if not isinstance(cp, Mapping) or not self._verify_platform_document(cp.get("signedCheckpoint") or {}):
819
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", "transparency checkpoint signature failed verification")
820
+ signed_cp = cp.get("signedCheckpoint") or {}
821
+ doc = signed_cp.get("document")
822
+ if not isinstance(doc, Mapping) or doc.get("type") != "agent-mediate/transparency-checkpoint/v1":
823
+ raise AgentMediateError(0, mismatch_code, f"unexpected checkpoint document.type {(doc or {}).get('type') if isinstance(doc, Mapping) else None}")
824
+ if self._expected_environment is not None and doc.get("environment") != self._expected_environment:
825
+ raise AgentMediateError(0, mismatch_code, f"checkpoint environment {doc.get('environment')} does not match expected {self._expected_environment}")
826
+ if self._expected_rules_hash is not None and doc.get("rulesHash") != self._expected_rules_hash:
827
+ raise AgentMediateError(0, mismatch_code, f"checkpoint rulesHash {doc.get('rulesHash')} does not match expected {self._expected_rules_hash}")
828
+ seq = doc.get("checkpointSeq")
829
+ dispute_count = doc.get("disputeCount")
830
+ merkle_root = doc.get("merkleRoot")
831
+ prev_hash = doc.get("prevCheckpointHash")
832
+ if (
833
+ not isinstance(seq, int)
834
+ or isinstance(seq, bool)
835
+ or seq < 1
836
+ or seq > _MAX_SAFE_INT
837
+ or not isinstance(dispute_count, int)
838
+ or isinstance(dispute_count, bool)
839
+ or dispute_count < 0
840
+ or dispute_count > _MAX_SAFE_INT
841
+ or not isinstance(merkle_root, str)
842
+ or not _SHA256_HEX_RE.fullmatch(merkle_root)
843
+ or not isinstance(prev_hash, str)
844
+ or not _SHA256_HEX_RE.fullmatch(prev_hash)
845
+ ):
846
+ raise AgentMediateError(0, mismatch_code, "checkpoint document fields are malformed")
847
+ expected_calldata = encode_base_anchor_calldata(seq, merkle_root)
848
+ calldata = doc.get("baseAnchorCalldata")
849
+ if not isinstance(calldata, str) or calldata.lower() != expected_calldata.lower():
850
+ raise AgentMediateError(0, mismatch_code, "checkpoint baseAnchorCalldata does not match (checkpointSeq, merkleRoot)")
851
+ expected_hash = sha256_hex("agent-mediate/checkpoint-chain/v1\n" + canonical_json(doc))
852
+ if cp.get("checkpointHash") != expected_hash:
853
+ raise AgentMediateError(0, mismatch_code, "checkpointHash does not match signed checkpoint document")
854
+ anchor = cp.get("anchor")
855
+ if anchor is not None:
856
+ anchored_at = anchor.get("anchoredAt") if isinstance(anchor, Mapping) else None
857
+ if (
858
+ not isinstance(anchor, Mapping)
859
+ or not isinstance(anchor.get("network"), str)
860
+ or len(anchor.get("network")) == 0
861
+ or not isinstance(anchor.get("txHash"), str)
862
+ or not _TX_HASH_RE.fullmatch(anchor.get("txHash"))
863
+ or not isinstance(anchor.get("calldata"), str)
864
+ or anchor.get("calldata").lower() != expected_calldata.lower()
865
+ or not isinstance(anchored_at, int)
866
+ or isinstance(anchored_at, bool)
867
+ or anchored_at <= 0
868
+ or anchored_at > _MAX_SAFE_INT
869
+ ):
870
+ raise AgentMediateError(0, mismatch_code, "checkpoint anchor metadata does not match signed checkpoint calldata")
871
+
872
+ def transparency_checkpoint(self, seq: Optional[int] = None) -> Dict[str, Any]:
873
+ if seq is not None and (not isinstance(seq, int) or isinstance(seq, bool) or seq < 1 or seq > _MAX_SAFE_INT):
874
+ raise ValueError("checkpoint seq must be a positive safe integer")
875
+ path = f"/v1/transparency/checkpoints/{seq}" if seq is not None else "/v1/transparency/checkpoint"
876
+ cp = self._get_public(path, error_detail=f"could not read {path}")
877
+ self._verify_checkpoint_envelope(cp, "CHECKPOINT_MISMATCH")
878
+ if seq is not None and cp["signedCheckpoint"]["document"]["checkpointSeq"] != seq:
879
+ raise AgentMediateError(0, "CHECKPOINT_MISMATCH", f"checkpoint seq {cp['signedCheckpoint']['document']['checkpointSeq']} does not match requested {seq}")
880
+ return cp
881
+
882
+ def transparency(self) -> Dict[str, Any]:
883
+ return self._get_public("/transparency?format=json", error_detail="could not read /transparency")
884
+
885
+ def honours_roll(self) -> Dict[str, Any]:
886
+ return self._get_public("/v1/honours", error_detail="could not read /v1/honours")
887
+
888
+ def check_honours(self, subject: str) -> Dict[str, Any]:
889
+ trimmed = subject.strip()
890
+ if not trimmed:
891
+ raise ValueError("subject must be a non-empty domain, did:web, or did:key")
892
+ enc = urllib.parse.quote(trimmed, safe="")
893
+ body = self._get_public(f"/v1/honours/{enc}", error_detail=f"could not read /v1/honours/{trimmed}")
894
+ if not body.get("listed"):
895
+ return {**body, "verified": False}
896
+ entry = body.get("entry")
897
+ signed_att = body.get("signedAttestation")
898
+ if not isinstance(entry, Mapping) or not isinstance(signed_att, Mapping):
899
+ raise AgentMediateError(0, "HONOURS_MISMATCH", "listed Honours Roll response is missing entry or signedAttestation")
900
+ proof = signed_att.get("proof")
901
+ doc = signed_att.get("document")
902
+ if not isinstance(doc, Mapping) or doc.get("type") != HONOURS_ATTESTATION_TYPE:
903
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"unexpected Honours attestation type {(doc or {}).get('type') if isinstance(doc, Mapping) else None}")
904
+ if doc.get("environment") == "production" and not self._pinned_platform_did and not self._allow_unpinned_platform_did:
905
+ raise AgentMediateError(
906
+ 0,
907
+ "UNPINNED_PLATFORM_DID",
908
+ "refusing unpinned TOFU verification for environment=production; pin platform_did out of band",
909
+ )
910
+ with self._pending_lock:
911
+ verified_active = self._verified_active_platform_did
912
+ expected_did = verified_active or self._pinned_platform_did or self.platform()["did"]
913
+ now = self._now_ms()
914
+ sig_ok = verify_document(signed_att, expected_did, now_ms=now)
915
+ vm = proof.get("verificationMethod") if isinstance(proof, Mapping) else None
916
+ if not sig_ok and self._pinned_platform_did and isinstance(vm, str) and vm != expected_did:
917
+ try:
918
+ hist = self.key_history(force=True)
919
+ hist_active = ((hist.get("document") or {}).get("activeDid")) if isinstance(hist, Mapping) else None
920
+ if isinstance(hist_active, str) and hist_active != expected_did:
921
+ expected_did = hist_active
922
+ sig_ok = verify_document(signed_att, expected_did, now_ms=now)
923
+ except Exception:
924
+ sig_ok = False
925
+ if not sig_ok:
926
+ raise AgentMediateError(
927
+ 0,
928
+ "INVALID_PLATFORM_SIGNATURE",
929
+ "Honours Roll attestation signature is invalid, expired, or not signed by the active platform DID",
930
+ )
931
+ created = proof.get("created") if isinstance(proof, Mapping) else None
932
+ exp = proof.get("expiresAt") if isinstance(proof, Mapping) else None
933
+ if (
934
+ not isinstance(created, int)
935
+ or isinstance(created, bool)
936
+ or not isinstance(exp, int)
937
+ or isinstance(exp, bool)
938
+ or created != doc.get("issuedAt")
939
+ or created > now + 300_000
940
+ or exp <= created
941
+ or exp - created > 24 * 3_600_000
942
+ ):
943
+ raise AgentMediateError(0, "HONOURS_MISMATCH", "Honours Roll attestation proof timestamps or 24h TTL bounds are invalid")
944
+ if self._expected_environment is not None and doc.get("environment") != self._expected_environment:
945
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"attestation environment {doc.get('environment')} does not match expected {self._expected_environment}")
946
+ if self._expected_rules_hash is not None and doc.get("rulesHash") != self._expected_rules_hash:
947
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"attestation rulesHash {doc.get('rulesHash')} does not match expected {self._expected_rules_hash}")
948
+ agent_ids = doc.get("agentIds")
949
+ entry_agent_ids = entry.get("agentIds")
950
+ same_agents = (
951
+ isinstance(agent_ids, list)
952
+ and isinstance(entry_agent_ids, list)
953
+ and len(agent_ids) == len(entry_agent_ids)
954
+ and all(isinstance(aid, str) and aid == entry_agent_ids[idx] for idx, aid in enumerate(agent_ids))
955
+ )
956
+ if (
957
+ not same_agents
958
+ or doc.get("domain") != entry.get("domain")
959
+ or doc.get("didWeb") != entry.get("didWeb")
960
+ or doc.get("memberSince") != entry.get("memberSince")
961
+ or doc.get("verifiedAt") != entry.get("verifiedAt")
962
+ or doc.get("qualifiedHonoredCount") != entry.get("qualifiedHonoredCount")
963
+ or doc.get("totalHonoredObligations") != entry.get("totalHonoredObligations")
964
+ or doc.get("confirmedByCounterpartyCount") != entry.get("confirmedByCounterpartyCount")
965
+ or doc.get("distinctCounterparties") != entry.get("distinctCounterparties")
966
+ or doc.get("verifiedDomainCounterparties") != entry.get("verifiedDomainCounterparties")
967
+ or doc.get("curedLateCount") != entry.get("curedLateCount")
968
+ or doc.get("fulfilmentRate") != 1
969
+ or entry.get("fulfilmentRate") != 1
970
+ or doc.get("lastHonoredAt") != entry.get("lastHonoredAt")
971
+ ):
972
+ raise AgentMediateError(0, "HONOURS_MISMATCH", "Honours Roll entry disagrees with signedAttestation")
973
+ if len(trimmed) > 512:
974
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll subject {trimmed}")
975
+ if trimmed.startswith("did:key:"):
976
+ if not is_did_key(trimmed):
977
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll subject {trimmed}")
978
+ if trimmed not in agent_ids:
979
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"signedAttestation does not include requested agent {trimmed}")
980
+ elif trimmed.startswith("did:web:"):
981
+ segments = trimmed[len("did:web:") :].split(":")
982
+ if len(segments) != 1 or not segments[0]:
983
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"Honours Roll requires root-domain did:web without path segments, got {trimmed}")
984
+ try:
985
+ parsed = urllib.parse.urlsplit(url_from_did_web(trimmed))
986
+ port = parsed.port
987
+ except ValueError as exc:
988
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid did:web subject {trimmed}") from exc
989
+ if parsed.path != "/.well-known/did.json" or parsed.query != "" or parsed.fragment != "":
990
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid did:web subject {trimmed}")
991
+ raw_host = (parsed.hostname or "").strip("[]").lower().rstrip(".")
992
+ if not raw_host or (_is_ip_host(raw_host) and raw_host not in _LOCAL_HONOURS_HOSTS):
993
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid did:web subject {trimmed}")
994
+ try:
995
+ host = _uts46_to_ascii(raw_host) if not _is_ip_host(raw_host) else raw_host
996
+ except UnicodeError as exc:
997
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid did:web subject {trimmed}") from exc
998
+ expected_domain = f"{host}:{port}" if (port and port != 443) else host
999
+ if not expected_domain or doc.get("domain") != expected_domain or not isinstance(doc.get("didWeb"), str):
1000
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"signedAttestation domain {doc.get('domain')} does not match requested {trimmed}")
1001
+ else:
1002
+ if re.search(r"[/?#@\\\s\x00-\x1f\x7f]", trimmed) or trimmed.startswith("."):
1003
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}")
1004
+ stripped = trimmed.rstrip(".")
1005
+ if not stripped:
1006
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}")
1007
+ try:
1008
+ parsed = urllib.parse.urlsplit(f"https://{stripped}")
1009
+ port = parsed.port
1010
+ except ValueError as exc:
1011
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}") from exc
1012
+ if (
1013
+ not parsed.hostname
1014
+ or parsed.username is not None
1015
+ or parsed.password is not None
1016
+ or parsed.path not in ("", "/")
1017
+ or parsed.query != ""
1018
+ or parsed.fragment != ""
1019
+ ):
1020
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}")
1021
+ raw_host = parsed.hostname.strip("[]").lower().rstrip(".")
1022
+ if not raw_host or raw_host in (".", "..") or (_is_ip_host(raw_host) and raw_host not in _LOCAL_HONOURS_HOSTS):
1023
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}")
1024
+ try:
1025
+ host = _uts46_to_ascii(raw_host) if not _is_ip_host(raw_host) else raw_host
1026
+ except UnicodeError as exc:
1027
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"invalid Honours Roll domain subject {trimmed}") from exc
1028
+ expected_domain = f"{host}:{port}" if (port and port != 443) else host
1029
+ if not expected_domain or doc.get("domain") != expected_domain:
1030
+ raise AgentMediateError(0, "HONOURS_MISMATCH", f"signedAttestation domain {doc.get('domain')} does not match requested {trimmed}")
1031
+ return {**body, "verified": True}
1032
+
1033
+ def _verify_platform_document(self, doc: Mapping[str, Any]) -> bool:
1034
+ inner_doc = doc.get("document") if isinstance(doc, Mapping) else None
1035
+ doc_env = inner_doc.get("environment") if isinstance(inner_doc, Mapping) else None
1036
+ if doc_env == "production" and not self._pinned_platform_did and not self._allow_unpinned_platform_did:
1037
+ raise AgentMediateError(
1038
+ 0,
1039
+ "UNPINNED_PLATFORM_DID",
1040
+ "refusing unpinned TOFU verification for environment=production; pin platform_did out of band",
1041
+ )
1042
+ root_expected_did = self._pinned_platform_did or self.platform()["did"]
1043
+ with self._pending_lock:
1044
+ fast_expected_did = self._verified_active_platform_did or root_expected_did
1045
+ now = self._now_ms()
1046
+ if verify_document(doc, fast_expected_did, now_ms=now):
1047
+ return True
1048
+ proof = doc.get("proof") if isinstance(doc, Mapping) else None
1049
+ vm = proof.get("verificationMethod") if isinstance(proof, Mapping) else None
1050
+ if isinstance(vm, str) and vm != fast_expected_did:
1051
+ try:
1052
+ with self._pending_lock:
1053
+ was_cached = (
1054
+ self._key_history_cache is not None
1055
+ and now - self._key_history_cache["fetched_at"] < _KEY_HISTORY_CACHE_TTL_MS
1056
+ )
1057
+ can_refresh = now - self._key_history_refresh_at >= _KEY_HISTORY_REFRESH_COOLDOWN_MS
1058
+ hist = self.key_history()
1059
+ proof_key_id = proof.get("keyId") if isinstance(proof, Mapping) else None
1060
+ keys = ((hist.get("document") or {}).get("keys")) if isinstance(hist, Mapping) else None
1061
+ has_key = any(
1062
+ isinstance(k, Mapping)
1063
+ and k.get("did") == vm
1064
+ and (proof_key_id is None or k.get("keyId") == proof_key_id)
1065
+ for k in (keys or [])
1066
+ )
1067
+ if not has_key and was_cached and can_refresh:
1068
+ with self._pending_lock:
1069
+ self._key_history_refresh_at = now
1070
+ hist = self.key_history(force=True)
1071
+ with self._pending_lock:
1072
+ min_upd = self._key_history_state["min_updated_at"] or None
1073
+ return bool(
1074
+ verify_document_with_key_history(
1075
+ doc,
1076
+ hist,
1077
+ expected_active_did=root_expected_did,
1078
+ now_ms=now,
1079
+ max_age_ms=DEFAULT_KEY_HISTORY_TTL_MS,
1080
+ min_updated_at=min_upd,
1081
+ ).get("ok")
1082
+ )
1083
+ except Exception:
1084
+ return False
1085
+ return False
1086
+
1087
+ # --- Notifications --------------------------------------------------------
1088
+
1089
+ def register_notifications(
1090
+ self,
1091
+ *,
1092
+ webhook_url: Optional[str] = None,
1093
+ a2a_card_url: Optional[str] = None,
1094
+ email: Optional[str] = None,
1095
+ clear_fields: Sequence[str] = (),
1096
+ idempotency_key: Optional[str] = None,
1097
+ ) -> Dict[str, Any]:
1098
+ body: Dict[str, Any] = {}
1099
+ if webhook_url is not None:
1100
+ body["webhookUrl"] = webhook_url
1101
+ if a2a_card_url is not None:
1102
+ body["a2aCardUrl"] = a2a_card_url
1103
+ if email is not None:
1104
+ body["email"] = email
1105
+ for field_name in clear_fields:
1106
+ body[field_name] = None
1107
+ return self._put("/v1/agents/me/notify", body, idempotency_key=idempotency_key)
1108
+
1109
+ def get_notifications(self) -> Dict[str, Any]:
1110
+ return self._get("/v1/agents/me/notify")
1111
+
1112
+ def update_my_honours(
1113
+ self,
1114
+ opt_in: bool,
1115
+ *,
1116
+ did_web: Optional[str] = None,
1117
+ a2a_card_url: Optional[str] = None,
1118
+ idempotency_key: Optional[str] = None,
1119
+ ) -> Dict[str, Any]:
1120
+ body: Dict[str, Any] = {"optIn": bool(opt_in)}
1121
+ if did_web is not None:
1122
+ body["didWeb"] = did_web
1123
+ if a2a_card_url is not None:
1124
+ body["a2aCardUrl"] = a2a_card_url
1125
+ return self._put("/v1/agents/me/honours", body, idempotency_key=idempotency_key)
1126
+
1127
+ def get_my_honours(self) -> Dict[str, Any]:
1128
+ return self._get("/v1/agents/me/honours")
1129
+
1130
+ # --- Cold-start invites & discovery ---------------------------------------
1131
+
1132
+ def create_invite(
1133
+ self,
1134
+ *,
1135
+ contract_hash: str,
1136
+ summary: str,
1137
+ respondent_id: Optional[str] = None,
1138
+ respondent_contact: Optional[Mapping[str, Any]] = None,
1139
+ webhook_url: Optional[str] = None,
1140
+ ttl_ms: Optional[int] = None,
1141
+ idempotency_key: Optional[str] = None,
1142
+ ) -> Dict[str, Any]:
1143
+ """Send a ``$0.00`` pre-filing mediation invite (``POST /v1/invites``) and verify ``signedInvite`` against the platform DID."""
1144
+ body: Dict[str, Any] = {
1145
+ "contractHash": contract_hash,
1146
+ "summary": summary,
1147
+ }
1148
+ if respondent_id is not None:
1149
+ body["respondentId"] = respondent_id
1150
+ if respondent_contact is not None:
1151
+ body["respondentContact"] = dict(respondent_contact)
1152
+ if webhook_url is not None:
1153
+ body["webhookUrl"] = webhook_url
1154
+ if ttl_ms is not None:
1155
+ body["ttlMs"] = int(ttl_ms)
1156
+ res = self._post("/v1/invites", body, idempotency_key=idempotency_key)
1157
+ signed_invite = res.get("signedInvite")
1158
+ if not isinstance(signed_invite, Mapping):
1159
+ raise AgentMediateError(0, "INVITE_MISMATCH", "invite response is missing signedInvite")
1160
+ doc = self.verify_invite(
1161
+ signed_invite,
1162
+ invite_id=str(res.get("inviteId") or ""),
1163
+ claimant_id=self.did,
1164
+ respondent_id=respondent_id,
1165
+ contract_hash=contract_hash,
1166
+ allow_third_party=True,
1167
+ )
1168
+ if doc.get("inviteUrl") != res.get("inviteUrl"):
1169
+ raise AgentMediateError(0, "INVITE_MISMATCH", "inviteUrl does not match signedInvite.document.inviteUrl")
1170
+ return res
1171
+
1172
+ def get_invite(self, invite_id: str, *, token: Optional[str] = None) -> Dict[str, Any]:
1173
+ """Read mediation invite status (``GET /v1/invites/:id``), optionally passing ``token`` for an unbound cold respondent."""
1174
+ enc = urllib.parse.quote(invite_id, safe="")
1175
+ q = f"?token={urllib.parse.quote(token, safe='')}" if token else ""
1176
+ return self._get(f"/v1/invites/{enc}{q}")
1177
+
1178
+ def accept_invite(
1179
+ self,
1180
+ token: str,
1181
+ *,
1182
+ webhook_url: Optional[str] = None,
1183
+ idempotency_key: Optional[str] = None,
1184
+ ) -> Dict[str, Any]:
1185
+ """Accept a ``$0.00`` mediation invite (``POST /v1/invites/:token/accept``) using your authenticated respondent ``did:key``."""
1186
+ body: Dict[str, Any] = {}
1187
+ if webhook_url is not None:
1188
+ body["webhookUrl"] = webhook_url
1189
+ enc = urllib.parse.quote(token, safe="")
1190
+ return self._post(f"/v1/invites/{enc}/accept", body, idempotency_key=idempotency_key)
1191
+
1192
+ def discover_respondent(
1193
+ self,
1194
+ target: str,
1195
+ *,
1196
+ transport: Optional[TransportLike] = None,
1197
+ resolve_host: Optional[Callable[[str], Sequence[Any]]] = None,
1198
+ timeout_ms: int = 3_000,
1199
+ allow_insecure_http: bool = False,
1200
+ ) -> Dict[str, Any]:
1201
+ """Probe public metadata for a target domain, HTTPS URL, or ``did:web`` before filing a dispute."""
1202
+ with self._pending_lock:
1203
+ plat_did = self._verified_active_platform_did or self._pinned_platform_did
1204
+ return discover_respondent(
1205
+ target,
1206
+ base_url=self.base_url,
1207
+ platform_did=plat_did,
1208
+ expected_environment=self._expected_environment,
1209
+ expected_rules_hash=self._expected_rules_hash,
1210
+ transport=transport,
1211
+ api_transport=self._custom_transport,
1212
+ resolve_host=resolve_host,
1213
+ timeout_ms=timeout_ms,
1214
+ allow_insecure_http=allow_insecure_http,
1215
+ now_ms=self._now_ms,
1216
+ )
1217
+
1218
+ # --- Dispute lifecycle ----------------------------------------------------
1219
+
1220
+ def file_dispute(
1221
+ self,
1222
+ *,
1223
+ respondent_id: str,
1224
+ contract_hash: str,
1225
+ claim: Mapping[str, str],
1226
+ proposed_issues: Sequence[Mapping[str, Any]],
1227
+ mandate: Optional[Mapping[str, Any]] = None,
1228
+ bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1229
+ determination_consent: Optional[bool] = None,
1230
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1231
+ disclose_gap_on_failure: Optional[bool] = None,
1232
+ config: Optional[Mapping[str, Any]] = None,
1233
+ webhook_url: Optional[str] = None,
1234
+ respondent_contact: Optional[Mapping[str, Any]] = None,
1235
+ clause: Optional[Mapping[str, Any]] = None,
1236
+ require_delivery: Optional[bool] = None,
1237
+ invite_id: Optional[str] = None,
1238
+ idempotency_key: Optional[str] = None,
1239
+ ) -> Dict[str, Any]:
1240
+ """File a dispute. Keep ``config["feeMode"] == "FILER_PAYS"`` (the default) for cold respondents so joining costs $0.00 and zero crypto setup."""
1241
+ key = idempotency_key or f"pysdk-{uuid.uuid4()}"
1242
+ scope = {"contractHash": contract_hash, "counterpartyId": respondent_id}
1243
+ fp = (
1244
+ self._mandate_fingerprint(
1245
+ bounds=bounds,
1246
+ determination_consent=determination_consent,
1247
+ determination_bounds=determination_bounds,
1248
+ scope=scope,
1249
+ )
1250
+ if (bounds is not None and mandate is None)
1251
+ else None
1252
+ )
1253
+ pending_mandate: Optional[Dict[str, Any]] = None
1254
+ if fp is not None:
1255
+ with self._pending_lock:
1256
+ pending = self._pending_paid.get(f"POST /v1/disputes {key}")
1257
+ if (
1258
+ pending is not None
1259
+ and self._now_ms() - pending["at"] < _PENDING_PAID_TTL_MS
1260
+ and isinstance(pending.get("mandate"), Mapping)
1261
+ and pending.get("mandateFingerprint") == fp
1262
+ ):
1263
+ pending_mandate = dict(pending["mandate"])
1264
+ resolved_mandate = (
1265
+ pending_mandate
1266
+ if pending_mandate is not None
1267
+ else self._resolve_mandate(
1268
+ mandate=mandate,
1269
+ bounds=bounds,
1270
+ determination_consent=determination_consent,
1271
+ determination_bounds=determination_bounds,
1272
+ scope=scope,
1273
+ idempotency_key=f"file::{key}",
1274
+ )
1275
+ )
1276
+ body: Dict[str, Any] = {
1277
+ "respondentId": respondent_id,
1278
+ "contractHash": contract_hash,
1279
+ "claim": dict(claim),
1280
+ "mandate": resolved_mandate,
1281
+ "proposedIssues": [dict(i) for i in proposed_issues],
1282
+ }
1283
+ if disclose_gap_on_failure is not None:
1284
+ body["discloseGapOnFailure"] = disclose_gap_on_failure
1285
+ if config is not None:
1286
+ body["config"] = dict(config)
1287
+ if webhook_url is not None:
1288
+ body["webhookUrl"] = webhook_url
1289
+ if respondent_contact is not None:
1290
+ body["respondentContact"] = dict(respondent_contact)
1291
+ if clause is not None:
1292
+ body["clause"] = dict(clause)
1293
+ if require_delivery is not None:
1294
+ body["requireDelivery"] = bool(require_delivery)
1295
+ if invite_id is not None:
1296
+ body["inviteId"] = invite_id
1297
+ res = self._post(
1298
+ self._view_path("/v1/disputes"),
1299
+ body,
1300
+ idempotency_key=key,
1301
+ paid_operation="file",
1302
+ mandate_meta={"mandate": resolved_mandate, "fingerprint": fp} if fp is not None else None,
1303
+ )
1304
+ notice = res.get("notice") if isinstance(res, Mapping) else None
1305
+ if notice is not None:
1306
+ if not isinstance(notice, Mapping) or notice.get("signedNotice") is None:
1307
+ raise AgentMediateError(0, "NOTICE_MISMATCH", "filing response included notice metadata without signedNotice")
1308
+ self._verify_filing_notice(
1309
+ notice.get("signedNotice"),
1310
+ dispute_id=str(res.get("disputeId") or ""),
1311
+ respondent_id=respondent_id,
1312
+ contract_hash=contract_hash,
1313
+ notice_url=notice.get("noticeUrl") if "noticeUrl" in notice else None,
1314
+ )
1315
+ return res
1316
+
1317
+ def list_disputes(
1318
+ self,
1319
+ *,
1320
+ status: Optional[str] = None,
1321
+ role: Optional[str] = None,
1322
+ limit: Optional[int] = None,
1323
+ cursor: Optional[str] = None,
1324
+ ) -> Dict[str, Any]:
1325
+ params: Dict[str, str] = {}
1326
+ if status is not None:
1327
+ params["status"] = status
1328
+ if role is not None:
1329
+ params["role"] = role
1330
+ if limit is not None:
1331
+ params["limit"] = str(limit)
1332
+ if cursor is not None:
1333
+ params["cursor"] = cursor
1334
+ qs = urllib.parse.urlencode(params)
1335
+ return self._get(f"/v1/disputes?{qs}" if qs else "/v1/disputes")
1336
+
1337
+ def get_dispute(self, dispute_id: str, *, view: Optional[str] = None) -> Dict[str, Any]:
1338
+ enc = urllib.parse.quote(dispute_id, safe="")
1339
+ return self._get(self._view_path(f"/v1/disputes/{enc}", view=view))
1340
+
1341
+ def events(self, dispute_id: str, *, after: int = 0) -> Dict[str, Any]:
1342
+ enc = urllib.parse.quote(dispute_id, safe="")
1343
+ return self._get(f"/v1/disputes/{enc}/events?after={after}")
1344
+
1345
+ def audit(
1346
+ self,
1347
+ dispute_id: str,
1348
+ *,
1349
+ require_checkpoint: bool = False,
1350
+ require_anchor: bool = False,
1351
+ expected_outcome: Optional[Mapping[str, Any]] = None,
1352
+ ) -> Dict[str, Any]:
1353
+ enc = urllib.parse.quote(dispute_id, safe="")
1354
+ res = self._get(f"/v1/disputes/{enc}/audit")
1355
+ entries = res.get("entries")
1356
+ if not isinstance(entries, list):
1357
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit response entries must be a list")
1358
+ verified = verify_public_audit_chain(entries)
1359
+ if not verified.get("ok"):
1360
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", f"audit chain broken at seq {verified.get('atSeq')}: {verified.get('reason')}")
1361
+ if verified.get("head") != res.get("head"):
1362
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit chain does not end at the reported head")
1363
+ cp = res.get("checkpoint")
1364
+ if (require_checkpoint or require_anchor) and cp is None:
1365
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit response does not include a required transparency checkpoint")
1366
+ if require_anchor and (not isinstance(cp, Mapping) or cp.get("anchor") is None):
1367
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit transparency checkpoint does not include a required Base L2 anchor")
1368
+ if cp is not None:
1369
+ self._verify_checkpoint_envelope(cp, "INVALID_AUDIT_CHAIN")
1370
+ leaf = cp.get("leaf")
1371
+ inc = cp.get("inclusionProof")
1372
+ cp_doc = cp["signedCheckpoint"]["document"]
1373
+ merkle_root = str(cp_doc["merkleRoot"])
1374
+ if not isinstance(leaf, Mapping) or not isinstance(inc, Mapping):
1375
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit checkpoint Merkle inclusion proof failed verification")
1376
+ # Checkpoints are daily: the checkpointed head may be older than `head`, but it must be a point of this
1377
+ # same verified chain (a forked head is rejected).
1378
+ at_checkpoint = next((e for e in entries if isinstance(e, Mapping) and e.get("seq") == leaf.get("auditSeq")), None)
1379
+ if (
1380
+ leaf.get("disputeId") != dispute_id
1381
+ or at_checkpoint is None
1382
+ or at_checkpoint.get("hash") != leaf.get("auditHead")
1383
+ or not verify_checkpoint_inclusion(leaf, inc, merkle_root, expected_total_leaves=cp_doc["disputeCount"])
1384
+ ):
1385
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "audit checkpoint Merkle inclusion proof failed verification")
1386
+ if expected_outcome is not None:
1387
+ out_doc = expected_outcome.get("document") if isinstance(expected_outcome, Mapping) else None
1388
+ if (
1389
+ not isinstance(out_doc, Mapping)
1390
+ or out_doc.get("disputeId") != dispute_id
1391
+ or not isinstance(out_doc.get("auditRoot"), str)
1392
+ or not isinstance(out_doc.get("outcomeHash"), str)
1393
+ ):
1394
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "expected_outcome does not match disputeId or lacks auditRoot/outcomeHash")
1395
+ expected_status = (
1396
+ out_doc.get("executionStatus")
1397
+ if out_doc.get("type") == "agent-mediate/settlement-instruction/v1"
1398
+ else ("UNRESOLVED" if out_doc.get("type") == "agent-mediate/unresolved-certificate/v1" else None)
1399
+ )
1400
+ if not isinstance(expected_status, str):
1401
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", f"expected_outcome carries unsupported type {out_doc.get('type')}")
1402
+ out_entry = next((e for e in entries if e.get("hash") == out_doc.get("auditRoot")), None)
1403
+ if out_entry is None:
1404
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "expected_outcome auditRoot is not present in the verified audit chain")
1405
+ if cp is not None:
1406
+ leaf = cp["leaf"]
1407
+ is_terminal = expected_status in ("HONORED", "BREACH_REPORTED", "UNRESOLVED")
1408
+ if leaf["auditSeq"] > out_entry["seq"] and is_terminal:
1409
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "checkpoint leaf advances beyond a terminal signed outcome")
1410
+ if leaf["auditSeq"] == out_entry["seq"] and (
1411
+ leaf["outcomeHash"] != out_doc["outcomeHash"] or leaf["status"] != expected_status
1412
+ ):
1413
+ raise AgentMediateError(0, "INVALID_AUDIT_CHAIN", "checkpoint leaf outcomeHash/status disagrees with expected_outcome")
1414
+ out: Dict[str, Any] = {"head": res["head"], "entries": res["entries"], "redacted": verified["redacted"]}
1415
+ if cp is not None:
1416
+ out["checkpoint"] = cp
1417
+ return out
1418
+
1419
+ def signatures(
1420
+ self,
1421
+ dispute_id: str,
1422
+ *,
1423
+ strict: bool = True,
1424
+ expected_parties: Optional[Mapping[str, str]] = None,
1425
+ ) -> Dict[str, Any]:
1426
+ enc = urllib.parse.quote(dispute_id, safe="")
1427
+ res = self._get(f"/v1/disputes/{enc}/signatures")
1428
+ raw_sigs = res.get("signatures") if isinstance(res, Mapping) else None
1429
+ if not isinstance(res, Mapping) or res.get("disputeId") != dispute_id or not isinstance(raw_sigs, list):
1430
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signatures response disputeId {(res or {}).get('disputeId') if isinstance(res, Mapping) else None} does not match requested {dispute_id}")
1431
+ party_agents: Dict[str, str] = {}
1432
+ seen_file_dispute = False
1433
+ checked: List[Dict[str, Any]] = []
1434
+
1435
+ for entry in raw_sigs:
1436
+ if not isinstance(entry, Mapping):
1437
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", "malformed signature entry")
1438
+ party = entry.get("party")
1439
+ agent_id = entry.get("agentId")
1440
+ action = entry.get("action")
1441
+ seq_range = entry.get("seqRange")
1442
+ if entry.get("redacted") is True and action == "confidential_action":
1443
+ proof_hash = entry.get("proofHash")
1444
+ valid_confidential_seq_range = seq_range is None or (
1445
+ isinstance(seq_range, list)
1446
+ and len(seq_range) == 2
1447
+ and all(isinstance(x, int) and not isinstance(x, bool) and 0 < x <= _MAX_SAFE_INT for x in seq_range)
1448
+ and seq_range[0] > 1
1449
+ and seq_range[1] >= seq_range[0]
1450
+ )
1451
+ if (
1452
+ party is not None
1453
+ or agent_id is not None
1454
+ or not seen_file_dispute
1455
+ or not valid_confidential_seq_range
1456
+ or not isinstance(proof_hash, str)
1457
+ or not _SHA256_HEX_RE.fullmatch(proof_hash)
1458
+ ):
1459
+ raise AgentMediateError(
1460
+ 0,
1461
+ "INVALID_REQUEST_PROOF",
1462
+ f"signature #{entry.get('id')} (confidential_action) has invalid redacted metadata",
1463
+ )
1464
+ checked.append(dict(entry))
1465
+ continue
1466
+
1467
+ if party not in ("claimant", "respondent") or not is_did_key(agent_id) or not isinstance(action, str):
1468
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signature #{entry.get('id')} has invalid party, agentId, or action")
1469
+ if action == "file_dispute":
1470
+ if party != "claimant" or seen_file_dispute or not isinstance(seq_range, list) or len(seq_range) != 2 or seq_range[0] != 1:
1471
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signature #{entry.get('id')} (file_dispute) has invalid party or sequence binding")
1472
+ seen_file_dispute = True
1473
+ elif action == "join_dispute" and party != "respondent":
1474
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signature #{entry.get('id')} (join_dispute) must belong to respondent")
1475
+
1476
+ if party in party_agents and party_agents[party] != agent_id:
1477
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"party {party} changed agentId across signatures")
1478
+ party_agents[party] = agent_id
1479
+ if "claimant" in party_agents and "respondent" in party_agents and party_agents["claimant"] == party_agents["respondent"]:
1480
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", "claimant and respondent cannot share the same agentId")
1481
+ if expected_parties is not None and expected_parties.get(party) is not None and agent_id != expected_parties.get(party):
1482
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"party {party} agentId {agent_id} does not match expected {expected_parties.get(party)}")
1483
+ if agent_id == self.did and entry.get("redacted") is True:
1484
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"own signature #{entry.get('id')} must not be redacted")
1485
+
1486
+ item = dict(entry)
1487
+ if not entry.get("redacted"):
1488
+ try:
1489
+ verdict = verify_request_proof(
1490
+ entry.get("proof") or {},
1491
+ expected_agent_id=agent_id,
1492
+ expected_proof_hash=entry.get("proofHash"),
1493
+ expected_base_url=self.base_url,
1494
+ expected_dispute_id=dispute_id,
1495
+ expected_action=action,
1496
+ )
1497
+ except Exception as exc:
1498
+ verdict = {"ok": False, "reason": f"malformed proof: {exc}"}
1499
+ ok = bool(verdict.get("ok"))
1500
+ if not ok and strict:
1501
+ raise AgentMediateError(
1502
+ 0,
1503
+ "INVALID_REQUEST_PROOF",
1504
+ f"signature #{entry.get('id')} ({action}) failed verification: {verdict.get('reason')}",
1505
+ )
1506
+ item["verified"] = ok
1507
+ if not ok:
1508
+ item["verifyReason"] = verdict.get("reason")
1509
+ else:
1510
+ proof_hash = entry.get("proofHash")
1511
+ if action != "file_dispute" or not isinstance(proof_hash, str) or not _SHA256_HEX_RE.fullmatch(proof_hash):
1512
+ raise AgentMediateError(
1513
+ 0,
1514
+ "INVALID_REQUEST_PROOF",
1515
+ f"signature #{entry.get('id')} ({action}) has an invalid redacted entry or non-confidential action",
1516
+ )
1517
+ checked.append(item)
1518
+
1519
+ if len(raw_sigs) > 0 and not seen_file_dispute:
1520
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signatures for {dispute_id} are missing the claimant file_dispute entry")
1521
+ if (
1522
+ ("claimant" in party_agents and "respondent" in party_agents and self.did not in (party_agents["claimant"], party_agents["respondent"]))
1523
+ or (
1524
+ "claimant" in party_agents
1525
+ and self.did != party_agents["claimant"]
1526
+ and "respondent" not in party_agents
1527
+ and any(s.get("action") == "confidential_action" for s in checked)
1528
+ )
1529
+ ):
1530
+ raise AgentMediateError(0, "INVALID_REQUEST_PROOF", f"signatures for {dispute_id} do not name this agent ({self.did}) as a party")
1531
+ if expected_parties is not None and (
1532
+ (expected_parties.get("claimant") is not None and "claimant" not in party_agents)
1533
+ or (expected_parties.get("respondent") is not None and "respondent" not in party_agents)
1534
+ ):
1535
+ compact_view = self.get_dispute(dispute_id, view="compact")["view"]
1536
+ actual_parties = (
1537
+ {"claimant": self.did, "respondent": str(compact_view["counterpartId"])}
1538
+ if compact_view.get("you") == "claimant"
1539
+ else {"claimant": str(compact_view["counterpartId"]), "respondent": self.did}
1540
+ )
1541
+ for p_name in ("claimant", "respondent"):
1542
+ if expected_parties.get(p_name) is not None and actual_parties[p_name] != expected_parties.get(p_name):
1543
+ raise AgentMediateError(
1544
+ 0,
1545
+ "INVALID_REQUEST_PROOF",
1546
+ f"party {p_name} agentId {actual_parties[p_name]} does not match expected {expected_parties.get(p_name)}",
1547
+ )
1548
+ return {"disputeId": dispute_id, "signatures": checked}
1549
+
1550
+ def join(
1551
+ self,
1552
+ dispute_id: str,
1553
+ *,
1554
+ mandate: Optional[Mapping[str, Any]] = None,
1555
+ bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1556
+ determination_consent: Optional[bool] = None,
1557
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1558
+ disclose_gap_on_failure: Optional[bool] = None,
1559
+ webhook_url: Optional[str] = None,
1560
+ windows: Optional[Mapping[str, int]] = None,
1561
+ idempotency_key: Optional[str] = None,
1562
+ ) -> Dict[str, Any]:
1563
+ key = idempotency_key or f"pysdk-{uuid.uuid4()}"
1564
+ scope = self._scope_of(dispute_id, idempotency_key=f"join:{key}") if (bounds is not None and mandate is None) else None
1565
+ resolved_mandate = self._resolve_mandate(
1566
+ mandate=mandate,
1567
+ bounds=bounds,
1568
+ determination_consent=determination_consent,
1569
+ determination_bounds=determination_bounds,
1570
+ scope=scope,
1571
+ idempotency_key=f"join:{dispute_id}:{key}",
1572
+ )
1573
+ body: Dict[str, Any] = {"mandate": resolved_mandate}
1574
+ if disclose_gap_on_failure is not None:
1575
+ body["discloseGapOnFailure"] = disclose_gap_on_failure
1576
+ if webhook_url is not None:
1577
+ body["webhookUrl"] = webhook_url
1578
+ if windows is not None:
1579
+ body["windows"] = dict(windows)
1580
+ enc = urllib.parse.quote(dispute_id, safe="")
1581
+ return self._post(self._view_path(f"/v1/disputes/{enc}/join"), body, idempotency_key=key)
1582
+
1583
+ def submit_evidence(
1584
+ self,
1585
+ dispute_id: str,
1586
+ items: Sequence[Mapping[str, Any]],
1587
+ *,
1588
+ idempotency_key: Optional[str] = None,
1589
+ ) -> Dict[str, Any]:
1590
+ payload: List[Dict[str, Any]] = []
1591
+ for raw_item in items:
1592
+ item = dict(raw_item)
1593
+ content = item.pop("content", None)
1594
+ sha = item.get("sha256")
1595
+ if not sha and content is None:
1596
+ raise ValueError(f"evidence {item.get('id')}: provide sha256 or content")
1597
+ item["sha256"] = sha or content_hash(content)
1598
+ payload.append(item)
1599
+ enc = urllib.parse.quote(dispute_id, safe="")
1600
+ return self._post(self._view_path(f"/v1/disputes/{enc}/evidence"), {"items": payload}, idempotency_key=idempotency_key)
1601
+
1602
+ def close_evidence(self, dispute_id: str, *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
1603
+ enc = urllib.parse.quote(dispute_id, safe="")
1604
+ return self._post(self._view_path(f"/v1/disputes/{enc}/evidence/close"), {}, idempotency_key=idempotency_key)
1605
+
1606
+ def confirm_issues(
1607
+ self,
1608
+ dispute_id: str,
1609
+ issues_hash: str,
1610
+ *,
1611
+ mandate: Optional[Mapping[str, Any]] = None,
1612
+ bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1613
+ determination_consent: Optional[bool] = None,
1614
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1615
+ idempotency_key: Optional[str] = None,
1616
+ ) -> Dict[str, Any]:
1617
+ key = idempotency_key or f"pysdk-{uuid.uuid4()}"
1618
+ body: Dict[str, Any] = {"issuesHash": issues_hash}
1619
+ if mandate is not None or bounds is not None:
1620
+ ctx = self._mandate_context_of(dispute_id, idempotency_key=f"confirm:{key}") if (bounds is not None and mandate is None) else None
1621
+ effective_consent, effective_det_bounds = _merge_prior_determination_bounds(
1622
+ bounds=bounds,
1623
+ determination_consent=determination_consent,
1624
+ determination_bounds=determination_bounds,
1625
+ ctx=ctx,
1626
+ )
1627
+ body["mandate"] = self._resolve_mandate(
1628
+ mandate=mandate,
1629
+ bounds=bounds,
1630
+ determination_consent=effective_consent,
1631
+ determination_bounds=effective_det_bounds,
1632
+ scope={"contractHash": ctx["contractHash"], "counterpartyId": ctx["counterpartyId"]} if ctx is not None else None,
1633
+ idempotency_key=f"confirm:{dispute_id}:{key}",
1634
+ min_issued_at=(int(ctx["prevIssuedAt"]) + 1) if (ctx is not None and ctx.get("prevIssuedAt") is not None) else None,
1635
+ min_expires_at=int(ctx["prevExpiresAt"]) if (ctx is not None and ctx.get("prevExpiresAt") is not None) else None,
1636
+ )
1637
+ enc = urllib.parse.quote(dispute_id, safe="")
1638
+ return self._post(self._view_path(f"/v1/disputes/{enc}/issues/confirm"), body, idempotency_key=key)
1639
+
1640
+ def reject_issues(
1641
+ self,
1642
+ dispute_id: str,
1643
+ issues_hash: str,
1644
+ *,
1645
+ adopt_suggested_ids: Optional[Sequence[str]] = None,
1646
+ idempotency_key: Optional[str] = None,
1647
+ ) -> Dict[str, Any]:
1648
+ if not isinstance(issues_hash, str) or len(issues_hash) == 0:
1649
+ raise ValueError("reject_issues requires issues_hash")
1650
+ body: Dict[str, Any] = {"issuesHash": issues_hash}
1651
+ if adopt_suggested_ids is not None:
1652
+ body["adoptSuggestedIds"] = [str(s) for s in adopt_suggested_ids]
1653
+ enc = urllib.parse.quote(dispute_id, safe="")
1654
+ return self._post(self._view_path(f"/v1/disputes/{enc}/issues/reject"), body, idempotency_key=idempotency_key)
1655
+
1656
+ def update_mandate(
1657
+ self,
1658
+ dispute_id: str,
1659
+ *,
1660
+ mandate: Optional[Mapping[str, Any]] = None,
1661
+ bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1662
+ determination_consent: Optional[bool] = None,
1663
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]] = None,
1664
+ idempotency_key: Optional[str] = None,
1665
+ ) -> Dict[str, Any]:
1666
+ """Monotonically widen your principal-signed mandate during BARGAINING or DETERMINATION (v1.2.0/v1.3.0)."""
1667
+ key = idempotency_key or f"pysdk-{uuid.uuid4()}"
1668
+ ctx = self._mandate_context_of(dispute_id, idempotency_key=f"update:{key}") if (bounds is not None and mandate is None) else None
1669
+ effective_consent, effective_det_bounds = _merge_prior_determination_bounds(
1670
+ bounds=bounds,
1671
+ determination_consent=determination_consent,
1672
+ determination_bounds=determination_bounds,
1673
+ ctx=ctx,
1674
+ )
1675
+ resolved = self._resolve_mandate(
1676
+ mandate=mandate,
1677
+ bounds=bounds,
1678
+ determination_consent=effective_consent,
1679
+ determination_bounds=effective_det_bounds,
1680
+ scope={"contractHash": ctx["contractHash"], "counterpartyId": ctx["counterpartyId"]} if ctx is not None else None,
1681
+ idempotency_key=f"update:{dispute_id}:{key}",
1682
+ min_issued_at=(int(ctx["prevIssuedAt"]) + 1) if (ctx is not None and ctx.get("prevIssuedAt") is not None) else None,
1683
+ min_expires_at=int(ctx["prevExpiresAt"]) if (ctx is not None and ctx.get("prevExpiresAt") is not None) else None,
1684
+ )
1685
+ enc = urllib.parse.quote(dispute_id, safe="")
1686
+ return self._post(self._view_path(f"/v1/disputes/{enc}/mandate"), {"mandate": resolved}, idempotency_key=key)
1687
+
1688
+ def submit_offer(
1689
+ self,
1690
+ dispute_id: str,
1691
+ round_num: int,
1692
+ *,
1693
+ offer: Mapping[str, float],
1694
+ private: Optional[Mapping[str, Any]] = None,
1695
+ weights: Optional[Mapping[str, float]] = None,
1696
+ walkaway: Optional[Mapping[str, float]] = None,
1697
+ limits: Optional[Mapping[str, Mapping[str, float]]] = None,
1698
+ proposal_response: Optional[str] = None,
1699
+ idempotency_key: Optional[str] = None,
1700
+ ) -> Dict[str, Any]:
1701
+ if private is not None and (weights is not None or walkaway is not None or limits is not None):
1702
+ raise ValueError("pass either private=... or weights/walkaway/limits, not both")
1703
+ if (weights is None) != (walkaway is None):
1704
+ raise ValueError("weights and walkaway must both be provided together on your first offer")
1705
+ if limits is not None and private is None and weights is None:
1706
+ raise ValueError("limits requires weights and walkaway (or private=...)")
1707
+ body: Dict[str, Any] = {"offer": dict(offer)}
1708
+ if private is not None or (weights is not None and walkaway is not None):
1709
+ priv_dict: Dict[str, Any] = dict(private) if private is not None else {
1710
+ "weights": dict(weights or {}),
1711
+ "walkaway": dict(walkaway or {}),
1712
+ }
1713
+ if limits is not None:
1714
+ priv_dict["limits"] = {k: dict(v) for k, v in limits.items()}
1715
+ body["private"] = priv_dict
1716
+ if proposal_response is not None:
1717
+ body["proposalResponse"] = proposal_response
1718
+ enc = urllib.parse.quote(dispute_id, safe="")
1719
+ return self._post(self._view_path(f"/v1/disputes/{enc}/rounds/{round_num}/offer"), body, idempotency_key=idempotency_key)
1720
+
1721
+ def submit_final_offer(
1722
+ self,
1723
+ dispute_id: str,
1724
+ offer: Mapping[str, float],
1725
+ *,
1726
+ idempotency_key: Optional[str] = None,
1727
+ ) -> Dict[str, Any]:
1728
+ enc = urllib.parse.quote(dispute_id, safe="")
1729
+ return self._post(
1730
+ self._view_path(f"/v1/disputes/{enc}/determination/final-offer"),
1731
+ {"offer": dict(offer)},
1732
+ idempotency_key=idempotency_key,
1733
+ )
1734
+
1735
+ def respond_improvement(
1736
+ self,
1737
+ dispute_id: str,
1738
+ response: str,
1739
+ *,
1740
+ idempotency_key: Optional[str] = None,
1741
+ ) -> Dict[str, Any]:
1742
+ enc = urllib.parse.quote(dispute_id, safe="")
1743
+ return self._post(
1744
+ self._view_path(f"/v1/disputes/{enc}/execution/improvement"),
1745
+ {"response": response},
1746
+ idempotency_key=idempotency_key,
1747
+ )
1748
+
1749
+ def submit_execution_proof(
1750
+ self,
1751
+ dispute_id: str,
1752
+ reference: str,
1753
+ *,
1754
+ idempotency_key: Optional[str] = None,
1755
+ ) -> Dict[str, Any]:
1756
+ enc = urllib.parse.quote(dispute_id, safe="")
1757
+ return self._post(
1758
+ self._view_path(f"/v1/disputes/{enc}/execution/proof"),
1759
+ {"reference": reference},
1760
+ idempotency_key=idempotency_key,
1761
+ )
1762
+
1763
+ def confirm_execution(self, dispute_id: str, *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
1764
+ enc = urllib.parse.quote(dispute_id, safe="")
1765
+ return self._post(self._view_path(f"/v1/disputes/{enc}/execution/confirm"), {}, idempotency_key=idempotency_key)
1766
+
1767
+ def contest_execution(
1768
+ self,
1769
+ dispute_id: str,
1770
+ reason: str,
1771
+ *,
1772
+ idempotency_key: Optional[str] = None,
1773
+ ) -> Dict[str, Any]:
1774
+ enc = urllib.parse.quote(dispute_id, safe="")
1775
+ return self._post(
1776
+ self._view_path(f"/v1/disputes/{enc}/execution/contest"),
1777
+ {"reason": reason},
1778
+ idempotency_key=idempotency_key,
1779
+ )
1780
+
1781
+ def acknowledge_cure(
1782
+ self,
1783
+ dispute_id: str,
1784
+ *,
1785
+ reference: Optional[str] = None,
1786
+ note: Optional[str] = None,
1787
+ idempotency_key: Optional[str] = None,
1788
+ ) -> Dict[str, Any]:
1789
+ body: Dict[str, Any] = {}
1790
+ if reference is not None:
1791
+ body["reference"] = reference
1792
+ if note is not None:
1793
+ body["note"] = note
1794
+ enc = urllib.parse.quote(dispute_id, safe="")
1795
+ return self._post(f"/v1/disputes/{enc}/cure", body, idempotency_key=idempotency_key)
1796
+
1797
+ def withdraw(self, dispute_id: str, *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
1798
+ enc = urllib.parse.quote(dispute_id, safe="")
1799
+ return self._post(self._view_path(f"/v1/disputes/{enc}/withdraw"), {}, idempotency_key=idempotency_key)
1800
+
1801
+ def verify_notice(
1802
+ self,
1803
+ signed_notice: Mapping[str, Any],
1804
+ *,
1805
+ dispute_id: Optional[str] = None,
1806
+ claimant_id: Optional[str] = None,
1807
+ respondent_id: Optional[str] = None,
1808
+ contract_hash: Optional[str] = None,
1809
+ rules_version: Optional[str] = None,
1810
+ allow_third_party: bool = False,
1811
+ ) -> Dict[str, Any]:
1812
+ """Verify a platform-signed Notice of Dispute (`agent-mediate/dispute-notice/v1`) received via `/n/:token`, webhook, A2A card, or email (`PR-L10`, `CR3-SDK-L1`)."""
1813
+ doc = signed_notice.get("document") if isinstance(signed_notice, Mapping) else None
1814
+ if not isinstance(doc, Mapping) or doc.get("type") != "agent-mediate/dispute-notice/v1":
1815
+ raise AgentMediateError(
1816
+ 0,
1817
+ "NOTICE_MISMATCH",
1818
+ f"unexpected notice document.type {(doc or {}).get('type') if isinstance(doc, Mapping) else None}",
1819
+ )
1820
+ if (
1821
+ not isinstance(doc.get("disputeId"), str)
1822
+ or len(doc["disputeId"]) == 0
1823
+ or not is_did_key(doc.get("claimantId"))
1824
+ or not is_did_key(doc.get("respondentId"))
1825
+ or not isinstance(doc.get("contractHash"), str)
1826
+ or not _SHA256_HEX_RE.fullmatch(doc["contractHash"])
1827
+ ):
1828
+ raise AgentMediateError(0, "NOTICE_MISMATCH", "dispute notice document fields are malformed")
1829
+ base_prefix = f"{self.base_url}/"
1830
+ for url_field in ("noticeUrl", "joinEndpoint", "disputeEndpoint", "llmsTxtUrl"):
1831
+ val = doc.get(url_field)
1832
+ if val is not None and (not isinstance(val, str) or not val.startswith(base_prefix)):
1833
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice {url_field} does not start with base_url {base_prefix}")
1834
+ if doc.get("rulesVersion") is not None and (not isinstance(doc.get("rulesVersion"), str) or len(doc["rulesVersion"]) == 0):
1835
+ raise AgentMediateError(0, "NOTICE_MISMATCH", "notice rulesVersion is malformed")
1836
+ if rules_version is not None and doc.get("rulesVersion") != rules_version:
1837
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice rulesVersion {doc.get('rulesVersion')} does not match expected {rules_version}")
1838
+ if dispute_id is not None and doc.get("disputeId") != dispute_id:
1839
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice disputeId {doc.get('disputeId')} does not match expected {dispute_id}")
1840
+ if claimant_id is not None and doc.get("claimantId") != claimant_id:
1841
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice claimantId {doc.get('claimantId')} does not match expected {claimant_id}")
1842
+ expected_respondent = respondent_id if respondent_id is not None else (None if allow_third_party else self.did)
1843
+ if expected_respondent is not None and doc.get("respondentId") != expected_respondent:
1844
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice respondentId {doc.get('respondentId')} does not match expected {expected_respondent}")
1845
+ if contract_hash is not None and doc.get("contractHash") != contract_hash:
1846
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"notice contractHash {doc.get('contractHash')} does not match expected {contract_hash}")
1847
+ if self._expected_environment is not None and doc.get("environment") != self._expected_environment:
1848
+ raise AgentMediateError(
1849
+ 0,
1850
+ "NOTICE_MISMATCH",
1851
+ f"notice environment {doc.get('environment')} does not match expected {self._expected_environment}",
1852
+ )
1853
+ if not self._verify_platform_document(signed_notice):
1854
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", "dispute notice signature failed verification")
1855
+ return dict(doc)
1856
+
1857
+ def verify_invite(
1858
+ self,
1859
+ signed_invite: Mapping[str, Any],
1860
+ *,
1861
+ invite_id: Optional[str] = None,
1862
+ claimant_id: Optional[str] = None,
1863
+ respondent_id: Optional[str] = None,
1864
+ contract_hash: Optional[str] = None,
1865
+ rules_version: Optional[str] = None,
1866
+ allow_third_party: bool = False,
1867
+ ) -> Dict[str, Any]:
1868
+ """Verify a platform-signed Pre-Filing Mediation Invite (`agent-mediate/dispute-invite/v1`) received via `/i/:token`, webhook, A2A card, or email (`CR3-SDK-L1`)."""
1869
+ doc = signed_invite.get("document") if isinstance(signed_invite, Mapping) else None
1870
+ if not isinstance(doc, Mapping) or doc.get("type") != DISPUTE_INVITE_TYPE:
1871
+ raise AgentMediateError(
1872
+ 0,
1873
+ "INVITE_MISMATCH",
1874
+ f"unexpected invite document.type {(doc or {}).get('type') if isinstance(doc, Mapping) else None}",
1875
+ )
1876
+ resp_val = doc.get("respondentId")
1877
+ if (
1878
+ not isinstance(doc.get("inviteId"), str)
1879
+ or len(doc["inviteId"]) == 0
1880
+ or not is_did_key(doc.get("claimantId"))
1881
+ or (resp_val is not None and not is_did_key(resp_val))
1882
+ or not isinstance(doc.get("contractHash"), str)
1883
+ or not _SHA256_HEX_RE.fullmatch(doc["contractHash"])
1884
+ or not isinstance(doc.get("rulesVersion"), str)
1885
+ or len(doc["rulesVersion"]) == 0
1886
+ ):
1887
+ raise AgentMediateError(0, "INVITE_MISMATCH", "dispute invite document fields are malformed")
1888
+ base_prefix = f"{self.base_url}/"
1889
+ for url_field in ("inviteUrl", "acceptEndpoint", "inviteEndpoint"):
1890
+ val = doc.get(url_field)
1891
+ if not isinstance(val, str) or not val.startswith(base_prefix):
1892
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite {url_field} does not start with base_url {base_prefix}")
1893
+ if doc.get("llmsTxtUrl") is not None and (
1894
+ not isinstance(doc.get("llmsTxtUrl"), str) or not str(doc["llmsTxtUrl"]).startswith(base_prefix)
1895
+ ):
1896
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite llmsTxtUrl does not start with base_url {base_prefix}")
1897
+ if rules_version is not None and doc.get("rulesVersion") != rules_version:
1898
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite rulesVersion {doc.get('rulesVersion')} does not match expected {rules_version}")
1899
+ if invite_id is not None and doc.get("inviteId") != invite_id:
1900
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite inviteId {doc.get('inviteId')} does not match expected {invite_id}")
1901
+ if claimant_id is not None and doc.get("claimantId") != claimant_id:
1902
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite claimantId {doc.get('claimantId')} does not match expected {claimant_id}")
1903
+ if respondent_id is not None:
1904
+ if resp_val != respondent_id:
1905
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite respondentId {resp_val} does not match expected {respondent_id}")
1906
+ elif not allow_third_party and resp_val is not None and resp_val != self.did:
1907
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite respondentId {resp_val} does not match this agent ({self.did})")
1908
+ if contract_hash is not None and doc.get("contractHash") != contract_hash:
1909
+ raise AgentMediateError(0, "INVITE_MISMATCH", f"invite contractHash {doc.get('contractHash')} does not match expected {contract_hash}")
1910
+ if self._expected_environment is not None and doc.get("environment") != self._expected_environment:
1911
+ raise AgentMediateError(
1912
+ 0,
1913
+ "INVITE_MISMATCH",
1914
+ f"invite environment {doc.get('environment')} does not match expected {self._expected_environment}",
1915
+ )
1916
+ if not self._verify_platform_document(signed_invite):
1917
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", "dispute invite signature failed verification")
1918
+ return dict(doc)
1919
+
1920
+ def _verify_filing_notice(
1921
+ self,
1922
+ signed_notice: Any,
1923
+ *,
1924
+ dispute_id: str,
1925
+ respondent_id: str,
1926
+ contract_hash: str,
1927
+ notice_url: Optional[Any] = None,
1928
+ ) -> None:
1929
+ doc = signed_notice.get("document") if isinstance(signed_notice, Mapping) else None
1930
+ if not isinstance(doc, Mapping) or doc.get("type") != "agent-mediate/dispute-notice/v1":
1931
+ raise AgentMediateError(
1932
+ 0,
1933
+ "NOTICE_MISMATCH",
1934
+ f"unexpected notice document.type {(doc or {}).get('type') if isinstance(doc, Mapping) else None}",
1935
+ )
1936
+ if (
1937
+ doc.get("disputeId") != dispute_id
1938
+ or doc.get("claimantId") != self.did
1939
+ or doc.get("respondentId") != respondent_id
1940
+ or doc.get("contractHash") != contract_hash
1941
+ ):
1942
+ raise AgentMediateError(0, "NOTICE_MISMATCH", "filing notice document fields do not match the filed dispute")
1943
+ if (notice_url is not None or doc.get("noticeUrl") is not None) and doc.get("noticeUrl") != notice_url:
1944
+ raise AgentMediateError(0, "NOTICE_MISMATCH", "filing noticeUrl does not match signedNotice.document.noticeUrl")
1945
+ base_prefix = f"{self.base_url}/"
1946
+ for url_field in ("noticeUrl", "joinEndpoint", "disputeEndpoint", "llmsTxtUrl"):
1947
+ val = doc.get(url_field)
1948
+ if val is not None and (not isinstance(val, str) or not val.startswith(base_prefix)):
1949
+ raise AgentMediateError(0, "NOTICE_MISMATCH", f"filing notice {url_field} does not start with base_url {base_prefix}")
1950
+ if self._expected_environment is not None and doc.get("environment") != self._expected_environment:
1951
+ raise AgentMediateError(
1952
+ 0,
1953
+ "NOTICE_MISMATCH",
1954
+ f"filing notice environment {doc.get('environment')} does not match expected {self._expected_environment}",
1955
+ )
1956
+ if not self._verify_platform_document(signed_notice):
1957
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", "filing notice signature failed verification")
1958
+
1959
+ def outcome(self, dispute_id: str) -> Dict[str, Any]:
1960
+ enc = urllib.parse.quote(dispute_id, safe="")
1961
+ doc = self._get(f"/v1/disputes/{enc}/outcome")
1962
+ if not self._verify_platform_document(doc):
1963
+ raise AgentMediateError(0, "INVALID_PLATFORM_SIGNATURE", "outcome signature does not verify against the platform did")
1964
+ payload = doc.get("document") or {}
1965
+ doc_type = payload.get("type")
1966
+ if doc_type not in ("agent-mediate/settlement-instruction/v1", "agent-mediate/unresolved-certificate/v1"):
1967
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", f"unexpected outcome document.type {doc_type}")
1968
+ if payload.get("disputeId") != dispute_id:
1969
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", f"outcome disputeId {payload.get('disputeId')} does not match requested {dispute_id}")
1970
+ if self._expected_environment is not None and payload.get("environment") != self._expected_environment:
1971
+ raise AgentMediateError(
1972
+ 0,
1973
+ "OUTCOME_MISMATCH",
1974
+ f"outcome environment {payload.get('environment')} does not match expected {self._expected_environment}",
1975
+ )
1976
+ if self._expected_rules_hash is not None and payload.get("rulesHash") != self._expected_rules_hash:
1977
+ raise AgentMediateError(
1978
+ 0,
1979
+ "OUTCOME_MISMATCH",
1980
+ f"outcome rulesHash {payload.get('rulesHash')} does not match expected {self._expected_rules_hash}",
1981
+ )
1982
+ parties = payload.get("parties") or {}
1983
+ claimant_agent = (parties.get("claimant") or {}).get("agentId")
1984
+ respondent_agent = (parties.get("respondent") or {}).get("agentId")
1985
+ if self.did not in (claimant_agent, respondent_agent):
1986
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", f"outcome for {dispute_id} does not name this agent ({self.did}) as a party")
1987
+ outcome_hash = payload.get("outcomeHash")
1988
+ audit_root = payload.get("auditRoot")
1989
+ if not isinstance(outcome_hash, str) or not _SHA256_HEX_RE.fullmatch(outcome_hash):
1990
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", "outcome document is missing a valid 64-hex outcomeHash")
1991
+ if not isinstance(audit_root, str) or not _SHA256_HEX_RE.fullmatch(audit_root):
1992
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", "outcome document is missing a valid 64-hex auditRoot")
1993
+ if doc_type == "agent-mediate/settlement-instruction/v1":
1994
+ terms = payload.get("terms")
1995
+ method = payload.get("method")
1996
+ settled_at = payload.get("settledAt")
1997
+ rounds_completed = payload.get("roundsCompleted")
1998
+ exec_status = payload.get("executionStatus")
1999
+ if (
2000
+ payload.get("status") != "SETTLED"
2001
+ or exec_status not in ("EXECUTION_PENDING", "HONORED", "BREACH_REPORTED")
2002
+ or not isinstance(method, str)
2003
+ or method not in _SETTLEMENT_METHODS
2004
+ or not isinstance(settled_at, int)
2005
+ or isinstance(settled_at, bool)
2006
+ or abs(settled_at) > _MAX_SAFE_INT
2007
+ or not isinstance(rounds_completed, int)
2008
+ or isinstance(rounds_completed, bool)
2009
+ or rounds_completed < 0
2010
+ or rounds_completed > _MAX_SAFE_INT
2011
+ or not isinstance(terms, Mapping)
2012
+ or isinstance(terms, (list, tuple))
2013
+ or compute_terms_hash(terms) != payload.get("termsHash")
2014
+ or compute_outcome_hash(
2015
+ {
2016
+ "kind": "SETTLED",
2017
+ "method": method,
2018
+ "terms": terms,
2019
+ "at": settled_at,
2020
+ "roundsCompleted": rounds_completed,
2021
+ },
2022
+ exec_status,
2023
+ )
2024
+ != outcome_hash
2025
+ ):
2026
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", "settlement instruction outcomeHash, termsHash, or status is inconsistent")
2027
+ else:
2028
+ issued_at = payload.get("issuedAt")
2029
+ rounds_completed = payload.get("roundsCompleted")
2030
+ if (
2031
+ payload.get("status") != "UNRESOLVED"
2032
+ or not isinstance(payload.get("reason"), str)
2033
+ or not isinstance(issued_at, int)
2034
+ or isinstance(issued_at, bool)
2035
+ or abs(issued_at) > _MAX_SAFE_INT
2036
+ or not isinstance(rounds_completed, int)
2037
+ or isinstance(rounds_completed, bool)
2038
+ or rounds_completed < 0
2039
+ or rounds_completed > _MAX_SAFE_INT
2040
+ or compute_outcome_hash(
2041
+ {
2042
+ "kind": "UNRESOLVED",
2043
+ "reason": payload.get("reason"),
2044
+ "at": issued_at,
2045
+ "roundsCompleted": rounds_completed,
2046
+ },
2047
+ "UNRESOLVED",
2048
+ )
2049
+ != outcome_hash
2050
+ ):
2051
+ raise AgentMediateError(0, "OUTCOME_MISMATCH", "unresolved certificate outcomeHash or status is inconsistent")
2052
+ return doc
2053
+
2054
+ def wait_for(
2055
+ self,
2056
+ dispute_id: str,
2057
+ predicate: Callable[[Mapping[str, Any]], bool],
2058
+ *,
2059
+ timeout_ms: int = 60_000,
2060
+ interval_ms: int = 1000,
2061
+ view: Optional[str] = None,
2062
+ ) -> Dict[str, Any]:
2063
+ deadline = self._now_ms() + timeout_ms
2064
+ while True:
2065
+ res = self.get_dispute(dispute_id, view=view)
2066
+ if predicate(res["view"]) or self._now_ms() >= deadline:
2067
+ return res
2068
+ time.sleep(interval_ms / 1000.0)
2069
+
2070
+ def wait_for_turn(
2071
+ self,
2072
+ dispute_id: str,
2073
+ *,
2074
+ timeout_ms: int = 60_000,
2075
+ interval_ms: int = 1000,
2076
+ view: Optional[str] = None,
2077
+ ) -> Dict[str, Any]:
2078
+ """Poll until it is your turn to act (`view['nextActions'][0] != 'wait_for_change'`) or the timeout passes."""
2079
+ return self.wait_for(
2080
+ dispute_id,
2081
+ lambda v: bool(v.get("nextActions")) and v["nextActions"][0] != "wait_for_change",
2082
+ timeout_ms=timeout_ms,
2083
+ interval_ms=interval_ms,
2084
+ view=view,
2085
+ )
2086
+
2087
+ @staticmethod
2088
+ def verify_webhook(
2089
+ *,
2090
+ url: str,
2091
+ headers: Mapping[str, str],
2092
+ body: str,
2093
+ platform_did: str,
2094
+ now_ms: Optional[int] = None,
2095
+ agent_id: Optional[str] = None,
2096
+ allow_unbound_invite: bool = False,
2097
+ dispute_id: Optional[str] = None,
2098
+ invite_id: Optional[str] = None,
2099
+ key_history: Optional[Mapping[str, Any]] = None,
2100
+ ) -> Dict[str, Any]:
2101
+ resolved_now_ms = now_ms if now_ms is not None else int(time.time() * 1000)
2102
+ verified = verify_request(
2103
+ method="POST",
2104
+ target_uri=url,
2105
+ headers=headers,
2106
+ body=body,
2107
+ now_ms=resolved_now_ms,
2108
+ expect_tag=WEBHOOK_SIGNATURE_TAG,
2109
+ )
2110
+ if not verified.get("ok"):
2111
+ return {"ok": False, "reason": verified.get("reason")}
2112
+ if verified.get("keyid") != platform_did:
2113
+ if key_history is None:
2114
+ return {"ok": False, "reason": "signed by an unexpected key"}
2115
+ kh = verify_key_history(
2116
+ key_history,
2117
+ expected_active_did=platform_did,
2118
+ now_ms=resolved_now_ms,
2119
+ max_age_ms=DEFAULT_KEY_HISTORY_TTL_MS,
2120
+ )
2121
+ if not kh.get("ok"):
2122
+ return {"ok": False, "reason": f"key_history invalid: {kh.get('reason')}"}
2123
+ hist_doc = (key_history.get("document") or {}) if isinstance(key_history, Mapping) else {}
2124
+ keys = hist_doc.get("keys")
2125
+ hist = next((k for k in (keys or []) if isinstance(k, Mapping) and k.get("did") == verified.get("keyid")), None)
2126
+ allowed_status = (
2127
+ hist is not None
2128
+ and (
2129
+ hist.get("status") == "retired"
2130
+ or (hist.get("status") == "active" and verified.get("keyid") == hist_doc.get("activeDid"))
2131
+ )
2132
+ )
2133
+ created_sec = int(verified["created"])
2134
+ if (
2135
+ hist is None
2136
+ or not allowed_status
2137
+ or hist.get("compromisedAfter") is not None
2138
+ or hist.get("revokedAt") is not None
2139
+ or (int(hist["validFrom"]) // 1000) > created_sec
2140
+ or (hist.get("validUntil") is not None and created_sec > (int(hist["validUntil"]) // 1000))
2141
+ ):
2142
+ return {"ok": False, "reason": "signed by an unexpected key"}
2143
+ try:
2144
+ event = loads_jcs_json(body)
2145
+ except Exception:
2146
+ return {"ok": False, "reason": "body is not JSON"}
2147
+ if not isinstance(event, Mapping):
2148
+ return {"ok": False, "reason": "body is not a JSON object"}
2149
+ if dispute_id is not None and event.get("disputeId") != dispute_id:
2150
+ return {"ok": False, "reason": "event is for another dispute"}
2151
+ if invite_id is not None and event.get("inviteId") != invite_id:
2152
+ return {"ok": False, "reason": "event is for another invite"}
2153
+ recipient = event.get("recipient")
2154
+ recipient_agent = recipient.get("agentId") if isinstance(recipient, Mapping) else None
2155
+ if agent_id is not None and recipient_agent != agent_id:
2156
+ is_unbound_invite = (
2157
+ allow_unbound_invite is True
2158
+ and event.get("type") == "DISPUTE_INVITE"
2159
+ and recipient_agent is None
2160
+ )
2161
+ if not is_unbound_invite:
2162
+ return {"ok": False, "reason": "event is addressed to another agent"}
2163
+ return {"ok": True, "event": event, "nonce": verified["nonce"], "created": verified["created"]}
2164
+
2165
+ # --- Internal transport ---------------------------------------------------
2166
+
2167
+ def _backoff(self, attempt: int, res: Optional[HttpResponse] = None) -> bool:
2168
+ if attempt >= self._max_retries:
2169
+ return False
2170
+ wait_sec = _parse_retry_after_seconds(res.headers.get("retry-after"), self._now_ms()) if res is not None else 0.0
2171
+ time.sleep(wait_sec if wait_sec > 0 else 0.25 * (2**attempt))
2172
+ return True
2173
+
2174
+ def _get_public(
2175
+ self,
2176
+ path: str,
2177
+ *,
2178
+ error_code: str = "HTTP_ERROR",
2179
+ error_detail: Optional[str] = None,
2180
+ ) -> Dict[str, Any]:
2181
+ attempt = 0
2182
+ while True:
2183
+ try:
2184
+ res = self._transport("GET", f"{self.base_url}{path}", {}, None)
2185
+ except AgentMediateError:
2186
+ raise
2187
+ except Exception as err:
2188
+ if self._backoff(attempt):
2189
+ attempt += 1
2190
+ continue
2191
+ raise AgentMediateError(0, "NETWORK_ERROR", str(err)) from err
2192
+
2193
+ if 300 <= res.status < 400:
2194
+ raise AgentMediateError(res.status, "UNEXPECTED_REDIRECT", f"refusing HTTP {res.status} redirect from {path}")
2195
+
2196
+ if (res.status == 429 or res.status >= 500) and self._backoff(attempt, res):
2197
+ attempt += 1
2198
+ continue
2199
+
2200
+ if len(res.body.encode("utf-8")) > _MAX_RESPONSE_BYTES:
2201
+ raise AgentMediateError(res.status, "RESPONSE_TOO_LARGE", f"response body exceeds {_MAX_RESPONSE_BYTES} bytes")
2202
+
2203
+ try:
2204
+ parsed_any: Any = loads_jcs_json(res.body) if res.body else {}
2205
+ except Exception:
2206
+ parsed_any = None
2207
+
2208
+ if res.status < 200 or res.status >= 300:
2209
+ parsed_err = parsed_any if isinstance(parsed_any, Mapping) else {}
2210
+ code = (
2211
+ str(parsed_err["code"])
2212
+ if error_code == "HTTP_ERROR" and isinstance(parsed_err.get("code"), str)
2213
+ else error_code
2214
+ )
2215
+ detail = (
2216
+ str(parsed_err["detail"])
2217
+ if isinstance(parsed_err.get("detail"), str)
2218
+ else (error_detail or f"could not read {path}")
2219
+ )
2220
+ raise AgentMediateError(res.status, code, detail, parsed_any)
2221
+ if not isinstance(parsed_any, dict):
2222
+ raise AgentMediateError(res.status, error_code, error_detail or f"expected JSON object from {path}", parsed_any)
2223
+ return parsed_any
2224
+
2225
+ def _mandate_fingerprint(
2226
+ self,
2227
+ *,
2228
+ bounds: Optional[Mapping[str, Mapping[str, float]]],
2229
+ determination_consent: Optional[bool],
2230
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]],
2231
+ scope: Optional[Mapping[str, str]],
2232
+ ) -> str:
2233
+ return canonical_json(
2234
+ {
2235
+ "baseUrl": self.base_url,
2236
+ "agentId": self.did,
2237
+ "bounds": {k: dict(v) for k, v in bounds.items()} if bounds is not None else None,
2238
+ "determinationConsent": determination_consent,
2239
+ "determinationBounds": {k: dict(v) for k, v in determination_bounds.items()} if determination_bounds is not None else None,
2240
+ "scope": dict(scope) if scope is not None else None,
2241
+ }
2242
+ )
2243
+
2244
+ def _resolve_mandate(
2245
+ self,
2246
+ *,
2247
+ mandate: Optional[Mapping[str, Any]],
2248
+ bounds: Optional[Mapping[str, Mapping[str, float]]],
2249
+ determination_consent: Optional[bool],
2250
+ determination_bounds: Optional[Mapping[str, Mapping[str, float]]],
2251
+ scope: Optional[Mapping[str, str]],
2252
+ idempotency_key: Optional[str] = None,
2253
+ min_issued_at: Optional[int] = None,
2254
+ min_expires_at: Optional[int] = None,
2255
+ ) -> Dict[str, Any]:
2256
+ if mandate is not None:
2257
+ if determination_consent is not None and bool(mandate.get("determinationConsent") is True) != determination_consent:
2258
+ raise ValueError("determination_consent must be signed inside mandate.determinationConsent when providing a pre-signed mandate")
2259
+ if determination_bounds is not None:
2260
+ raise ValueError("determination_bounds must be signed inside mandate.determinationBounds when providing a pre-signed mandate")
2261
+ return dict(mandate)
2262
+ if bounds is not None:
2263
+ now = self._now_ms()
2264
+ fingerprint = self._mandate_fingerprint(
2265
+ bounds=bounds,
2266
+ determination_consent=determination_consent,
2267
+ determination_bounds=determination_bounds,
2268
+ scope=scope,
2269
+ )
2270
+ if idempotency_key:
2271
+ with self._pending_lock:
2272
+ cached = self._mandate_cache.get(idempotency_key)
2273
+ if (
2274
+ cached is not None
2275
+ and cached["fingerprint"] == fingerprint
2276
+ and now - cached["at"] < _PENDING_PAID_TTL_MS
2277
+ and int(cached["mandate"]["expiresAt"]) > now + 60_000
2278
+ and (min_issued_at is None or int(cached["mandate"]["issuedAt"]) >= int(min_issued_at))
2279
+ and (min_expires_at is None or int(cached["mandate"]["expiresAt"]) >= int(min_expires_at))
2280
+ ):
2281
+ return dict(cached["mandate"])
2282
+ created = self.mandate(
2283
+ bounds,
2284
+ scope=scope,
2285
+ determination_consent=determination_consent,
2286
+ determination_bounds=determination_bounds,
2287
+ min_issued_at=min_issued_at,
2288
+ min_expires_at=min_expires_at,
2289
+ )
2290
+ if idempotency_key:
2291
+ with self._pending_lock:
2292
+ if idempotency_key not in self._mandate_cache and len(self._mandate_cache) >= _PENDING_PAID_MAX:
2293
+ self._mandate_cache.pop(next(iter(self._mandate_cache)), None)
2294
+ self._mandate_cache[idempotency_key] = {"fingerprint": fingerprint, "mandate": created, "at": now}
2295
+ return created
2296
+ raise ValueError("provide mandate or bounds")
2297
+
2298
+ def _mandate_context_of(self, dispute_id: str, *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
2299
+ cache_key = f"{dispute_id}:{idempotency_key}" if idempotency_key else None
2300
+ if cache_key is not None:
2301
+ with self._pending_lock:
2302
+ cached = self._scope_cache.get(cache_key)
2303
+ if cached is not None and self._now_ms() - cached["at"] < _PENDING_PAID_TTL_MS:
2304
+ return {k: v for k, v in cached.items() if k != "at"}
2305
+ view = self.get_dispute(dispute_id, view="compact")["view"]
2306
+ ym = view.get("yourMandate")
2307
+ ctx: Dict[str, Any] = {
2308
+ "contractHash": str(view["contractHash"]),
2309
+ "counterpartyId": str(view["counterpartId"]),
2310
+ }
2311
+ if isinstance(ym, Mapping):
2312
+ if isinstance(ym.get("issuedAt"), int) and not isinstance(ym.get("issuedAt"), bool):
2313
+ ctx["prevIssuedAt"] = int(ym["issuedAt"])
2314
+ if isinstance(ym.get("expiresAt"), int) and not isinstance(ym.get("expiresAt"), bool):
2315
+ ctx["prevExpiresAt"] = int(ym["expiresAt"])
2316
+ if isinstance(ym.get("determinationConsent"), bool):
2317
+ ctx["prevDeterminationConsent"] = bool(ym["determinationConsent"])
2318
+ if isinstance(ym.get("bounds"), Mapping):
2319
+ ctx["prevBounds"] = {str(k): dict(v) for k, v in ym["bounds"].items() if isinstance(v, Mapping)}
2320
+ if isinstance(ym.get("determinationBounds"), Mapping):
2321
+ ctx["prevDeterminationBounds"] = {str(k): dict(v) for k, v in ym["determinationBounds"].items() if isinstance(v, Mapping)}
2322
+ if cache_key is not None:
2323
+ with self._pending_lock:
2324
+ if cache_key not in self._scope_cache and len(self._scope_cache) >= _PENDING_PAID_MAX:
2325
+ self._scope_cache.pop(next(iter(self._scope_cache)), None)
2326
+ self._scope_cache[cache_key] = {**ctx, "at": self._now_ms()}
2327
+ return ctx
2328
+
2329
+ def _scope_of(self, dispute_id: str, *, idempotency_key: Optional[str] = None) -> Dict[str, str]:
2330
+ ctx = self._mandate_context_of(dispute_id, idempotency_key=idempotency_key)
2331
+ return {"contractHash": str(ctx["contractHash"]), "counterpartyId": str(ctx["counterpartyId"])}
2332
+
2333
+ def _verified_platform_pay_to(self, info: Mapping[str, Any]) -> Optional[str]:
2334
+ fees = info.get("fees") if isinstance(info.get("fees"), Mapping) else None
2335
+ raw_pay_to = fees.get("payTo") if isinstance(fees, Mapping) and isinstance(fees.get("payTo"), str) else None
2336
+ if not raw_pay_to:
2337
+ return None
2338
+ with self._pending_lock:
2339
+ cached_pay_to = self._verified_pay_to
2340
+ if cached_pay_to is not None and cached_pay_to.lower() == raw_pay_to.lower():
2341
+ return cached_pay_to
2342
+ expected_did = self._pinned_platform_did or str(info.get("did") or "")
2343
+ try:
2344
+ card = self._get_public("/.well-known/agent-card.json", error_detail="could not read /.well-known/agent-card.json")
2345
+ except AgentMediateError as err:
2346
+ raise PaymentPolicyError(f"could not verify /.well-known/agent-card.json for payTo: {err}") from err
2347
+ if not verify_agent_card_signature(card, expected_did):
2348
+ raise PaymentPolicyError("/.well-known/agent-card.json failed platform signature verification")
2349
+ norm_base = self.base_url.rstrip("/")
2350
+
2351
+ def _check_origin(candidate: Any, label: str) -> None:
2352
+ if isinstance(candidate, str) and candidate.rstrip("/") != norm_base:
2353
+ raise PaymentPolicyError(
2354
+ f"/.well-known/agent-card.json {label} ({candidate}) does not match base_url ({norm_base})"
2355
+ )
2356
+
2357
+ _check_origin(card.get("url") if isinstance(card, Mapping) else None, "url")
2358
+ provider = card.get("provider") if isinstance(card, Mapping) else None
2359
+ _check_origin(provider.get("url") if isinstance(provider, Mapping) else None, "provider.url")
2360
+ caps = card.get("capabilities") if isinstance(card, Mapping) else None
2361
+ exts = caps.get("extensions") if isinstance(caps, Mapping) and isinstance(caps.get("extensions"), list) else []
2362
+ rest_ext = next((ext for ext in exts if isinstance(ext, Mapping) and ext.get("uri") == "urn:agent-mediate:ext:rest-api:v1"), None)
2363
+ rest_params = rest_ext.get("params") if isinstance(rest_ext, Mapping) and isinstance(rest_ext.get("params"), Mapping) else None
2364
+ _check_origin(rest_params.get("baseUrl") if isinstance(rest_params, Mapping) else None, "rest-api baseUrl")
2365
+ try:
2366
+ expected_did_web: Optional[str] = did_web_from_url(norm_base)
2367
+ except Exception:
2368
+ expected_did_web = None
2369
+ sigs = card.get("signatures") if isinstance(card, Mapping) else None
2370
+ if expected_did_web is not None and isinstance(sigs, list):
2371
+ for sig_entry in sigs:
2372
+ prot = sig_entry.get("protected") if isinstance(sig_entry, Mapping) else None
2373
+ if not isinstance(prot, str):
2374
+ continue
2375
+ try:
2376
+ pad = "=" * ((4 - (len(prot) % 4)) % 4)
2377
+ hdr = loads_jcs_json(base64.urlsafe_b64decode(prot + pad).decode("utf-8"))
2378
+ kid = hdr.get("kid") if isinstance(hdr, Mapping) else None
2379
+ if isinstance(kid, str) and kid.startswith("did:web:") and kid.split("#", 1)[0] != expected_did_web:
2380
+ raise PaymentPolicyError(
2381
+ f"/.well-known/agent-card.json JWS kid ({kid}) does not match expected {expected_did_web}"
2382
+ )
2383
+ except PaymentPolicyError:
2384
+ raise
2385
+ except Exception:
2386
+ pass
2387
+ fee_ext = next((ext for ext in exts if isinstance(ext, Mapping) and ext.get("uri") == "urn:agent-mediate:ext:x402-fees:v1"), None)
2388
+ params = fee_ext.get("params") if isinstance(fee_ext, Mapping) and isinstance(fee_ext.get("params"), Mapping) else None
2389
+ signed_pay_to = params.get("payTo") if isinstance(params, Mapping) and isinstance(params.get("payTo"), str) else None
2390
+ if not signed_pay_to or signed_pay_to.lower() != raw_pay_to.lower():
2391
+ raise PaymentPolicyError(
2392
+ f"/v1/platform fees.payTo ({raw_pay_to}) does not match signed /.well-known/agent-card.json payTo ({signed_pay_to})"
2393
+ )
2394
+ with self._pending_lock:
2395
+ self._verified_pay_to = signed_pay_to
2396
+ return signed_pay_to
2397
+
2398
+ def _get(self, path: str) -> Dict[str, Any]:
2399
+ return self._request("GET", path)
2400
+
2401
+ def _post(
2402
+ self,
2403
+ path: str,
2404
+ body: Mapping[str, Any],
2405
+ *,
2406
+ idempotency_key: Optional[str] = None,
2407
+ paid_operation: Optional[str] = None,
2408
+ mandate_meta: Optional[Mapping[str, Any]] = None,
2409
+ ) -> Dict[str, Any]:
2410
+ return self._request(
2411
+ "POST",
2412
+ path,
2413
+ body=body,
2414
+ idempotency_key=idempotency_key or f"pysdk-{uuid.uuid4()}",
2415
+ paid_operation=paid_operation,
2416
+ mandate_meta=mandate_meta,
2417
+ )
2418
+
2419
+ def _put(self, path: str, body: Mapping[str, Any], *, idempotency_key: Optional[str] = None) -> Dict[str, Any]:
2420
+ return self._request("PUT", path, body=body, idempotency_key=idempotency_key or f"pysdk-{uuid.uuid4()}")
2421
+
2422
+ def _request(
2423
+ self,
2424
+ method: str,
2425
+ path: str,
2426
+ *,
2427
+ body: Optional[Mapping[str, Any]] = None,
2428
+ idempotency_key: Optional[str] = None,
2429
+ paid_operation: Optional[str] = None,
2430
+ mandate_meta: Optional[Mapping[str, Any]] = None,
2431
+ ) -> Dict[str, Any]:
2432
+ raw_str = "" if body is None else json.dumps(body, separators=(",", ":"))
2433
+ payment_sig: Optional[str] = None
2434
+ attempt = 0
2435
+ # CR-SDK-M1: a retry of a paid call that failed ambiguously after paying resends the identical request + payment.
2436
+ pending_key = f"{method} {path.split('?')[0]} {idempotency_key}" if idempotency_key and paid_operation else None
2437
+ if pending_key is not None:
2438
+ with self._pending_lock:
2439
+ prior = self._pending_paid.get(pending_key)
2440
+ if prior is not None and self._now_ms() - prior["at"] < _PENDING_PAID_TTL_MS:
2441
+ if body is not None and canonical_json(body) != canonical_json(loads_jcs_json(prior["raw"])):
2442
+ raise AgentMediateError(
2443
+ 422,
2444
+ "IDEMPOTENCY_CONFLICT",
2445
+ "Idempotency-Key has a pending payment for a different request body",
2446
+ idempotency_key=idempotency_key,
2447
+ payment_sent=True,
2448
+ )
2449
+ path, raw_str, payment_sig = prior["path"], prior["raw"], prior["payment"]
2450
+ elif prior is not None:
2451
+ self._pending_paid.pop(pending_key, None)
2452
+ raw_bytes = raw_str.encode("utf-8") if raw_str else None
2453
+
2454
+ def fail(status: int, code: str, message: str, err_body: Any = None) -> AgentMediateError:
2455
+ # CR3-PY-M1 & CR3-SDK-M3: 422 RESPONDENT_UNREACHABLE aborts before x402 settlement ($0.00 charged);
2456
+ # mark payment_sent=False and release the authorization so its budget reclaims after validBefore + 60s.
2457
+ unsettled_abort = code == "RESPONDENT_UNREACHABLE"
2458
+ if unsettled_abort and payment_sig is not None and self._payer is not None:
2459
+ release_fn = getattr(self._payer, "release_unsettled", None)
2460
+ if callable(release_fn):
2461
+ release_fn(payment_sig)
2462
+ paid = payment_sig is not None and not unsettled_abort
2463
+ if pending_key is not None:
2464
+ with self._pending_lock:
2465
+ if paid and (status == 0 or status == 429 or status >= 500 or code in _AMBIGUOUS_PAYMENT_CODES):
2466
+ if pending_key not in self._pending_paid and len(self._pending_paid) >= _PENDING_PAID_MAX:
2467
+ self._pending_paid.pop(next(iter(self._pending_paid)), None)
2468
+ existing = self._pending_paid.get(pending_key)
2469
+ entry_data: Dict[str, Any] = {"path": path, "raw": raw_str, "payment": payment_sig, "at": self._now_ms()}
2470
+ if mandate_meta is not None:
2471
+ entry_data["mandate"] = dict(mandate_meta["mandate"])
2472
+ entry_data["mandateFingerprint"] = str(mandate_meta["fingerprint"])
2473
+ elif isinstance(existing, Mapping) and "mandate" in existing and "mandateFingerprint" in existing:
2474
+ entry_data["mandate"] = existing["mandate"]
2475
+ entry_data["mandateFingerprint"] = existing["mandateFingerprint"]
2476
+ self._pending_paid[pending_key] = entry_data
2477
+ else:
2478
+ self._pending_paid.pop(pending_key, None)
2479
+ suffix = (
2480
+ f' (a payment authorisation was already sent: retry with idempotency_key "{idempotency_key}" to avoid a second charge)'
2481
+ if idempotency_key and paid
2482
+ else ""
2483
+ )
2484
+ return AgentMediateError(status, code, message + suffix, err_body, idempotency_key=idempotency_key, payment_sent=paid)
2485
+
2486
+ while True:
2487
+ headers: Dict[str, str] = {}
2488
+ if raw_str:
2489
+ headers["content-type"] = "application/json"
2490
+ if idempotency_key:
2491
+ headers["idempotency-key"] = idempotency_key
2492
+ sig_headers = sign_request(
2493
+ method=method,
2494
+ target_uri=self.base_url + path,
2495
+ headers=headers,
2496
+ body=raw_str if raw_str else None,
2497
+ key=self.agent_key,
2498
+ created=self._now_ms() // 1000,
2499
+ nonce=str(uuid.uuid4()),
2500
+ )
2501
+ headers.update(sig_headers)
2502
+ if payment_sig:
2503
+ headers["payment-signature"] = payment_sig
2504
+
2505
+ try:
2506
+ res = self._transport(method, self.base_url + path, headers, raw_bytes)
2507
+ except AgentMediateError as err:
2508
+ raise fail(err.status, err.code, str(err), err.body) from err
2509
+ except Exception as err:
2510
+ if self._backoff(attempt):
2511
+ attempt += 1
2512
+ continue
2513
+ raise fail(0, "NETWORK_ERROR", str(err)) from err
2514
+
2515
+ if 300 <= res.status < 400:
2516
+ raise fail(res.status, "UNEXPECTED_REDIRECT", f"refusing HTTP {res.status} redirect from {path}")
2517
+
2518
+ if len(res.body.encode("utf-8")) > _MAX_RESPONSE_BYTES:
2519
+ raise fail(res.status, "RESPONSE_TOO_LARGE", f"response body exceeds {_MAX_RESPONSE_BYTES} bytes")
2520
+
2521
+ try:
2522
+ parsed_any: Any = loads_jcs_json(res.body) if res.body else {}
2523
+ except Exception:
2524
+ parsed_any = None
2525
+ parsed: Dict[str, Any] = parsed_any if isinstance(parsed_any, dict) else {}
2526
+
2527
+ if res.status == 402 and parsed.get("code") == "PAYMENT_REQUIRED" and not payment_sig:
2528
+ pr_hdr = res.headers.get("payment-required")
2529
+ try:
2530
+ challenge = json.loads(base64.b64decode(pr_hdr).decode("utf-8")) if pr_hdr else (parsed.get("paymentRequired") or {})
2531
+ except Exception:
2532
+ raise fail(402, "MALFORMED_PAYMENT_REQUIRED", "the payment-required header is not valid base64 JSON", parsed) from None
2533
+ if not isinstance(challenge, Mapping):
2534
+ raise fail(402, "MALFORMED_PAYMENT_REQUIRED", "the 402 response carries no payment challenge", parsed)
2535
+ if not paid_operation:
2536
+ raise fail(402, "UNEXPECTED_PAYMENT_REQUEST", f"{method} {path} is not a paid operation; refusing to pay", parsed)
2537
+ if self._payer is None:
2538
+ raise PaymentRequiredError(challenge, parsed, idempotency_key=idempotency_key)
2539
+ info = self.platform()
2540
+ fees = info.get("fees") if isinstance(info.get("fees"), Mapping) else {}
2541
+ accepts = challenge.get("accepts")
2542
+ # CR-SDK-L6: enforce out-of-band platform_did pinning on Base mainnet even when a custom payer omits .network.
2543
+ is_mainnet = (
2544
+ getattr(self._payer, "network", None) == BASE_MAINNET
2545
+ or fees.get("network") == BASE_MAINNET
2546
+ or (isinstance(accepts, Sequence) and any(isinstance(a, Mapping) and a.get("network") == BASE_MAINNET for a in accepts))
2547
+ )
2548
+ if is_mainnet and not self._pinned_platform_did:
2549
+ raise PaymentPolicyError("on Base mainnet, platform_did must be pinned out of band")
2550
+ expected_pay_to = self._verified_platform_pay_to(info)
2551
+ payment_sig = self._payer.pay(challenge, operation=paid_operation, expected_pay_to=expected_pay_to)
2552
+ continue
2553
+
2554
+ if (res.status == 429 or res.status >= 500) and self._backoff(attempt, res):
2555
+ attempt += 1
2556
+ continue
2557
+
2558
+ if res.status < 200 or res.status >= 300:
2559
+ raise fail(
2560
+ res.status,
2561
+ str(parsed.get("code") or "HTTP_ERROR"),
2562
+ str(parsed.get("detail") or f"HTTP {res.status}"),
2563
+ parsed_any,
2564
+ )
2565
+ if not isinstance(parsed_any, dict):
2566
+ raise fail(res.status, "HTTP_ERROR", f"expected JSON object from {path}", parsed_any)
2567
+ if pending_key is not None:
2568
+ with self._pending_lock:
2569
+ self._pending_paid.pop(pending_key, None)
2570
+ return parsed_any
2571
+
2572
+
2573
+ # --- Out-of-band respondent discovery (`CR3-SDK-H1`, `CR3-MCP-H1`, `CR3-SDK-M1`, `CR3-PY-M1`) ---
2574
+
2575
+ _MAX_DISCOVERY_BYTES = 128 * 1024
2576
+ _SIMPLE_EMAIL_RE = re.compile(r"^[^\s@<>,\"';:\\]+@[^\s@<>,\"';:\\]+\.[^\s@<>,\"';:\\]+$")
2577
+ _DISCOVERY_BLOCKED_SUFFIXES = (".localhost", ".local", ".internal", ".home.arpa", ".lan", ".intranet", ".corp", ".private")
2578
+ _DISCOVERY_BLOCKED_NAMES = frozenset({"localhost", "metadata.google.internal", "metadata", "instance-data"})
2579
+ _DISCOVERY_V4_BLOCKED = tuple(
2580
+ ipaddress.ip_network(cidr)
2581
+ for cidr in (
2582
+ "0.0.0.0/8",
2583
+ "10.0.0.0/8",
2584
+ "100.64.0.0/10",
2585
+ "127.0.0.0/8",
2586
+ "169.254.0.0/16",
2587
+ "172.16.0.0/12",
2588
+ "192.0.0.0/24",
2589
+ "192.0.2.0/24",
2590
+ "192.88.99.0/24",
2591
+ "192.168.0.0/16",
2592
+ "198.18.0.0/15",
2593
+ "198.51.100.0/24",
2594
+ "203.0.113.0/24",
2595
+ "224.0.0.0/4",
2596
+ "240.0.0.0/4",
2597
+ )
2598
+ )
2599
+
2600
+
2601
+ def is_public_ip_address(ip: str) -> bool:
2602
+ """Return True iff ``ip`` is a publicly routable global-unicast IPv4 or IPv6 address."""
2603
+ if not isinstance(ip, str) or not ip:
2604
+ return False
2605
+ cleaned = ip.split("%", 1)[0] if ":" in ip else ip
2606
+ try:
2607
+ addr = ipaddress.ip_address(cleaned)
2608
+ except ValueError:
2609
+ return False
2610
+ if isinstance(addr, ipaddress.IPv4Address):
2611
+ return not any(addr in net for net in _DISCOVERY_V4_BLOCKED)
2612
+ val = int(addr)
2613
+ h0 = (val >> 112) & 0xFFFF
2614
+ h1 = (val >> 96) & 0xFFFF
2615
+ if (h0 & 0xE000) != 0x2000:
2616
+ return False
2617
+ if h0 == 0x2001 and h1 < 0x0200:
2618
+ return False
2619
+ if h0 == 0x2001 and h1 == 0x0DB8:
2620
+ return False
2621
+ if h0 == 0x2002:
2622
+ return False
2623
+ if h0 == 0x3FFF and h1 < 0x1000:
2624
+ return False
2625
+ return True
2626
+
2627
+
2628
+ def _is_loopback_discovery_host(hostname: str) -> bool:
2629
+ h = hostname.strip("[]").lower()
2630
+ return h in ("localhost", "127.0.0.1", "::1")
2631
+
2632
+
2633
+ def _is_internal_or_ip_discovery_host(hostname: str) -> bool:
2634
+ h = hostname.strip("[]").lower().rstrip(".")
2635
+ if not h or ":" in h:
2636
+ return True
2637
+ if _is_ip_host(h) or re.fullmatch(r"^\d{1,3}(?:\.\d{1,3}){3}$", h) or re.fullmatch(r"^[0-9.]+$", h) or h.startswith("0x"):
2638
+ return True
2639
+ if "." not in h:
2640
+ return True
2641
+ if h in _DISCOVERY_BLOCKED_NAMES or any(h.endswith(s) for s in _DISCOVERY_BLOCKED_SUFFIXES):
2642
+ return True
2643
+ return False
2644
+
2645
+
2646
+ def _origin_of_url(raw: str) -> Optional[str]:
2647
+ try:
2648
+ u = urllib.parse.urlsplit(raw)
2649
+ port = u.port
2650
+ except ValueError:
2651
+ return None
2652
+ scheme = u.scheme.lower()
2653
+ if scheme not in ("http", "https") or not u.hostname or u.username is not None or u.password is not None:
2654
+ return None
2655
+ raw_host = u.hostname.strip("[]").lower().rstrip(".")
2656
+ if not raw_host:
2657
+ return None
2658
+ if ":" in raw_host:
2659
+ host_fmt = f"[{raw_host}]"
2660
+ elif _is_ip_host(raw_host):
2661
+ host_fmt = raw_host
2662
+ else:
2663
+ try:
2664
+ host_fmt = _uts46_to_ascii(raw_host)
2665
+ except UnicodeError:
2666
+ return None
2667
+ default_port = 443 if scheme == "https" else 80
2668
+ port_suffix = f":{port}" if (port is not None and port != default_port) else ""
2669
+ return f"{scheme}://{host_fmt}{port_suffix}"
2670
+
2671
+
2672
+ def _normalize_discovery_target(
2673
+ target: str,
2674
+ allow_insecure_http: bool,
2675
+ ) -> tuple[str, str, bool, Optional[str], str]:
2676
+ trimmed = target.strip()
2677
+ if not trimmed:
2678
+ raise ValueError("target must be a non-empty domain, URL, or did:web")
2679
+ if trimmed.startswith("did:web:"):
2680
+ raw_doc_url = url_from_did_web(trimmed)
2681
+ parsed = urllib.parse.urlsplit(raw_doc_url)
2682
+ raw_host = (parsed.hostname or "").strip("[]").lower().rstrip(".")
2683
+ loopback = _is_loopback_discovery_host(raw_host)
2684
+ if loopback:
2685
+ if not allow_insecure_http:
2686
+ raise ValueError("target must be a public domain name")
2687
+ else:
2688
+ if parsed.scheme.lower() != "https":
2689
+ raise ValueError("target URL must use https://")
2690
+ if parsed.port is not None and parsed.port != 443:
2691
+ raise ValueError("target URL must use default https port 443")
2692
+ if _is_internal_or_ip_discovery_host(raw_host):
2693
+ raise ValueError("target must be a public domain name")
2694
+ clean_host = raw_host if (_is_ip_host(raw_host) or loopback) else _uts46_to_ascii(raw_host)
2695
+ origin = _origin_of_url(raw_doc_url)
2696
+ if not origin:
2697
+ raise ValueError("invalid did:web target")
2698
+ did_doc_url = f"{origin}{parsed.path or '/.well-known/did.json'}"
2699
+ return origin, clean_host, loopback, trimmed, did_doc_url
2700
+
2701
+ with_scheme = trimmed if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", trimmed) else f"https://{trimmed}"
2702
+ parsed = urllib.parse.urlsplit(with_scheme)
2703
+ if parsed.username is not None or parsed.password is not None:
2704
+ raise ValueError("target URL must not contain credentials")
2705
+ if not parsed.hostname:
2706
+ raise ValueError("target must be a valid domain or URL")
2707
+ raw_host = parsed.hostname.strip("[]").lower().rstrip(".")
2708
+ loopback = _is_loopback_discovery_host(raw_host)
2709
+ scheme = parsed.scheme.lower()
2710
+ if loopback:
2711
+ if not allow_insecure_http:
2712
+ raise ValueError("target must be a public domain name")
2713
+ if scheme not in ("http", "https"):
2714
+ raise ValueError(f"unsupported target protocol {scheme}:")
2715
+ else:
2716
+ if scheme != "https":
2717
+ raise ValueError("target URL must use https://")
2718
+ if parsed.port is not None and parsed.port != 443:
2719
+ raise ValueError("target URL must use default https port 443")
2720
+ if _is_internal_or_ip_discovery_host(raw_host):
2721
+ raise ValueError("target must be a public domain name")
2722
+ clean_host = raw_host if (_is_ip_host(raw_host) or loopback) else _uts46_to_ascii(raw_host)
2723
+ origin = _origin_of_url(with_scheme)
2724
+ if not origin:
2725
+ raise ValueError("invalid target URL")
2726
+ return origin, clean_host, loopback, None, f"{origin}/.well-known/did.json"
2727
+
2728
+
2729
+ def _default_resolve_discovery_host(hostname: str) -> List[tuple[str, int]]:
2730
+ infos = socket.getaddrinfo(hostname, None, type=socket.SOCK_STREAM)
2731
+ seen: List[tuple[str, int]] = []
2732
+ for family, _socktype, _proto, _canon, sockaddr in infos:
2733
+ addr = str(sockaddr[0])
2734
+ fam = 6 if family == socket.AF_INET6 else 4
2735
+ if (addr, fam) not in seen:
2736
+ seen.append((addr, fam))
2737
+ return seen
2738
+
2739
+
2740
+ def _transport_get_bounded(
2741
+ transport: TransportLike,
2742
+ url: str,
2743
+ accept: str,
2744
+ ) -> Optional[HttpResponse]:
2745
+ try:
2746
+ res = transport("GET", url, {"accept": accept}, None)
2747
+ except Exception:
2748
+ return None
2749
+ if res.status < 200 or res.status >= 300:
2750
+ return None
2751
+ try:
2752
+ declared = int(res.headers.get("content-length") or "0")
2753
+ if declared > _MAX_DISCOVERY_BYTES:
2754
+ return None
2755
+ except ValueError:
2756
+ pass
2757
+ if len(res.body.encode("utf-8")) > _MAX_DISCOVERY_BYTES:
2758
+ return None
2759
+ return res
2760
+
2761
+
2762
+ def _pinned_socket_get_bounded(
2763
+ url: str,
2764
+ accept: str,
2765
+ timeout_sec: float,
2766
+ pins: Optional[Sequence[tuple[str, int]]],
2767
+ ) -> Optional[HttpResponse]:
2768
+ u = urllib.parse.urlsplit(url)
2769
+ scheme = u.scheme.lower()
2770
+ if scheme not in ("http", "https") or not u.hostname:
2771
+ return None
2772
+ hostname = u.hostname.strip("[]")
2773
+ clean_sni = hostname.rstrip(".")
2774
+ try:
2775
+ sni_host = _uts46_to_ascii(clean_sni) if (clean_sni and not _is_ip_host(clean_sni)) else clean_sni
2776
+ except UnicodeError:
2777
+ sni_host = clean_sni
2778
+ port = u.port or (443 if scheme == "https" else 80)
2779
+ target_path = (u.path or "/") + (f"?{u.query}" if u.query else "")
2780
+ host_header = f"[{hostname}]" if ":" in hostname else (sni_host or hostname)
2781
+ if u.port is not None and u.port != (443 if scheme == "https" else 80):
2782
+ host_header = f"{host_header}:{u.port}"
2783
+
2784
+ candidates: Sequence[Optional[tuple[str, int]]] = list(pins[:2]) if pins else [None]
2785
+ for idx, pin in enumerate(candidates):
2786
+ conn: Optional[http.client.HTTPConnection] = None
2787
+ sock: Optional[socket.socket] = None
2788
+ received_headers = False
2789
+ try:
2790
+ if pin is not None:
2791
+ pin_addr, pin_family = pin
2792
+ af = socket.AF_INET6 if pin_family == 6 else socket.AF_INET
2793
+ raw_sock = socket.socket(af, socket.SOCK_STREAM)
2794
+ raw_sock.settimeout(timeout_sec)
2795
+ raw_sock.connect((pin_addr, port))
2796
+ if scheme == "https":
2797
+ ctx = ssl.create_default_context()
2798
+ sock = ctx.wrap_socket(raw_sock, server_hostname=sni_host or hostname)
2799
+ else:
2800
+ sock = raw_sock
2801
+ conn = http.client.HTTPConnection(hostname, port=port, timeout=timeout_sec)
2802
+ conn.sock = sock
2803
+ else:
2804
+ if scheme == "https":
2805
+ conn = http.client.HTTPSConnection(hostname, port=port, timeout=timeout_sec)
2806
+ else:
2807
+ conn = http.client.HTTPConnection(hostname, port=port, timeout=timeout_sec)
2808
+ conn.request("GET", target_path, headers={"Host": host_header, "Accept": accept, "Connection": "close"})
2809
+ resp = conn.getresponse()
2810
+ received_headers = True
2811
+ if resp.status < 200 or resp.status >= 300:
2812
+ return None
2813
+ headers = {k.lower(): v for k, v in resp.getheaders()}
2814
+ try:
2815
+ if int(headers.get("content-length") or "0") > _MAX_DISCOVERY_BYTES:
2816
+ return None
2817
+ except ValueError:
2818
+ pass
2819
+ raw_bytes = resp.read(_MAX_DISCOVERY_BYTES + 1)
2820
+ if len(raw_bytes) > _MAX_DISCOVERY_BYTES:
2821
+ return None
2822
+ return HttpResponse(status=resp.status, headers=headers, body=raw_bytes.decode("utf-8"))
2823
+ except Exception:
2824
+ if idx + 1 < len(candidates) and not received_headers:
2825
+ continue
2826
+ return None
2827
+ finally:
2828
+ if conn is not None:
2829
+ try:
2830
+ conn.close()
2831
+ except Exception:
2832
+ pass
2833
+ elif sock is not None:
2834
+ try:
2835
+ sock.close()
2836
+ except Exception:
2837
+ pass
2838
+ return None
2839
+
2840
+
2841
+ def _parse_link_header_agent_card(link_header: Optional[str], expected_origin: str) -> Optional[str]:
2842
+ if not link_header or len(link_header) > 4096:
2843
+ return None
2844
+ for part in link_header.split(","):
2845
+ url_match = re.search(r"<([^>\s]{1,1024})>", part)
2846
+ rel_match = re.search(r';\s*rel\s*=\s*(?:"([^"]*)"|([^\s;]+))', part, re.IGNORECASE)
2847
+ if not url_match or not rel_match:
2848
+ continue
2849
+ rel_tokens = [t for t in (rel_match.group(1) or rel_match.group(2) or "").lower().split() if t]
2850
+ if "agent-card" not in rel_tokens and "https://a2a-protocol.org/rel/agent-card" not in rel_tokens:
2851
+ continue
2852
+ resolved = urllib.parse.urljoin(f"{expected_origin}/", url_match.group(1))
2853
+ if _origin_of_url(resolved) == expected_origin:
2854
+ return resolved
2855
+ return None
2856
+
2857
+
2858
+ def _extract_did_methods_from_did_doc(
2859
+ doc: Mapping[str, Any],
2860
+ expected_did_web: Optional[str],
2861
+ ) -> tuple[List[str], Dict[str, str]]:
2862
+ candidates: List[str] = []
2863
+ method_by_id: Dict[str, str] = {}
2864
+ aka = doc.get("alsoKnownAs")
2865
+ if isinstance(aka, list):
2866
+ for item in aka:
2867
+ if isinstance(item, str) and is_did_key(item) and item not in candidates:
2868
+ candidates.append(item)
2869
+ vms = doc.get("verificationMethod")
2870
+ if isinstance(vms, list):
2871
+ for vm in vms:
2872
+ if not isinstance(vm, Mapping):
2873
+ continue
2874
+ resolved_did: Optional[str] = None
2875
+ jwk = vm.get("publicKeyJwk")
2876
+ if isinstance(jwk, Mapping):
2877
+ try:
2878
+ derived = did_key_from_ed25519_jwk(jwk)
2879
+ if derived and is_did_key(derived):
2880
+ resolved_did = derived
2881
+ except Exception:
2882
+ pass
2883
+ if resolved_did is None and isinstance(vm.get("publicKeyMultibase"), str):
2884
+ maybe_did = f"did:key:{vm['publicKeyMultibase']}"
2885
+ if is_did_key(maybe_did):
2886
+ resolved_did = maybe_did
2887
+ if resolved_did:
2888
+ if resolved_did not in candidates:
2889
+ candidates.append(resolved_did)
2890
+ vm_id = vm.get("id")
2891
+ if isinstance(vm_id, str) and vm_id:
2892
+ norm_id = f"{expected_did_web}{vm_id}" if (vm_id.startswith("#") and expected_did_web) else vm_id
2893
+ method_by_id[norm_id] = resolved_did
2894
+ return candidates, method_by_id
2895
+
2896
+
2897
+ def _extract_did_candidates_from_card(
2898
+ card: Mapping[str, Any],
2899
+ did_doc_methods: Optional[Mapping[str, str]],
2900
+ expected_did_web: Optional[str],
2901
+ ) -> List[str]:
2902
+ candidates: List[str] = []
2903
+ caps = card.get("capabilities")
2904
+ exts = caps.get("extensions") if isinstance(caps, Mapping) else None
2905
+ if isinstance(exts, list):
2906
+ for ext in exts:
2907
+ params = ext.get("params") if isinstance(ext, Mapping) else None
2908
+ if not isinstance(params, Mapping):
2909
+ continue
2910
+ for key_name in ("agentId", "did", "didKey", "respondentId"):
2911
+ val = params.get(key_name)
2912
+ if isinstance(val, str) and is_did_key(val) and val not in candidates:
2913
+ candidates.append(val)
2914
+ sigs = card.get("signatures")
2915
+ if isinstance(sigs, list):
2916
+ for sig in sigs:
2917
+ prot = sig.get("protected") if isinstance(sig, Mapping) else None
2918
+ if not isinstance(prot, str):
2919
+ continue
2920
+ try:
2921
+ pad = "=" * ((4 - (len(prot) % 4)) % 4)
2922
+ hdr = json.loads(base64.urlsafe_b64decode(prot + pad).decode("utf-8"))
2923
+ if not isinstance(hdr, Mapping):
2924
+ continue
2925
+ kid = hdr.get("kid")
2926
+ if isinstance(kid, str):
2927
+ if is_did_key(kid) and kid not in candidates:
2928
+ candidates.append(kid)
2929
+ elif did_doc_methods:
2930
+ norm_kid = f"{expected_did_web}{kid}" if (kid.startswith("#") and expected_did_web) else kid
2931
+ mapped = did_doc_methods.get(norm_kid)
2932
+ if mapped and is_did_key(mapped) and mapped not in candidates:
2933
+ candidates.append(mapped)
2934
+ jwk = hdr.get("jwk")
2935
+ if isinstance(jwk, Mapping):
2936
+ derived = did_key_from_ed25519_jwk(jwk)
2937
+ if derived and is_did_key(derived) and derived not in candidates:
2938
+ candidates.append(derived)
2939
+ except Exception:
2940
+ pass
2941
+ return candidates
2942
+
2943
+
2944
+ def _agent_card_matches_origin(
2945
+ card: Mapping[str, Any],
2946
+ expected_origin: str,
2947
+ allowed_did_webs: set[str],
2948
+ has_custom_same_origin_webhook: bool,
2949
+ ) -> bool:
2950
+ has_positive_claim = has_custom_same_origin_webhook
2951
+
2952
+ def same_origin_url(raw: Any) -> bool:
2953
+ return isinstance(raw, str) and _origin_of_url(raw) == expected_origin
2954
+
2955
+ if "url" in card and card.get("url") is not None:
2956
+ if not same_origin_url(card.get("url")):
2957
+ return False
2958
+ has_positive_claim = True
2959
+ if "supportedInterfaces" in card and card.get("supportedInterfaces") is not None:
2960
+ ifaces = card.get("supportedInterfaces")
2961
+ if not isinstance(ifaces, list):
2962
+ return False
2963
+ for iface in ifaces:
2964
+ if not isinstance(iface, Mapping):
2965
+ return False
2966
+ if "url" in iface and iface.get("url") is not None:
2967
+ if not same_origin_url(iface.get("url")):
2968
+ return False
2969
+ has_positive_claim = True
2970
+ provider = card.get("provider")
2971
+ if isinstance(provider, Mapping) and "url" in provider and provider.get("url") is not None:
2972
+ if not same_origin_url(provider.get("url")):
2973
+ return False
2974
+ has_positive_claim = True
2975
+ sigs = card.get("signatures")
2976
+ if isinstance(sigs, list):
2977
+ for sig in sigs:
2978
+ prot = sig.get("protected") if isinstance(sig, Mapping) else None
2979
+ if not isinstance(prot, str):
2980
+ continue
2981
+ try:
2982
+ pad = "=" * ((4 - (len(prot) % 4)) % 4)
2983
+ hdr = json.loads(base64.urlsafe_b64decode(prot + pad).decode("utf-8"))
2984
+ if not isinstance(hdr, Mapping):
2985
+ return False
2986
+ if "jku" in hdr and hdr.get("jku") is not None:
2987
+ if not same_origin_url(hdr.get("jku")):
2988
+ return False
2989
+ has_positive_claim = True
2990
+ kid = hdr.get("kid")
2991
+ if isinstance(kid, str) and kid.startswith("did:web:"):
2992
+ kid_did_web = kid.split("#", 1)[0]
2993
+ if kid_did_web not in allowed_did_webs:
2994
+ return False
2995
+ has_positive_claim = True
2996
+ except Exception:
2997
+ return False
2998
+ return has_positive_claim
2999
+
3000
+
3001
+ def _extract_standard_a2a_rpc_url(card: Mapping[str, Any], expected_origin: str) -> Optional[str]:
3002
+ ifaces = card.get("supportedInterfaces")
3003
+ if isinstance(ifaces, list):
3004
+ for iface in ifaces:
3005
+ if not isinstance(iface, Mapping) or not isinstance(iface.get("url"), str):
3006
+ continue
3007
+ binding = str(iface.get("protocolBinding") or "JSONRPC").strip().upper()
3008
+ if binding not in ("JSONRPC", "HTTP+JSONRPC"):
3009
+ continue
3010
+ if _origin_of_url(iface["url"]) == expected_origin:
3011
+ return iface["url"]
3012
+ if isinstance(card.get("url"), str):
3013
+ transport = str(card.get("preferredTransport") or "JSONRPC").strip().upper()
3014
+ if transport in ("JSONRPC", "HTTP+JSONRPC") and _origin_of_url(card["url"]) == expected_origin:
3015
+ return card["url"]
3016
+ return None
3017
+
3018
+
3019
+ def _parse_security_txt_email(text: str) -> Optional[str]:
3020
+ for raw_line in text.splitlines():
3021
+ line = raw_line.strip()
3022
+ if not line or line.startswith("#"):
3023
+ continue
3024
+ m = re.match(r"^contact\s*:\s*(.+)$", line, re.IGNORECASE)
3025
+ if not m:
3026
+ continue
3027
+ raw_val = m.group(1).strip()
3028
+ email_addr = raw_val[7:].split("?", 1)[0].strip() if raw_val.lower().startswith("mailto:") else raw_val
3029
+ if len(email_addr) <= 254 and _SIMPLE_EMAIL_RE.fullmatch(email_addr):
3030
+ return email_addr
3031
+ return None
3032
+
3033
+
3034
+ def discover_respondent(
3035
+ target: str,
3036
+ *,
3037
+ base_url: Optional[str] = None,
3038
+ platform_did: Optional[str] = None,
3039
+ expected_environment: Optional[str] = None,
3040
+ expected_rules_hash: Optional[str] = None,
3041
+ transport: Optional[TransportLike] = None,
3042
+ api_transport: Optional[TransportLike] = None,
3043
+ resolve_host: Optional[Callable[[str], Sequence[Any]]] = None,
3044
+ timeout_ms: int = 3_000,
3045
+ allow_insecure_http: bool = False,
3046
+ now_ms: Optional[Callable[[], int]] = None,
3047
+ ) -> Dict[str, Any]:
3048
+ """
3049
+ Out-of-band respondent discovery helper matching TypeScript ``discoverRespondent`` (``CR3-SDK-H1``, ``CR3-MCP-H1``, ``CR3-SDK-M1``, ``CR3-PY-M1``, ``M-2``).
3050
+ """
3051
+ timeout_sec = max(0.1, float(timeout_ms) / 1000.0)
3052
+ clock = now_ms or (lambda: int(time.time() * 1000))
3053
+ origin, domain, is_loopback, initial_did_web, did_doc_url = _normalize_discovery_target(target, allow_insecure_http)
3054
+
3055
+ vetted_pins: Optional[List[tuple[str, int]]] = None
3056
+ if not is_loopback and (transport is None or resolve_host is not None):
3057
+ try:
3058
+ raw_resolved = resolve_host(domain) if resolve_host is not None else _default_resolve_discovery_host(domain)
3059
+ except Exception as exc:
3060
+ raise ValueError("target host could not be resolved") from exc
3061
+ if not raw_resolved:
3062
+ raise ValueError("target host could not be resolved")
3063
+ parsed_pins: List[tuple[str, int]] = []
3064
+ for item in raw_resolved:
3065
+ if isinstance(item, str):
3066
+ addr_str = item
3067
+ elif isinstance(item, Mapping) and isinstance(item.get("address"), str):
3068
+ addr_str = str(item["address"])
3069
+ elif isinstance(item, (tuple, list)) and len(item) >= 1 and isinstance(item[0], str):
3070
+ addr_str = str(item[0])
3071
+ else:
3072
+ raise ValueError("target must resolve exclusively to public IP addresses")
3073
+ if not is_public_ip_address(addr_str):
3074
+ raise ValueError("target must resolve exclusively to public IP addresses")
3075
+ fam = 6 if ":" in addr_str else 4
3076
+ if (addr_str, fam) not in parsed_pins:
3077
+ parsed_pins.append((addr_str, fam))
3078
+ vetted_pins = parsed_pins
3079
+
3080
+ def get_from_target(url: str, accept: str) -> Optional[HttpResponse]:
3081
+ if transport is not None:
3082
+ return _transport_get_bounded(transport, url, accept)
3083
+ return _pinned_socket_get_bounded(url, accept, timeout_sec, vetted_pins)
3084
+
3085
+ honours_transport = api_transport or transport or _make_default_transport(timeout_sec)
3086
+
3087
+ sources: List[str] = []
3088
+
3089
+ def add_source(src: str) -> None:
3090
+ if src not in sources:
3091
+ sources.append(src)
3092
+
3093
+ respondent_id: Optional[str] = None
3094
+ verified_standing = False
3095
+ has_verified_notice_channel = False
3096
+ contact: Dict[str, str] = {}
3097
+ if initial_did_web:
3098
+ contact["didWeb"] = initial_did_web
3099
+
3100
+ # 1. Settlement Honours Roll lookup (trusted ONLY with verified active platform signedAttestation, P1-2)
3101
+ clean_base = normalize_base_url(base_url) if base_url else None
3102
+ effective_platform_did = platform_did if platform_did is not None else (
3103
+ DEFAULT_PRODUCTION_PLATFORM_DIDS.get(clean_base) if clean_base else None
3104
+ )
3105
+ effective_expected_env = expected_environment if expected_environment is not None else (
3106
+ "production" if clean_base == PRODUCTION_API_URL else None
3107
+ )
3108
+ if clean_base and effective_platform_did and is_did_key(effective_platform_did):
3109
+ honours_res = _transport_get_bounded(
3110
+ honours_transport,
3111
+ f"{clean_base}/v1/honours/{urllib.parse.quote(domain, safe='')}",
3112
+ "application/json",
3113
+ )
3114
+ if honours_res is not None:
3115
+ try:
3116
+ body = json.loads(honours_res.body)
3117
+ now_ts = clock()
3118
+ att = body.get("signedAttestation") if isinstance(body, Mapping) else None
3119
+ doc = att.get("document") if isinstance(att, Mapping) else None
3120
+ proof = att.get("proof") if isinstance(att, Mapping) else None
3121
+ created = proof.get("created") if isinstance(proof, Mapping) else None
3122
+ exp = proof.get("expiresAt") if isinstance(proof, Mapping) else None
3123
+ agent_ids = doc.get("agentIds") if isinstance(doc, Mapping) else None
3124
+ if (
3125
+ isinstance(body, Mapping)
3126
+ and body.get("listed") is True
3127
+ and body.get("inGoodStanding") is not False
3128
+ and isinstance(att, Mapping)
3129
+ and isinstance(doc, Mapping)
3130
+ and doc.get("type") == HONOURS_ATTESTATION_TYPE
3131
+ and doc.get("domain") == domain
3132
+ and (effective_expected_env is None or doc.get("environment") == effective_expected_env)
3133
+ and (expected_rules_hash is None or doc.get("rulesHash") == expected_rules_hash)
3134
+ and doc.get("fulfilmentRate") == 1
3135
+ and isinstance(agent_ids, list)
3136
+ and len(agent_ids) > 0
3137
+ and isinstance(created, int)
3138
+ and not isinstance(created, bool)
3139
+ and isinstance(exp, int)
3140
+ and not isinstance(exp, bool)
3141
+ and created == doc.get("issuedAt")
3142
+ and created <= now_ts + 300_000
3143
+ and exp > created
3144
+ and exp - created <= 24 * 3_600_000
3145
+ ):
3146
+ att_sig_ok = verify_document(att, effective_platform_did, now_ms=now_ts)
3147
+ if (
3148
+ not att_sig_ok
3149
+ and isinstance(proof, Mapping)
3150
+ and proof.get("verificationMethod") != effective_platform_did
3151
+ ):
3152
+ kh_res = _transport_get_bounded(
3153
+ honours_transport,
3154
+ f"{clean_base}/.well-known/key-history.json",
3155
+ "application/json",
3156
+ )
3157
+ if kh_res is not None:
3158
+ kh = json.loads(kh_res.body)
3159
+ if (
3160
+ isinstance(kh, Mapping)
3161
+ and verify_key_history(
3162
+ kh,
3163
+ expected_active_did=effective_platform_did,
3164
+ now_ms=now_ts,
3165
+ max_age_ms=DEFAULT_KEY_HISTORY_TTL_MS,
3166
+ ).get("ok")
3167
+ ):
3168
+ kh_active = kh.get("document", {}).get("activeDid")
3169
+ if isinstance(kh_active, str) and kh_active != effective_platform_did:
3170
+ att_sig_ok = verify_document(att, kh_active, now_ms=now_ts)
3171
+ if att_sig_ok:
3172
+ entry = body.get("entry")
3173
+ entry_matches = entry is None or (
3174
+ isinstance(entry, Mapping)
3175
+ and entry.get("domain") == doc.get("domain")
3176
+ and entry.get("didWeb") == doc.get("didWeb")
3177
+ and isinstance(entry.get("agentIds"), list)
3178
+ and entry.get("agentIds") == agent_ids
3179
+ )
3180
+ if entry_matches:
3181
+ first_did = next((aid for aid in agent_ids if isinstance(aid, str) and is_did_key(aid)), None)
3182
+ if first_did:
3183
+ respondent_id = first_did
3184
+ verified_standing = True
3185
+ if isinstance(doc.get("didWeb"), str) and str(doc["didWeb"]).startswith("did:web:"):
3186
+ contact["didWeb"] = str(doc["didWeb"])
3187
+ add_source("honours")
3188
+ except Exception:
3189
+ pass
3190
+
3191
+ # 2. A2A Agent Card (/.well-known/agent-card.json -> /.well-known/agent.json -> Link header on /)
3192
+ card_url: Optional[str] = f"{origin}/.well-known/agent-card.json"
3193
+ card_res = get_from_target(card_url, "application/json")
3194
+ if card_res is None:
3195
+ card_url = f"{origin}/.well-known/agent.json"
3196
+ card_res = get_from_target(card_url, "application/json")
3197
+ if card_res is None:
3198
+ root_res = get_from_target(f"{origin}/", "text/html, application/json;q=0.9, */*;q=0.5")
3199
+ linked = _parse_link_header_agent_card(root_res.headers.get("link") if root_res else None, origin)
3200
+ if linked:
3201
+ card_res = get_from_target(linked, "application/json")
3202
+ if card_res is not None:
3203
+ card_url = linked
3204
+ add_source("link_header")
3205
+
3206
+ parsed_card: Optional[Dict[str, Any]] = None
3207
+ if card_res is not None and card_url is not None:
3208
+ try:
3209
+ c = json.loads(card_res.body)
3210
+ if isinstance(c, dict):
3211
+ parsed_card = c
3212
+ contact["a2aCardUrl"] = card_url
3213
+ add_source("a2a_card")
3214
+ except Exception:
3215
+ pass
3216
+
3217
+ # 3. W3C did:web (/.well-known/did.json or path-scoped did_doc_url)
3218
+ try:
3219
+ root_did_web: Optional[str] = did_web_from_url(origin)
3220
+ except Exception:
3221
+ root_did_web = None
3222
+ expected_did_web = initial_did_web or root_did_web
3223
+ allowed_did_webs: set[str] = set()
3224
+ if root_did_web:
3225
+ allowed_did_webs.add(root_did_web)
3226
+ if initial_did_web:
3227
+ allowed_did_webs.add(initial_did_web)
3228
+
3229
+ did_doc_authorized_keys: List[str] = []
3230
+ did_doc_method_by_id: Dict[str, str] = {}
3231
+ did_res = get_from_target(did_doc_url, "application/did+ld+json, application/json")
3232
+ if did_res is not None:
3233
+ try:
3234
+ did_doc = json.loads(did_res.body)
3235
+ if isinstance(did_doc, dict):
3236
+ if expected_did_web:
3237
+ contact["didWeb"] = expected_did_web
3238
+ add_source("did_web")
3239
+ extracted_candidates, did_doc_method_by_id = _extract_did_methods_from_did_doc(did_doc, expected_did_web)
3240
+ raw_candidates = ([respondent_id] if respondent_id else []) + extracted_candidates
3241
+ if expected_did_web:
3242
+ for cand in raw_candidates:
3243
+ if cand not in did_doc_authorized_keys and did_web_document_authorizes_key(did_doc, expected_did_web, cand):
3244
+ did_doc_authorized_keys.append(cand)
3245
+ did_webhook_url: Optional[str] = None
3246
+ if isinstance(did_doc.get("service"), list):
3247
+ for svc in did_doc["service"]:
3248
+ if (
3249
+ isinstance(svc, Mapping)
3250
+ and svc.get("type") == "AgentMediateNotice"
3251
+ and isinstance(svc.get("serviceEndpoint"), str)
3252
+ and _origin_of_url(svc["serviceEndpoint"]) == origin
3253
+ ):
3254
+ did_webhook_url = svc["serviceEndpoint"]
3255
+ break
3256
+ for cand in did_doc_authorized_keys:
3257
+ if verify_agent_card_signature(did_doc, cand):
3258
+ if respondent_id is None:
3259
+ respondent_id = cand
3260
+ if cand == respondent_id and did_webhook_url is not None:
3261
+ if "webhookUrl" not in contact:
3262
+ contact["webhookUrl"] = did_webhook_url
3263
+ has_verified_notice_channel = True
3264
+ break
3265
+ if parsed_card is None and isinstance(did_doc.get("service"), list):
3266
+ for svc in did_doc["service"]:
3267
+ if (
3268
+ isinstance(svc, Mapping)
3269
+ and svc.get("type") in ("A2AAgentCard", "AgentCard")
3270
+ and isinstance(svc.get("serviceEndpoint"), str)
3271
+ ):
3272
+ ep = svc["serviceEndpoint"]
3273
+ if _origin_of_url(ep) == origin:
3274
+ linked_card = get_from_target(ep, "application/json")
3275
+ if linked_card is not None:
3276
+ try:
3277
+ c = json.loads(linked_card.body)
3278
+ if isinstance(c, dict):
3279
+ parsed_card = c
3280
+ contact["a2aCardUrl"] = ep
3281
+ add_source("a2a_card")
3282
+ except Exception:
3283
+ pass
3284
+ break
3285
+ except Exception:
3286
+ pass
3287
+
3288
+ # Evaluate Agent Card cryptographic binding & channels
3289
+ if parsed_card is not None:
3290
+ caps = parsed_card.get("capabilities")
3291
+ exts = caps.get("extensions") if isinstance(caps, Mapping) else None
3292
+ custom_webhook: Optional[str] = None
3293
+ if isinstance(exts, list):
3294
+ for ext in exts:
3295
+ if isinstance(ext, Mapping) and ext.get("uri") in (
3296
+ "urn:agent-mediate:ext:dispute-notice:v1",
3297
+ "urn:agent-mediate:ext:dispute-clause:v1",
3298
+ "urn:agent-mediate:ext:notifications:v1",
3299
+ "urn:agent-mediate:ext:notice:v1",
3300
+ ):
3301
+ params = ext.get("params")
3302
+ wh = (params.get("noticeWebhookUrl") or params.get("webhookUrl")) if isinstance(params, Mapping) else None
3303
+ if isinstance(wh, str) and _origin_of_url(wh) == origin:
3304
+ custom_webhook = wh
3305
+ standard_rpc_url = _extract_standard_a2a_rpc_url(parsed_card, origin)
3306
+ if _agent_card_matches_origin(parsed_card, origin, allowed_did_webs, custom_webhook is not None):
3307
+ raw_card_candidates = (
3308
+ ([respondent_id] if respondent_id else [])
3309
+ + _extract_did_candidates_from_card(parsed_card, did_doc_method_by_id, expected_did_web)
3310
+ + did_doc_authorized_keys
3311
+ )
3312
+ unique_candidates: List[str] = []
3313
+ for cand in raw_card_candidates:
3314
+ if cand not in unique_candidates:
3315
+ unique_candidates.append(cand)
3316
+ for cand in unique_candidates:
3317
+ if verify_agent_card_signature(parsed_card, cand):
3318
+ if respondent_id is None:
3319
+ respondent_id = cand
3320
+ if cand == respondent_id and (custom_webhook is not None or standard_rpc_url is not None):
3321
+ has_verified_notice_channel = True
3322
+ break
3323
+ provider = parsed_card.get("provider")
3324
+ prov_email = provider.get("email") if isinstance(provider, Mapping) else None
3325
+ if isinstance(prov_email, str) and _SIMPLE_EMAIL_RE.fullmatch(prov_email.strip()):
3326
+ contact["email"] = prov_email.strip()
3327
+
3328
+ # 4. RFC 9116 security.txt fallback
3329
+ if "email" not in contact:
3330
+ sec_res = get_from_target(f"{origin}/.well-known/security.txt", "text/plain")
3331
+ if sec_res is None:
3332
+ sec_res = get_from_target(f"{origin}/security.txt", "text/plain")
3333
+ if sec_res is not None:
3334
+ sec_email = _parse_security_txt_email(sec_res.body)
3335
+ if sec_email:
3336
+ contact["email"] = sec_email
3337
+ add_source("security_txt")
3338
+
3339
+ recommended_action = (
3340
+ "file_dispute"
3341
+ if (respondent_id is not None and has_verified_notice_channel)
3342
+ else "send_invite"
3343
+ )
3344
+ return {
3345
+ "domain": domain,
3346
+ "origin": origin,
3347
+ "respondentId": respondent_id,
3348
+ "respondentContact": contact,
3349
+ "verifiedStanding": verified_standing,
3350
+ "hasVerifiedNoticeChannel": has_verified_notice_channel,
3351
+ "recommendedAction": recommended_action,
3352
+ "sources": sources,
3353
+ }