From 21c1b98ab2b0e9d2b5afa3cb35bc416442ffd98f Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Mon, 19 Oct 2026 16:09:52 -0400 Subject: [PATCH 1/2] 1.1.4: honour Retry-After on signed payment-unavailable responses --- README.md | 2 ++ skills/x402/SKILL.md | 1 + skills/x402/lib/payment.py | 17 +++++++++---- tests/test_payment_retry.py | 48 ++++++++++++++++++++++++++++++++++++- 4 files changed, 62 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4641bd0..e005434 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,8 @@ Run checks with `python3 -m pytest -q`. Regenerate the Available Services table ## Changelog +- **1.1.4** - Honour Retry-After on signed 503 payment-unavailable or retryable responses, reusing the identical payment and retaining expired recovery records. + - **1.1.3** - Retry identical payments after lost responses without paying twice. Save pending requests by txid and provide a `retry-payment` recovery command. Stop on signed replay or expired-quote codes; retain expired payments as `expired-unclaimed` with recovery instructions, time and server details, and remove records only for signed HTTP 200, claimed replay, or imported refunds. Report unsigned or signed paid 402 refusals with the txid. Bound send starts by the quote window while retaining the 300-second response timeout and one session refresh. Preserve delivered responses and refund bytes on import failure, with an `import-refund` command. Normalize the body once before quoting, tolerate stale server clocks beyond 60 seconds, suppress expired retry commands, and print payment JSON if the initial recovery-file write fails. - **1.1.2** - Document the MetaNet Client and headless wallet paths, including gaps in the wallet README. Generate all service rows, exact registry tier ranges, and sync/async delivery from the public registry. diff --git a/skills/x402/SKILL.md b/skills/x402/SKILL.md index e65b72f..9e0d322 100644 --- a/skills/x402/SKILL.md +++ b/skills/x402/SKILL.md @@ -1,5 +1,6 @@ --- name: x402 +version: 1.1.4 description: "Make BSV-authenticated or paid API requests. Use for: BRC-31 auth, 402 payment, BSV micropayments, x402, paid API calls. Requires a BRC-100 wallet (MetaNet Client at localhost:3321, or X402_WALLET_URL)." argument-hint: [URL or description of API to call] --- diff --git a/skills/x402/lib/payment.py b/skills/x402/lib/payment.py index 785cdda..e6b4a1f 100644 --- a/skills/x402/lib/payment.py +++ b/skills/x402/lib/payment.py @@ -622,10 +622,14 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon for attempt in range(min(max(0, max_retries), len(PAYMENT_BACKOFF)) + 1): if attempt: delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[attempt - 1] - retry_after = None - if time.time() + delay >= record["expires_at"]: + if retry_after is not None: + delay = min(delay, max(0, record["expires_at"] - time.time())) + time.sleep(delay) + retry_after = None + elif time.time() + delay >= record["expires_at"]: break - time.sleep(delay) + else: + time.sleep(delay) remaining = record["expires_at"] - time.time() if remaining <= 0: break @@ -661,8 +665,11 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon "to the first request or will be refunded. No payment remains to retry.") if response.status_code == 402: raise _unresolved(record, path, "paid request returned HTTP 402; no new payment created") - if response.status_code == 202: - last_error = "payment outcome still pending" + unavailable = response.status_code == 503 and isinstance(parsed, dict) and ( + code == "ERR_PAYMENT_UNAVAILABLE" or parsed.get("retryable") is True + ) + if response.status_code == 202 or unavailable: + last_error = "payment unavailable" if unavailable else "payment outcome still pending" try: retry_after = max(0, int(response.headers.get("Retry-After", "5"))) except ValueError: diff --git a/tests/test_payment_retry.py b/tests/test_payment_retry.py index 127b999..25b1f67 100644 --- a/tests/test_payment_retry.py +++ b/tests/test_payment_retry.py @@ -67,7 +67,7 @@ def request(method, url, headers, data, timeout): outcome = outcomes.pop(0) if isinstance(outcome, Exception): raise outcome - status, body, signed = outcome + status, body, signed, *extra = outcome response = requests.Response() response.status_code = status response._content = json.dumps(body).encode() if body is not None else b"" @@ -82,6 +82,8 @@ def request(method, url, headers, data, timeout): response.headers["x-bsv-auth-your-nonce"] = load_session(URL.rsplit("/", 1)[0]).client_nonce_b64 if status == 402: response.headers.update(quote_headers) + if len(calls) > 1 and extra: + response.headers.update(extra[0]) if signed: rid = base64.b64decode(headers["x-bsv-auth-request-id"]) payload = serialize_response(rid, status, filter_signable_headers(response.headers), response.content or None) @@ -482,3 +484,47 @@ def test_unconfirmed_response_keeps_terminal_record(server, status, code): with pytest.raises(payment.PaymentError, match="keep this file"): payment.retry_payment(path) assert len(actions) == 1 and len(calls) == 2 + + +@pytest.mark.parametrize("body", [{"code": "ERR_PAYMENT_UNAVAILABLE"}, + {"code": "OTHER", "retryable": True}]) +@pytest.mark.parametrize("header, delay", [("7", 7), ("invalid", 5), (None, 5)]) +def test_unavailable_retries_identical_payment(server, body, header, delay): + outcomes, actions, calls, sleeps, _, _ = server + headers = {} if header is None else {"Retry-After": header} + outcomes.extend([(503, body, True, headers), (200, {"ok": True}, True)]) + assert payment.paid_request("POST", URL, body="same payload").status_code == 200 + assert sleeps == [delay] and len(actions) == 1 + assert calls[1][1] == calls[2][1] + assert calls[1][0]["x-bsv-payment"] == calls[2][0]["x-bsv-payment"] + assert not (payment.PENDING_DIR / f"{TXID}.json").exists() + + +def test_unavailable_retry_after_capped_at_quote_expiry(server): + outcomes, actions, calls, sleeps, now, _ = server + outcomes.append((503, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True}, + True, {"Retry-After": "900"})) + with pytest.raises(payment.PaymentError, match="the quote expired"): + payment.paid_request("POST", URL) + saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text()) + assert saved["state"] == "expired-unclaimed" + assert saved["terminal_at"] == now[0] == saved["expires_at"] + assert sleeps == [300] and len(actions) == 1 and len(calls) == 2 + + +def test_unsigned_unavailable_ignores_retry_after(server): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([(503, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True}, + False, {"Retry-After": "900"}), (200, {"ok": True}, True)]) + assert payment.paid_request("POST", URL).status_code == 200 + assert sleeps == [2] and len(actions) == 1 and len(calls) == 3 + + +def test_nonretryable_signed_503_keeps_existing_handling(server): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.append((503, {"code": "OTHER", "retryable": False}, True, + {"Retry-After": "7"})) + assert payment.paid_request("POST", URL).status_code == 503 + saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text()) + assert saved["state"] == "terminal-unresolved" + assert sleeps == [] and len(actions) == 1 and len(calls) == 2 From d8883900a07dabd33cf514081a3b89d98eaa4127 Mon Sep 17 00:00:00 2001 From: John Calhoun Date: Mon, 19 Oct 2026 16:13:48 -0400 Subject: [PATCH 2/2] fix: fold 1.1.4 review with bounded independent 503 retries --- .claude-plugin/marketplace.json | 4 ++-- README.md | 4 ++-- skills/x402/SKILL.md | 2 +- skills/x402/lib/payment.py | 30 ++++++++++++++++++++++++------ tests/test_payment_retry.py | 31 +++++++++++++++++++++++++++++-- 5 files changed, 58 insertions(+), 13 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index aec0602..e5bf42c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -5,7 +5,7 @@ }, "metadata": { "description": "BSV micropayment skill for Claude Code - BRC-31 auth + BRC-29 payment via a BRC-100 wallet", - "version": "1.1.3" + "version": "1.1.4" }, "plugins": [ { @@ -15,7 +15,7 @@ "skills": [ "./skills/x402" ], - "version": "1.1.3" + "version": "1.1.4" } ] } diff --git a/README.md b/README.md index e005434..9eee259 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ All payment is automatic - no confirmation prompts for typical micropayments (1 ## Refunds -If a paid response is lost, the helper retries the identical payment up to three times after 2, 5, and 10 seconds. Each send must start within the quote's five-minute window; a started request retains its full 300-second response timeout so slow work can finish. It never pays twice for that quote. Before sending, it saves the payment and request in `~/.x402/pending/.json`. Unresolved calls report the txid and an exact `retry-payment` command while the window remains open. A signed `ERR_PAYMENT_REPLAYED` refusal stops retries and removes the file because the payment was already claimed for service or refund. A signed `ERR_QUOTE_EXPIRED` refusal stops retries and keeps the file marked `expired-unclaimed` with the time, server code and message: the quote expired; the server may not have claimed this payment; the sats are yours if no service was delivered; keep this file and recover with the server operator using its saved payment details through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also retains and marks the file, without an unusable retry command. Other unconfirmed responses retain a terminal recovery record. A signed HTTP 200 for the same payment or successfully imported refund removes the file. If refund import fails, the response is returned and saved in the pending file, with an `import-refund` command to recover the refund without resending the payment. +If a paid response is lost, the helper retries the identical payment up to three times after 2, 5, and 10 seconds. Signed retryable 503 responses use a separate six-attempt bound and honour `Retry-After`. Signed 202 and retryable 503 waits are capped at the remaining quote window. Each send must start within the quote's five-minute window; a started request retains its full 300-second response timeout so slow work can finish. It never pays twice for that quote. Before sending, it saves the payment and request in `~/.x402/pending/.json`. Unresolved calls report the txid and an exact `retry-payment` command while the window remains open. A signed `ERR_PAYMENT_REPLAYED` refusal stops retries and removes the file because the payment was already claimed for service or refund. A signed `ERR_QUOTE_EXPIRED` refusal stops retries and keeps the file marked `expired-unclaimed` with the time, server code and message: the quote expired; the server may not have claimed this payment; the sats are yours if no service was delivered; keep this file and recover with the server operator using its saved payment details through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also retains and marks the file, without an unusable retry command. Other unconfirmed responses retain a terminal recovery record. A signed HTTP 200 for the same payment or successfully imported refund removes the file. If refund import fails, the response is returned and saved in the pending file, with an `import-refund` command to recover the refund without resending the payment. ## Wallet selection and sessions @@ -199,7 +199,7 @@ Run checks with `python3 -m pytest -q`. Regenerate the Available Services table ## Changelog -- **1.1.4** - Honour Retry-After on signed 503 payment-unavailable or retryable responses, reusing the identical payment and retaining expired recovery records. +- **1.1.4** - Honour Retry-After on signed 503 payment-unavailable or retryable responses, reusing the identical payment and retaining expired recovery records. Both signed 202 and retryable 503 waits are capped at the remaining quote window and retain an expired-unclaimed record at expiry. Signed retryable 503s have a separate six-attempt bound, independent of the ordinary retry budget; exhaustion keeps the record for `retry-payment`. - **1.1.3** - Retry identical payments after lost responses without paying twice. Save pending requests by txid and provide a `retry-payment` recovery command. Stop on signed replay or expired-quote codes; retain expired payments as `expired-unclaimed` with recovery instructions, time and server details, and remove records only for signed HTTP 200, claimed replay, or imported refunds. Report unsigned or signed paid 402 refusals with the txid. Bound send starts by the quote window while retaining the 300-second response timeout and one session refresh. Preserve delivered responses and refund bytes on import failure, with an `import-refund` command. Normalize the body once before quoting, tolerate stale server clocks beyond 60 seconds, suppress expired retry commands, and print payment JSON if the initial recovery-file write fails. diff --git a/skills/x402/SKILL.md b/skills/x402/SKILL.md index 9e0d322..e3cdc38 100644 --- a/skills/x402/SKILL.md +++ b/skills/x402/SKILL.md @@ -151,7 +151,7 @@ Servers that support BRC-29 refunds will automatically return refund data when a The `discover` command shows which endpoints support refunds. The `pay` command output includes a `refund` block when a refund was received and internalized. -If a paid response is lost, the helper retries the identical payment after 2, 5, and 10 seconds. Sends must start within the quote's five-minute window; each started request retains its 300-second response timeout. It never creates another payment for that quote. Unresolved calls retain `~/.x402/pending/.json` and print the txid and an exact `retry-payment` command while the window remains open. Use that command with the original wallet instead of starting another `pay` call. Signed `ERR_PAYMENT_REPLAYED` stops retries and removes the already-claimed payment file. Signed `ERR_QUOTE_EXPIRED` stops retries and retains the file marked `expired-unclaimed`, with the time, server code and message: the server may not have claimed this payment; the sats are yours if no service was delivered. Keep the file and recover with the server operator through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also marks and retains the file without a retry command; other unconfirmed responses retain a terminal recovery record. Only signed HTTP 200 for the same payment, claimed replay, or an imported refund removes the pending file. Failed refund imports preserve and return the delivered response and print an `import-refund` command; use it with the original wallet to import the saved refund without resending the payment. +If a paid response is lost, the helper retries the identical payment after 2, 5, and 10 seconds. Signed retryable 503 responses use a separate six-attempt bound and honour `Retry-After`. Signed 202 and retryable 503 waits are capped at the remaining quote window. Sends must start within the quote's five-minute window; each started request retains its 300-second response timeout. It never creates another payment for that quote. Unresolved calls retain `~/.x402/pending/.json` and print the txid and an exact `retry-payment` command while the window remains open. Use that command with the original wallet instead of starting another `pay` call. Signed `ERR_PAYMENT_REPLAYED` stops retries and removes the already-claimed payment file. Signed `ERR_QUOTE_EXPIRED` stops retries and retains the file marked `expired-unclaimed`, with the time, server code and message: the server may not have claimed this payment; the sats are yours if no service was delivered. Keep the file and recover with the server operator through the refund path or a later receipt query, then use `import-refund` when refund data is available. Local quote expiry also marks and retains the file without a retry command; other unconfirmed responses retain a terminal recovery record. Only signed HTTP 200 for the same payment, claimed replay, or an imported refund removes the pending file. Failed refund imports preserve and return the delivered response and print an `import-refund` command; use it with the original wallet to import the saved refund without resending the payment. ## Payment Transport diff --git a/skills/x402/lib/payment.py b/skills/x402/lib/payment.py index e6b4a1f..d0b8041 100644 --- a/skills/x402/lib/payment.py +++ b/skills/x402/lib/payment.py @@ -53,9 +53,10 @@ # BRC-29 payment protocol version. Must match server expectation. PAYMENT_VERSION = "1.0" -# Maximum number of retries after the first paid send. +# Maximum number of ordinary retries after the first paid send. MAX_PAYMENT_ATTEMPTS = 3 PAYMENT_BACKOFF = (2, 5, 10) +MAX_UNAVAILABLE_ATTEMPTS = 6 QUOTE_WINDOW = 300 PENDING_DIR = Path.home() / ".x402" / "pending" @@ -619,9 +620,18 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon body = base64.b64decode(record["body"]) if record["body"] is not None else None last_error = "quote window expired" retry_after = None - for attempt in range(min(max(0, max_retries), len(PAYMENT_BACKOFF)) + 1): - if attempt: - delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[attempt - 1] + ordinary_retries = 0 + unavailable_attempts = 0 + unavailable_retry = False + first_send = True + retry_limit = min(max(0, max_retries), len(PAYMENT_BACKOFF)) + while True: + if not first_send: + if not unavailable_retry: + if ordinary_retries >= retry_limit: + break + ordinary_retries += 1 + delay = retry_after if retry_after is not None else PAYMENT_BACKOFF[ordinary_retries - 1] if retry_after is not None: delay = min(delay, max(0, record["expires_at"] - time.time())) time.sleep(delay) @@ -630,6 +640,8 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon break else: time.sleep(delay) + first_send = False + unavailable_retry = False remaining = record["expires_at"] - time.time() if remaining <= 0: break @@ -670,6 +682,11 @@ def _send_pending(record: dict, path: Path, max_retries: int) -> requests.Respon ) if response.status_code == 202 or unavailable: last_error = "payment unavailable" if unavailable else "payment outcome still pending" + if unavailable: + unavailable_attempts += 1 + if unavailable_attempts >= MAX_UNAVAILABLE_ATTEMPTS: + break + unavailable_retry = True try: retry_after = max(0, int(response.headers.get("Retry-After", "5"))) except ValueError: @@ -747,9 +764,10 @@ def paid_request( body: bytes | str | None = None, max_payment_attempts: int = MAX_PAYMENT_ATTEMPTS, ) -> requests.Response: - """Pay a verified quote once; retry the identical payment at most three times. + """Pay a verified quote once; retry the identical payment within bounded budgets. - ``max_payment_attempts`` limits retries after the first paid send. All sends + ``max_payment_attempts`` limits ordinary retries after the first paid send. + Signed retryable 503s have a separate six-attempt budget. All sends must begin within five minutes of receiving the quote (or the server's earlier Date within 60 seconds of local time). Responses may take 300 seconds after a send starts. Failures before payment creation propagate without paid retries. diff --git a/tests/test_payment_retry.py b/tests/test_payment_retry.py index 25b1f67..f119091 100644 --- a/tests/test_payment_retry.py +++ b/tests/test_payment_retry.py @@ -500,9 +500,10 @@ def test_unavailable_retries_identical_payment(server, body, header, delay): assert not (payment.PENDING_DIR / f"{TXID}.json").exists() -def test_unavailable_retry_after_capped_at_quote_expiry(server): +@pytest.mark.parametrize("status", [202, 503]) +def test_retry_after_capped_at_quote_expiry(server, status): outcomes, actions, calls, sleeps, now, _ = server - outcomes.append((503, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True}, + outcomes.append((status, {"code": "ERR_PAYMENT_UNAVAILABLE", "retryable": True}, True, {"Retry-After": "900"})) with pytest.raises(payment.PaymentError, match="the quote expired"): payment.paid_request("POST", URL) @@ -528,3 +529,29 @@ def test_nonretryable_signed_503_keeps_existing_handling(server): saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text()) assert saved["state"] == "terminal-unresolved" assert sleeps == [] and len(actions) == 1 and len(calls) == 2 + + +@pytest.mark.parametrize("retry_after", ["0", "1"]) +def test_unavailable_exhausts_separate_six_attempt_budget(server, retry_after): + outcomes, actions, calls, sleeps, now, _ = server + outcomes.extend([(503, {"code": "ERR_PAYMENT_UNAVAILABLE"}, True, + {"Retry-After": retry_after})] * 6) + with pytest.raises(payment.PaymentError, match="identical-payment retries exhausted"): + payment.paid_request("POST", URL, body="same payload", max_payment_attempts=0) + saved = json.loads((payment.PENDING_DIR / f"{TXID}.json").read_text()) + assert saved.get("state") not in ("expired-unclaimed", "terminal-unresolved") + assert now[0] < saved["expires_at"] + assert len(actions) == 1 and len(calls) == 7 + assert sleeps == [int(retry_after)] * 5 + assert all(call[1] == calls[1][1] for call in calls[1:]) + assert all(call[0]["x-bsv-payment"] == calls[1][0]["x-bsv-payment"] + for call in calls[1:]) + + +def test_unavailable_does_not_consume_ordinary_retry_budget(server): + outcomes, actions, calls, sleeps, _, _ = server + outcomes.extend([(503, {"retryable": True}, True, {"Retry-After": "1"})] * 5) + outcomes.extend([(503, None, False), (200, {"ok": True}, True)]) + assert payment.paid_request("POST", URL, max_payment_attempts=1).status_code == 200 + assert sleeps == [1] * 5 + [2] + assert len(actions) == 1 and len(calls) == 8