From 137e6b55a37bf112362d17cdceb4924ffa6d8fe6 Mon Sep 17 00:00:00 2001 From: bensynapse <118375461+bensynapse@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:07:51 +0200 Subject: [PATCH] Version 0.9.0: the spec at API 1.20.10 and the Checkout read of a top-up The saved spec follows the public document at API 1.20.10. It was merged three ways on the parsed documents, with the public document at 1.20.9 as the base. There were no conflicts, and every local declaration and earlier schema is kept. billing.get_topup_session takes check_checkout on both clients, false by default. TopupSession gains checkout_status and Delivery gains webhook_deleted. Delivery.webhook_deleted stays optional so older payloads still parse. Docstrings name the 409 of a replay to a deleted webhook and the cover limits. --- CHANGELOG.md | 22 +++ README.md | 6 +- pyproject.toml | 2 +- spec/openapi.yaml | 238 +++++++++++++++++++++++++----- src/faxforagents/__init__.py | 2 +- src/faxforagents/async_client.py | 37 ++++- src/faxforagents/client.py | 35 ++++- src/faxforagents/models.py | 32 ++-- tests/conftest.py | 22 +++ tests/fixtures/README.md | 2 + tests/fixtures/billing-pages.json | 6 +- tests/fixtures/responses.json | 3 +- tests/test_async.py | 31 +++- tests/test_client.py | 54 ++++++- tests/test_one_time.py | 16 ++ 15 files changed, 432 insertions(+), 76 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb74e4f..59a3a38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Changelog +## 0.9.0 (2026-11-15) + +Follows API 1.20.10. The saved spec has 163 operations and the models are regenerated from it. +Every operation has a method on both clients. + +New parameter: `billing.get_topup_session(topup_session_id, check_checkout=True)` asks Stripe about the hosted Checkout of an open top-up. +The new field `TopupSession.checkout_status` reads `open`, `complete`, `processing` or `expired`, and `None` when not asked. +`complete` means the person paid, and the wallet is credited when Stripe's event arrives. `processing` is a payment that confirms later, such as a bank debit. +The default is `False`, and the request is then the same as in 0.8.0. + +New field: `Delivery.webhook_deleted`, which only `DeliveryDetail` had. The API sends it on every delivery. +It is optional on `Delivery`, so a payload without it still parses. +`webhooks.replay_delivery` on a delivery whose webhook was deleted raises `ConflictError` with `details["reason"]` set to `webhook_deleted`. +Deleting a webhook ends the deliveries that were waiting for it. They read `failed`, with no next attempt. + +`OneTimeCoverCheck` describes the limits of `create`: `to_name` 120 characters, `subject` 200 and `message` 2,000. +`one_time_sends.check_cover` says a longer field raises `InvalidRequestError`, as `create` does. +`billing.cancel_topup_session` says `details["reason"]` is `paid` when the payment came in before the cancel. +New descriptions on the counters of `PolicyUsage` and on `policy_name` and `version` of `PolicyVerdict` and `PolicyEvaluation`. + +Nothing is removed. Other model names, fields and optionality are kept. + ## 0.8.0 (2026-11-15) Follows API 1.20.9. The saved spec has 163 operations and the models are regenerated from it. diff --git a/README.md b/README.md index 6ad319a..bad0aed 100644 --- a/README.md +++ b/README.md @@ -90,6 +90,9 @@ The same in async form, with `AsyncClient` and `await` on every call. a document by file name, or a received fax's file by the sender's number. - `one_time_sends.preview(file=...)` counts the pages of a document before any order exists, with no key. `one_time_sends.check_cover(message=...)` says whether a cover message fits on its page. +- `billing.get_topup_session(id, check_checkout=True)` asks Stripe about the hosted Checkout of an open + top-up. `checkout_status` reads `open`, `complete`, `processing` or `expired` while the wallet waits + for Stripe's event. - `faxes.wait(fax_id)` and `approvals.wait(approval_id)` poll with a timeout. - `verify_webhook(secret, headers, body)` checks the Standard Webhooks signature on a delivery. - Models are pydantic v2, generated from the public OpenAPI document. Money is an integer count of @@ -312,10 +315,11 @@ ruff check src tests && mypy src sh scripts/truthcheck.sh ``` -`spec/openapi.yaml` follows the public document at API version 1.20.9 and keeps the schemas of the earlier live documents. +`spec/openapi.yaml` follows the public document at API version 1.20.10 and keeps the schemas of the earlier live documents. The two validation error schemas are the exception. 0.5.0 removed them because the server never sent that shape. 0.6.0 removed two cost fields of an extraction, because the server stopped sending them. 0.8.0 replaced five fields it had declared itself with the public ones, such as `Quote.policy_evaluation`. +0.9.0 leaves `Delivery.webhook_deleted` optional, where the public document requires it. It also retains earlier public model names and route-documented response additions. To refresh it, merge the live schemas while preserving existing declarations, then run `uv run python scripts/gen_models.py`. Keep new response fields optional so older payloads and existing callers remain valid. diff --git a/pyproject.toml b/pyproject.toml index dbc6604..5b93383 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "faxforagents" -version = "0.8.0" +version = "0.9.0" description = "Python client for Fax for Agents: a fax API, a hosted MCP server and SDKs built so AI agents can send and receive faxes." readme = "README.md" requires-python = ">=3.10" diff --git a/spec/openapi.yaml b/spec/openapi.yaml index 1bd592b..4e37cee 100644 --- a/spec/openapi.yaml +++ b/spec/openapi.yaml @@ -1,4 +1,4 @@ -# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.20.9. +# Fax for Agents API, refreshed from the public document of https://github.com/faxforagents/openapi at API 1.20.10. # All earlier schemas are kept. Existing SDK routes, model names and serializer additions are retained. openapi: 3.1.0 info: @@ -26,7 +26,7 @@ info: x-logo: url: https://faxforagents.com/brand/logo-512.png altText: Fax for Agents - version: 1.20.9 + version: 1.20.10 servers: - url: https://api.faxforagents.com description: Production (live and test keys) @@ -236,9 +236,9 @@ paths: '404': $ref: '#/components/responses/NotFound' '409': - description: 'The key expired, so it cannot be rotated (conflict, with details.reason key_expired and - details.expires_at). Create a new key to replace it. Also idempotency_key_conflict: the Idempotency-Key - was used with a different body.' + description: 'The key expired, so it cannot be rotated. error.code is conflict, error.details.reason is + "key_expired" and error.details.expires_at says when it expired. Create a new key to replace it. idempotency_key_conflict: + the Idempotency-Key was used with a different request, or that request is still being processed.' content: application/json: schema: @@ -733,7 +733,12 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -790,7 +795,12 @@ paths: '409': $ref: '#/components/responses/Conflict' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '413': $ref: '#/components/responses/PayloadTooLarge' '422': @@ -884,7 +894,12 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -925,7 +940,12 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -974,7 +994,11 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' security: @@ -1013,7 +1037,12 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'document_expired: the document passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -2563,7 +2592,14 @@ paths: '402': $ref: '#/components/responses/PaymentRequired' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': @@ -2665,6 +2701,19 @@ paths: schema: type: string title: Topup Session Id + - name: check_checkout + in: query + required: false + schema: + type: boolean + description: Ask Stripe about the Checkout of an open top-up and answer its state as checkout_status. + The page Stripe returns the person to asks it, because the event that credits the wallet can arrive + seconds after the payment. + default: false + title: Check Checkout + description: Ask Stripe about the Checkout of an open top-up and answer its state as checkout_status. The + page Stripe returns the person to asks it, because the event that credits the wallet can arrive seconds + after the payment. responses: '200': description: Successful Response @@ -2728,13 +2777,21 @@ paths: '401': $ref: '#/components/responses/Unauthorized' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': - description: 'The top-up has no open Checkout to cancel: it was paid, declined or charged off session - (conflict, with details.status). details.reason is paid when it was paid before the cancel. Also idempotency_key_conflict: - the Idempotency-Key was used with a different body.' + description: 'The top-up has no open Checkout to cancel: it was paid, declined or charged off session. + error.code is conflict and error.details.status is the top-up''s status. error.details.reason is "paid" + when the payment came in before the cancel. idempotency_key_conflict: the Idempotency-Key was used with + a different request, or that request is still being processed.' content: application/json: schema: @@ -2825,7 +2882,14 @@ paths: '402': $ref: '#/components/responses/PaymentRequired' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': @@ -3408,7 +3472,14 @@ paths: '401': $ref: '#/components/responses/Unauthorized' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '410': @@ -3451,7 +3522,14 @@ paths: '401': $ref: '#/components/responses/Unauthorized' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '410': @@ -3494,7 +3572,14 @@ paths: '401': $ref: '#/components/responses/Unauthorized' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': @@ -3534,7 +3619,14 @@ paths: '402': $ref: '#/components/responses/PaymentRequired' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': @@ -3616,7 +3708,14 @@ paths: '402': $ref: '#/components/responses/PaymentRequired' '403': - $ref: '#/components/responses/Forbidden' + description: 'The credential is valid and is not allowed to do this. scope_missing puts the scope in error.details.scope. + Other codes are agent_forbidden and approval_required. A session can also meet csrf_invalid and reauth_required. + A test key, or a session switched to Test, gets environment_not_billable here: the test wallet is never + funded, so billing takes live.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '404': $ref: '#/components/responses/NotFound' '409': @@ -5993,7 +6092,12 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'inbox_item_expired: the received fax passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -6052,7 +6156,12 @@ paths: '409': $ref: '#/components/responses/Conflict' '410': - $ref: '#/components/responses/Gone' + description: 'inbox_item_expired: the received fax passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '413': $ref: '#/components/responses/PayloadTooLarge' '422': @@ -6105,7 +6214,12 @@ paths: '409': $ref: '#/components/responses/Conflict' '410': - $ref: '#/components/responses/Gone' + description: 'inbox_item_expired: the received fax passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -6148,7 +6262,12 @@ paths: '409': $ref: '#/components/responses/Conflict' '410': - $ref: '#/components/responses/Gone' + description: 'inbox_item_expired: the received fax passed its retention date and is no longer kept. organization_deleted: + the organization is being deleted, so the call is refused.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' '429': @@ -6197,7 +6316,11 @@ paths: '404': $ref: '#/components/responses/NotFound' '410': - $ref: '#/components/responses/Gone' + description: 'inbox_item_expired: the received fax passed its retention date and is no longer kept.' + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorEnvelope' '422': $ref: '#/components/responses/UnprocessableContent' security: @@ -8931,15 +9054,16 @@ components: schema: $ref: '#/components/schemas/ErrorEnvelope' Conflict: - description: The resource is in a state that refuses the call, or the Idempotency-Key was used with a different - request (idempotency_key_conflict). error.code names the state. + description: 'The resource is in a state that refuses the call. A state with a code of its own is named by + error.code, for example quote_expired. Otherwise error.code is conflict and error.message says what is in + the way. idempotency_key_conflict: the Idempotency-Key was used with a different request, or that request + is still being processed.' content: application/json: schema: $ref: '#/components/schemas/ErrorEnvelope' Gone: - description: 'What the call asks for is no longer kept. document_expired and inbox_item_expired: the document - or the received fax passed its retention date. organization_deleted: the organization is being deleted.' + description: 'organization_deleted: the organization is being deleted, so the call is refused.' content: application/json: schema: @@ -10631,6 +10755,11 @@ components: - type: 'null' title: Delivered At description: When the destination answered 2xx. Null until then. + webhook_deleted: + type: boolean + title: Webhook Deleted + description: True when the destination was deleted since. The deliveries that were waiting are not sent, + and no delivery to it can be replayed. additionalProperties: true type: object required: @@ -10733,7 +10862,8 @@ components: webhook_deleted: type: boolean title: Webhook Deleted - description: True when the destination was deleted since. + description: True when the destination was deleted since. The deliveries that were waiting are not sent, + and no delivery to it can be replayed. request_headers: additionalProperties: type: string @@ -13006,7 +13136,7 @@ components: - type: 'null' title: Email Pdf description: Attach the PDF of each received fax to the notice mail. The mail goes to the verified address - of an owner of the organization and to no other address. A PDF over 15 MB is not attached. It needs + of an owner of the organization and to no other address. A PDF over 15 MiB is not attached. It needs the scope number:buy. An agent, an OAuth connection and a connected app are refused. additionalProperties: false type: object @@ -13293,28 +13423,34 @@ components: to_name: anyOf: - type: string - maxLength: 1000 + maxLength: 120 - type: 'null' title: To Name + description: The recipient's name, printed in the To line. At most 120 characters, not counting spaces + at either end. subject: anyOf: - type: string - maxLength: 1000 + maxLength: 200 - type: 'null' title: Subject + description: Printed in a Subject line when it is given. At most 200 characters, not counting spaces at + either end. message: anyOf: - type: string - maxLength: 8000 + maxLength: 2000 - type: 'null' title: Message + description: The note printed under the Message heading. It has to fit on the one cover page. At most + 2,000 characters, not counting spaces at either end. additionalProperties: false type: object title: OneTimeCoverCheck description: |- The fields a one-time order prints on its cover sheet, as a form holds them before the order exists. - Every field may be empty. The limits of the create apply (cover.to_name 120 characters, cover.subject - 200, cover.message 2,000). + Every field may be empty. to_name, subject and message have the create's limits, and a longer one is + refused as the create refuses it: 422 invalid_request on cover. OneTimeCoverRoom: properties: fits: @@ -14472,11 +14608,14 @@ components: - type: string - type: 'null' title: Policy Name + description: The name of that policy. Null when none binds. version: anyOf: - type: integer - type: 'null' title: Version + description: 'The number of that version: 1 for the policy''s first rules, one more for each change. Null + when none binds.' managed: anyOf: - type: string @@ -14684,15 +14823,20 @@ components: day_jobs: type: integer title: Day Jobs + description: Sends this policy allowed so far in the current UTC day. day_amount_micro: type: integer title: Day Amount Micro + description: The amount of those sends in micro-USD, as priced when the policy allowed each one. A fax + that fails later still counts. month_jobs: type: integer title: Month Jobs + description: Sends this policy allowed so far in the current UTC month. month_amount_micro: type: integer title: Month Amount Micro + description: The amount of this month's sends in micro-USD, counted the same way as the day's. additionalProperties: true type: object required: @@ -14738,11 +14882,14 @@ components: - type: string - type: 'null' title: Policy Name + description: The name of that policy. Null when none binds. version: anyOf: - type: integer - type: 'null' title: Version + description: 'The number of that version: 1 for the policy''s first rules, one more for each change. Null + when none binds.' managed: anyOf: - type: string @@ -16030,6 +16177,21 @@ components: - type: string - type: 'null' title: Completed At + checkout_status: + anyOf: + - type: string + enum: + - open + - complete + - processing + - expired + - type: 'null' + title: Checkout Status + description: 'Stripe''s own state of the hosted Checkout, read from Stripe when a read of an open top-up + asks with check_checkout=true. complete: the payment was made at Stripe, and the wallet is credited + when Stripe''s event arrives, usually within seconds. processing: the person finished at Stripe with + a payment method that confirms later, such as a bank debit, which can take days. Null when not asked, + or when Stripe could not be read.' additionalProperties: true type: object required: diff --git a/src/faxforagents/__init__.py b/src/faxforagents/__init__.py index d98c7aa..dd1b64d 100644 --- a/src/faxforagents/__init__.py +++ b/src/faxforagents/__init__.py @@ -18,7 +18,7 @@ from __future__ import annotations -__version__ = "0.8.0" +__version__ = "0.9.0" from faxforagents._http import ORDER_TOKEN_HEADER from faxforagents.async_client import AsyncClient diff --git a/src/faxforagents/async_client.py b/src/faxforagents/async_client.py index 71f84b9..75729b0 100644 --- a/src/faxforagents/async_client.py +++ b/src/faxforagents/async_client.py @@ -402,7 +402,10 @@ async def update( ) async def delete(self, webhook_id: str, *, idempotency_key: str | None = None) -> m.Deleted: - """Remove a destination. Scope: webhook:admin.""" + """Remove a destination. Scope: webhook:admin. + + The deliveries that were waiting for it end at once, as ``failed`` with no next attempt. Every + delivery to it then reads ``webhook_deleted`` true and cannot be replayed.""" return await self._h.request( "DELETE", f"/v1/webhooks/{webhook_id}", model=m.Deleted, idempotency_key=idempotency_key ) @@ -442,7 +445,10 @@ async def get_delivery(self, delivery_id: str) -> m.DeliveryDetail: return await self._h.request("GET", f"/v1/webhook-deliveries/{delivery_id}", model=m.DeliveryDetail) async def replay_delivery(self, delivery_id: str, *, idempotency_key: str | None = None) -> m.Delivery: - """Deliver the event again with the same event id. Scope: webhook:admin.""" + """Deliver the event again with the same event id. Scope: webhook:admin. + + A delivery whose ``webhook_deleted`` is true cannot be replayed. It raises ``ConflictError`` + with ``details["reason"]`` ``webhook_deleted``.""" return await self._h.request( "POST", f"/v1/webhook-deliveries/{delivery_id}/replay", @@ -566,9 +572,21 @@ def iter_topup_sessions(self, *, limit: int | None = None) -> AsyncIterator[m.To """Every top-up session, following next_cursor.""" return apaginate(self.list_topup_sessions, {"limit": limit}) - async def get_topup_session(self, topup_session_id: str) -> m.TopupSession: - """Read a top-up session. Scope: billing:read.""" - return await self._h.request("GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession) + async def get_topup_session( + self, topup_session_id: str, *, check_checkout: bool = False + ) -> m.TopupSession: + """Read a top-up session. Scope: billing:read. + + ``check_checkout=True`` also asks Stripe about the hosted Checkout of an open top-up. Its state + is in ``checkout_status``: ``open``, ``complete``, ``processing`` or ``expired``. ``complete`` + means the person paid, and the wallet is credited when Stripe's event arrives. ``processing`` + means they paid with a method that confirms later, such as a bank debit. ``checkout_status`` + is ``None`` when not asked, for a top-up that is not open, or when Stripe could not be read. + The read changes nothing. The default, ``False``, sends no query parameter.""" + params = {"check_checkout": True} if check_checkout else None + return await self._h.request( + "GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession, params=params + ) async def cancel_topup_session( self, topup_session_id: str, *, idempotency_key: str | None = None @@ -578,7 +596,8 @@ async def cancel_topup_session( Canceling a setup payment also turns off the auto top-up that waited on it. A top-up already canceled or expired comes back as it is. One that was paid, declined or charged off session - raises ``ConflictError``, with the top-up's status in ``details["status"]``.""" + raises ``ConflictError``, with the top-up's status in ``details["status"]``. ``details["reason"]`` + is ``paid`` when the payment came in before the cancel.""" return await self._h.request( "POST", f"/v1/topup-sessions/{topup_session_id}/cancel", @@ -1623,7 +1642,11 @@ async def check_cover( Pass the cover fields typed so far, as ``create`` takes them, and leave out the rest. ``fits`` says whether the message fits on the one cover page, and ``lines_left`` how many more lines fit. When it runs over, ``fits_chars`` is how much of its start fits. ``create`` refuses a - cover that does not fit.""" + cover that does not fit. + + ``to_name``, ``subject`` and ``message`` have the limits of ``create``: 120, 200 and 2,000 + characters, not counting spaces at either end. A longer one raises ``InvalidRequestError``, + as ``create`` does.""" body = m.OneTimeCoverCheck( sender_name=sender_name, email=email, to=to, to_name=to_name, subject=subject, message=message ) diff --git a/src/faxforagents/client.py b/src/faxforagents/client.py index 4d8f09f..f7deaed 100644 --- a/src/faxforagents/client.py +++ b/src/faxforagents/client.py @@ -445,7 +445,10 @@ def update(self, webhook_id: str, *, idempotency_key: str | None = None, **chang ) def delete(self, webhook_id: str, *, idempotency_key: str | None = None) -> m.Deleted: - """Remove a destination. Scope: webhook:admin.""" + """Remove a destination. Scope: webhook:admin. + + The deliveries that were waiting for it end at once, as ``failed`` with no next attempt. Every + delivery to it then reads ``webhook_deleted`` true and cannot be replayed.""" return self._h.request( "DELETE", f"/v1/webhooks/{webhook_id}", model=m.Deleted, idempotency_key=idempotency_key ) @@ -483,7 +486,10 @@ def get_delivery(self, delivery_id: str) -> m.DeliveryDetail: return self._h.request("GET", f"/v1/webhook-deliveries/{delivery_id}", model=m.DeliveryDetail) def replay_delivery(self, delivery_id: str, *, idempotency_key: str | None = None) -> m.Delivery: - """Deliver the event again with the same event id. Scope: webhook:admin.""" + """Deliver the event again with the same event id. Scope: webhook:admin. + + A delivery whose ``webhook_deleted`` is true cannot be replayed. It raises ``ConflictError`` + with ``details["reason"]`` ``webhook_deleted``.""" return self._h.request( "POST", f"/v1/webhook-deliveries/{delivery_id}/replay", @@ -603,9 +609,19 @@ def iter_topup_sessions(self, *, limit: int | None = None) -> Iterator[m.TopupSe """Every top-up session, following next_cursor.""" return paginate(lambda p: self.list_topup_sessions(**p), {"limit": limit}) - def get_topup_session(self, topup_session_id: str) -> m.TopupSession: - """Read a top-up session. Scope: billing:read.""" - return self._h.request("GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession) + def get_topup_session(self, topup_session_id: str, *, check_checkout: bool = False) -> m.TopupSession: + """Read a top-up session. Scope: billing:read. + + ``check_checkout=True`` also asks Stripe about the hosted Checkout of an open top-up. Its state + is in ``checkout_status``: ``open``, ``complete``, ``processing`` or ``expired``. ``complete`` + means the person paid, and the wallet is credited when Stripe's event arrives. ``processing`` + means they paid with a method that confirms later, such as a bank debit. ``checkout_status`` + is ``None`` when not asked, for a top-up that is not open, or when Stripe could not be read. + The read changes nothing. The default, ``False``, sends no query parameter.""" + params = {"check_checkout": True} if check_checkout else None + return self._h.request( + "GET", f"/v1/topup-sessions/{topup_session_id}", model=m.TopupSession, params=params + ) def cancel_topup_session( self, topup_session_id: str, *, idempotency_key: str | None = None @@ -615,7 +631,8 @@ def cancel_topup_session( Canceling a setup payment also turns off the auto top-up that waited on it. A top-up already canceled or expired comes back as it is. One that was paid, declined or charged off session - raises ``ConflictError``, with the top-up's status in ``details["status"]``.""" + raises ``ConflictError``, with the top-up's status in ``details["status"]``. ``details["reason"]`` + is ``paid`` when the payment came in before the cancel.""" return self._h.request( "POST", f"/v1/topup-sessions/{topup_session_id}/cancel", @@ -1634,7 +1651,11 @@ def check_cover( Pass the cover fields typed so far, as ``create`` takes them, and leave out the rest. ``fits`` says whether the message fits on the one cover page, and ``lines_left`` how many more lines fit. When it runs over, ``fits_chars`` is how much of its start fits. ``create`` refuses a - cover that does not fit.""" + cover that does not fit. + + ``to_name``, ``subject`` and ``message`` have the limits of ``create``: 120, 200 and 2,000 + characters, not counting spaces at either end. A longer one raises ``InvalidRequestError``, + as ``create`` does.""" body = m.OneTimeCoverCheck( sender_name=sender_name, email=email, to=to, to_name=to_name, subject=subject, message=message ) diff --git a/src/faxforagents/models.py b/src/faxforagents/models.py index d24150a..4f903ff 100644 --- a/src/faxforagents/models.py +++ b/src/faxforagents/models.py @@ -1,6 +1,6 @@ """Typed models of the Fax for Agents API. -GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.20.9). Do not edit by hand. +GENERATED by scripts/gen_models.py from spec/openapi.yaml (API version 1.20.10). Do not edit by hand. Money fields ending in ``_micro`` are integer USD micro-units (39000 is $0.039). Timestamps are ISO 8601 strings in UTC. Response models accept fields the API adds later. Request models refuse unknown fields. """ @@ -695,6 +695,7 @@ class Delivery(_Response): next_attempt_at: str | None = Field(..., description="When the next attempt is due. Null once the delivery has ended.") created_at: str delivered_at: str | None = Field(..., description="When the destination answered 2xx. Null until then.") + webhook_deleted: bool | None = Field(None, description="True when the destination was deleted since. The deliveries that were waiting are not sent, and no delivery to it can be replayed.") class DeliveryDetail(_Response): @@ -715,7 +716,7 @@ class DeliveryDetail(_Response): next_attempt_at: str | None = Field(..., description="When the next attempt is due. Null once the delivery has ended.") created_at: str delivered_at: str | None = Field(..., description="When the destination answered 2xx. Null until then.") - webhook_deleted: bool = Field(..., description="True when the destination was deleted since.") + webhook_deleted: bool = Field(..., description="True when the destination was deleted since. The deliveries that were waiting are not sent, and no delivery to it can be replayed.") request_headers: dict[str, str] = Field(..., description="The headers every attempt carries. webhook-id is the event id. webhook-timestamp and webhook-signature are made at each attempt and are not stored, so their values here say what they hold. The signing secret is never returned.") payload: dict[str, Any] = Field(..., description="The JSON body that is sent, the same at every attempt.") @@ -1294,7 +1295,7 @@ class NumberUpdate(_Request): label: str | None = None project_id: str | None = None inbound_webhook_id: str | None = None - email_pdf: bool | None = Field(None, description="Attach the PDF of each received fax to the notice mail. The mail goes to the verified address of an owner of the organization and to no other address. A PDF over 15 MB is not attached. It needs the scope number:buy. An agent, an OAuth connection and a connected app are refused.") + email_pdf: bool | None = Field(None, description="Attach the PDF of each received fax to the notice mail. The mail goes to the verified address of an owner of the organization and to no other address. A PDF over 15 MiB is not attached. It needs the scope number:buy. An agent, an OAuth connection and a connected app are refused.") class OAuthConsentClient(_Response): @@ -1478,14 +1479,14 @@ class OneTimeConfirmed(_Response): class OneTimeCoverCheck(_Request): - """The fields a one-time order prints on its cover sheet, as a form holds them before the order exists. Every field may be empty. The limits of the create apply (cover.to_name 120 characters, cover.subject 200, cover.message 2,000).""" + """The fields a one-time order prints on its cover sheet, as a form holds them before the order exists. Every field may be empty. to_name, subject and message have the create's limits, and a longer one is refused as the create refuses it: 422 invalid_request on cover.""" sender_name: str | None = Field(None, description="Printed in the From line.") email: str | None = Field(None, description="Printed in the From line.") to: str | None = Field(None, description="The destination, when one is typed.") - to_name: str | None = None - subject: str | None = None - message: str | None = None + to_name: str | None = Field(None, description="The recipient's name, printed in the To line. At most 120 characters, not counting spaces at either end.") + subject: str | None = Field(None, description="Printed in a Subject line when it is given. At most 200 characters, not counting spaces at either end.") + message: str | None = Field(None, description="The note printed under the Message heading. It has to fit on the one cover page. At most 2,000 characters, not counting spaces at either end.") class OneTimeCoverRoom(_Response): @@ -1655,10 +1656,10 @@ class PolicyCreate(_Request): class PolicyUsage(_Response): """What the deciding policy had counted before the send it was asked about, in UTC periods.""" - day_jobs: int - day_amount_micro: int - month_jobs: int - month_amount_micro: int + day_jobs: int = Field(..., description="Sends this policy allowed so far in the current UTC day.") + day_amount_micro: int = Field(..., description="The amount of those sends in micro-USD, as priced when the policy allowed each one. A fax that fails later still counts.") + month_jobs: int = Field(..., description="Sends this policy allowed so far in the current UTC month.") + month_amount_micro: int = Field(..., description="The amount of this month's sends in micro-USD, counted the same way as the day's.") class PolicyEvaluation(_Response): @@ -1669,8 +1670,8 @@ class PolicyEvaluation(_Response): reason: str = Field(..., description="Why, in one sentence.") policy_id: str | None = Field(..., description="The policy that allowed the plan, or the first one that denied it. Null when none binds.") policy_version_id: str | None = Field(..., description="The version of that policy that decided.") - policy_name: str | None - version: int | None + policy_name: str | None = Field(..., description="The name of that policy. Null when none binds.") + version: int | None = Field(..., description="The number of that version: 1 for the policy's first rules, one more for each change. Null when none binds.") managed: str | None = Field(None, description="connected_apps when the organization's auto-send setting decided, else null.") denials: list[dict[str, Any]] = Field(..., description="Every policy that denied the plan, each with its policy_id, policy_version_id, decision, rule and reason. Empty on allow.") usage: PolicyUsage | None = Field(None, description="On allow: the deciding policy's counters for the day and the month before this send.") @@ -1724,8 +1725,8 @@ class PolicyVerdict(_Response): reason: str = Field(..., description="Why, in one sentence.") policy_id: str | None = Field(..., description="The policy that allowed the plan, or the first one that denied it. Null when none binds.") policy_version_id: str | None = Field(..., description="The version of that policy that decided.") - policy_name: str | None - version: int | None + policy_name: str | None = Field(..., description="The name of that policy. Null when none binds.") + version: int | None = Field(..., description="The number of that version: 1 for the policy's first rules, one more for each change. Null when none binds.") managed: str | None = Field(None, description="connected_apps when the organization's auto-send setting decided, else null.") denials: list[dict[str, Any]] = Field(..., description="Every policy that denied the plan, each with its policy_id, policy_version_id, decision, rule and reason. Empty on allow.") usage: PolicyUsage | None = Field(None, description="On allow: the deciding policy's counters for the day and the month before this send.") @@ -2145,6 +2146,7 @@ class TopupSession(_Response): created_at: str expires_at: str | None completed_at: str | None + checkout_status: Literal["open", "complete", "processing", "expired"] | None = Field(None, description="Stripe's own state of the hosted Checkout, read from Stripe when a read of an open top-up asks with check_checkout=true. complete: the payment was made at Stripe, and the wallet is credited when Stripe's event arrives, usually within seconds. processing: the person finished at Stripe with a payment method that confirms later, such as a bank debit, which can take days. Null when not asked, or when Stripe could not be read.") class TopupSessionPage(_Response): diff --git a/tests/conftest.py b/tests/conftest.py index 0d276ee..bfe9474 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -170,3 +170,25 @@ def topup_session(**over: Any) -> dict[str, Any]: "completed_at": None, } return {**base, **over} + + +def delivery(**over: Any) -> dict[str, Any]: + base = { + "id": "dlv_1", + "webhook_id": "wh_1", + "webhook_url": "https://example.com/hooks/fax", + "event_id": "evt_1", + "event_type": "fax.delivered", + "attempt": 1, + "status": "pending", + "response_status": None, + "error": None, + "duration_ms": None, + "replay_of": None, + "schedule_s": [0, 60, 300], + "next_attempt_at": None, + "created_at": "2026-11-15T09:00:00Z", + "delivered_at": None, + "webhook_deleted": False, + } + return {**base, **over} diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 1dff615..e42a2c5 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -17,6 +17,8 @@ Capabilities gains `one_time` from the updated snapshot. At API 1.20.0, server revision `3c06d076f0f5cfe477c42b71857cbdda9767884e`, the number gains `email_pdf` from `numbers/service.py`. The extraction page loses `cost_micro`, which `ocr/service.py` no longer sends. +At API 1.20.10, server revision `da29794e1fb66a7f1486680a08a5d16402aee435`, the top-up session gains `checkout_status` from `billing/wallet.py`. +It is null unless a read of an open top-up asks with `check_checkout=true`. ## One-time sends (`one-time.json`) diff --git a/tests/fixtures/billing-pages.json b/tests/fixtures/billing-pages.json index 82472e0..0092f62 100644 --- a/tests/fixtures/billing-pages.json +++ b/tests/fixtures/billing-pages.json @@ -57,7 +57,8 @@ "error": null, "created_at": "2026-11-02T00:00:00Z", "expires_at": null, - "completed_at": "2026-11-02T00:00:00Z" + "completed_at": "2026-11-02T00:00:00Z", + "checkout_status": null } ], "next_cursor": "top_2" @@ -78,7 +79,8 @@ "error": null, "created_at": "2026-11-02T00:00:00Z", "expires_at": null, - "completed_at": "2026-11-02T00:00:00Z" + "completed_at": "2026-11-02T00:00:00Z", + "checkout_status": null } ], "next_cursor": null diff --git a/tests/fixtures/responses.json b/tests/fixtures/responses.json index 702a170..0541227 100644 --- a/tests/fixtures/responses.json +++ b/tests/fixtures/responses.json @@ -361,7 +361,8 @@ "error": null, "created_at": "2026-11-02T00:00:00Z", "expires_at": null, - "completed_at": "2026-11-02T00:00:00Z" + "completed_at": "2026-11-02T00:00:00Z", + "checkout_status": null } }, { diff --git a/tests/test_async.py b/tests/test_async.py index 87df24e..dffa5c8 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -3,10 +3,11 @@ from __future__ import annotations import httpx +import pytest import respx -from faxforagents import AsyncClient -from tests.conftest import api_key_with_secret, fax_job, quote, topup_session +from faxforagents import AsyncClient, ConflictError +from tests.conftest import api_key_with_secret, delivery, error, fax_job, quote, topup_session async def test_async_send_and_wait(aclient: AsyncClient, api: respx.MockRouter) -> None: @@ -257,3 +258,29 @@ async def test_async_topup_cancel_statement_type_and_cover_check( room = await aclient.one_time_sends.check_cover(subject="Form", message="Hello") assert room.fits is True and room.lines_left == 30 assert json.loads(cover.calls.last.request.content) == {"subject": "Form", "message": "Hello"} + + +async def test_async_topup_checkout_read_and_a_deleted_webhook( + aclient: AsyncClient, api: respx.MockRouter +) -> None: + tid = topup_session()["id"] + read = api.get(f"/v1/topup-sessions/{tid}") + read.side_effect = [ + httpx.Response(200, json=topup_session(checkout_status="processing")), + httpx.Response(200, json=topup_session(checkout_status=None)), + ] + found = await aclient.billing.get_topup_session(tid, check_checkout=True) + assert found.checkout_status == "processing" + assert dict(read.calls[0].request.url.params) == {"check_checkout": "true"} + assert (await aclient.billing.get_topup_session(tid)).checkout_status is None + assert read.calls[1].request.url.query == b"" + replay = api.post("/v1/webhook-deliveries/dlv_1/replay") + replay.side_effect = [ + httpx.Response(202, json=delivery(id="dlv_3", replay_of="dlv_1")), + httpx.Response(409, json=error("conflict", "deleted", details={"reason": "webhook_deleted"})), + ] + again = await aclient.webhooks.replay_delivery("dlv_1") + assert again.replay_of == "dlv_1" and again.webhook_deleted is False + with pytest.raises(ConflictError) as exc: + await aclient.webhooks.replay_delivery("dlv_1") + assert exc.value.details == {"reason": "webhook_deleted"} diff --git a/tests/test_client.py b/tests/test_client.py index b58cf38..2b646c3 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -21,7 +21,17 @@ ScopeError, ServerError, ) -from tests.conftest import BASE, KEY, api_key_with_secret, document, error, fax_job, quote, topup_session +from tests.conftest import ( + BASE, + KEY, + api_key_with_secret, + delivery, + document, + error, + fax_job, + quote, + topup_session, +) def test_bearer_header_and_user_agent(client: Client, api: respx.MockRouter) -> None: @@ -1070,3 +1080,45 @@ def test_an_automatic_topup_receipt_has_no_pdf(client: Client, api: respx.MockRo ) found = client.billing.get_topup_receipt(tid) assert found.pdf_url is None and found.url.endswith("/receipts/payment/1") + + +def test_a_topup_read_asks_stripe_only_when_told(client: Client, api: respx.MockRouter) -> None: + """API 1.20.10: check_checkout reads the hosted Checkout at Stripe. The default sends nothing.""" + tid = topup_session()["id"] + route = api.get(f"/v1/topup-sessions/{tid}") + route.side_effect = [ + httpx.Response(200, json=topup_session(checkout_status=None)), + httpx.Response(200, json=topup_session(checkout_status="complete")), + httpx.Response(200, json=topup_session()), + ] + plain = client.billing.get_topup_session(tid) + assert plain.status == "open" and plain.checkout_status is None + assert route.calls[0].request.url.query == b"" + paid = client.billing.get_topup_session(tid, check_checkout=True) + assert paid.status == "open" and paid.checkout_status == "complete" + assert dict(route.calls[1].request.url.params) == {"check_checkout": "true"} + older = client.billing.get_topup_session(tid, check_checkout=False) + assert older.checkout_status is None + assert route.calls[2].request.url.query == b"" + + +def test_a_delivery_to_a_deleted_webhook_is_not_replayed(client: Client, api: respx.MockRouter) -> None: + """API 1.20.10: every delivery says whether its webhook was deleted, and a replay of one answers 409.""" + ended = delivery(status="failed", error="the webhook was deleted", webhook_deleted=True) + older = delivery(id="dlv_2") + older.pop("webhook_deleted") + listed = api.get("/v1/webhook-deliveries").respond( + 200, json={"items": [ended, older], "next_cursor": None} + ) + items = client.webhooks.list_deliveries(webhook_id="wh_1").items + assert items[0].webhook_deleted is True and items[0].next_attempt_at is None + assert items[1].webhook_deleted is None + assert dict(listed.calls.last.request.url.params) == {"webhook_id": "wh_1"} + details = {"reason": "webhook_deleted"} + replay = api.post("/v1/webhook-deliveries/dlv_1/replay").respond( + 409, json=error("conflict", "the webhook of this delivery was deleted", details=details) + ) + with pytest.raises(ConflictError) as exc: + client.webhooks.replay_delivery("dlv_1") + assert exc.value.code == "conflict" and exc.value.details == details + assert len(replay.calls) == 1 diff --git a/tests/test_one_time.py b/tests/test_one_time.py index c2d4ccd..cf37e68 100644 --- a/tests/test_one_time.py +++ b/tests/test_one_time.py @@ -462,3 +462,19 @@ def test_cover_check_is_refused_while_one_time_sends_are_off(keyless: Client, ap with pytest.raises(ServerError) as exc: keyless.one_time_sends.check_cover(message="hi") assert exc.value.status == 503 and exc.value.code == "one_time_unavailable" + + +def test_cover_check_refuses_a_field_over_the_limit_of_the_create( + keyless: Client, api: respx.MockRouter +) -> None: + """API 1.20.10: the cover check states the limits of the create and refuses a longer field as it does.""" + route = api.post("/v1/one-time-sends/cover-checks").respond( + 422, + json=error( + "invalid_request", "cover.message is longer than 2000 characters", details={"field": "cover"} + ), + ) + with pytest.raises(InvalidRequestError) as exc: + keyless.one_time_sends.check_cover(message="x" * 2001) + assert exc.value.status == 422 and exc.value.details == {"field": "cover"} + assert len(json.loads(route.calls.last.request.content)["message"]) == 2001