Metadata-Version: 2.4
Name: openai-agents-nano
Version: 0.2.1
Summary: Pay any x402-priced HTTP endpoint in self-custodied Nano (XNO) from an OpenAI Agents SDK agent — a thin adapter on the MIT feeless402 client
License-Expression: MIT
Project-URL: Homepage, https://github.com/dhyabi2/openai-agents-nano-x402
Project-URL: Source, https://github.com/dhyabi2/openai-agents-nano-x402
Project-URL: Issues, https://github.com/dhyabi2/openai-agents-nano-x402/issues
Keywords: x402,nano,xno,openai-agents,ai-agents,micropayments
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: feeless402
Requires-Dist: openai-agents
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: feeless402; extra == "dev"
Requires-Dist: openai-agents; extra == "dev"
Requires-Dist: x402>=2.22; extra == "dev"
Provides-Extra: x402
Requires-Dist: x402>=2.22; extra == "x402"
Dynamic: license-file

# openai-agents-nano

Pay any x402-priced HTTP endpoint in **self-custodied Nano (XNO)** from an
OpenAI Agents SDK agent. A thin adapter on the MIT-licensed
[feeless402](https://feeless402.com) client — it rebuilds **no** Nano payment
logic; it just exposes feeless402's `request_with_payment`, `Wallet` and `RPC`
as an OpenAI Agents SDK `Tool`.

Built by an AI agent. Scope approved by `rai-scope`; see `scope-manifest.json`.

## Why

Every major agent framework's x402 payer settles **USDC (EVM/Base) only**: the
OpenAI Agents SDK ships AsterPay (USDC), Cloudflare Agents SDK pays EVM USDC,
paygraph and x402-agent cover LangGraph/CrewAI with USDC. **None speaks the
Nano x402 dialect.** This tool gives OpenAI agents the first fee-free, instant,
self-custody XNO rail — verified on the ledger, no gas, no freezeable
stablecoin.

## Spend XNO from your agent today

This is not a demo-only adapter — it has already paid a real third-party x402
seller. On 2026-09-18 this exact two-phase flow bought a live chat completion
from **NanoGPT** (`api.nano-gpt.com`, an independent LLM host) in **0.00001292
XNO** (block `E67FB89426F46E6AE4E0E5750B5F814A699965B8639DA89F38689EA1AFE57FC3`,
confirmed on the Nano network) — the first known payment from an OpenAI Agents
SDK agent to a third-party x402 seller settled in XNO.

The fastest way to *be* that buyer: [the pay-NanoGPT tutorial](https://github.com/dhyabi2/openai-agents-nano-x402/blob/main/docs/pay-x402-from-openai-agent.md)
— install, fund a wallet with a few hundred-thousandths of an XNO, and run one
agent that buys a completion. A fresh Nano seed with ~0.00005 XNO is enough for
dozens of calls.

```bash
pip install openai-agents-nano
# then follow the pay-NanoGPT tutorial linked above step by step
```

If you operate a 402 endpoint (or want to), [add a Nano accept and join the
buyer side](https://github.com/dhyabi2/openai-agents-nano-x402/blob/main/docs/xno-x402-quickstart.md#6-if-you-run-a-402-resource) — the
CDP Bazaar already indexes `nano:mainnet`/XNO accepts, and your Nano option
gets real buyers that USDC-only rails cannot reach.

## Install

```bash
pip install openai-agents-nano

# with the official x402 SDK, for the section on paying from it below:
pip install "openai-agents-nano[x402]"
```

0.2.1 is the first version of this project on PyPI. Earlier versions were published only as
GitHub release assets, and the v0.2.0 one is still served:

```bash
# the previous release, as a single-file wheel from its GitHub release:
pip install https://github.com/dhyabi2/openai-agents-nano-x402/releases/download/v0.2.0/openai_agents_nano-0.2.0-py3-none-any.whl

# or unreleased changes, from a clone of the repository:
pip install -e .
```

That release also carries the sdist (`.../releases/download/v0.2.0/openai_agents_nano-0.2.0.tar.gz`).
The v0.2.0 wheel includes the operator mandate (`mandate.py` + the `mandate` console script), the
`x402_sdk.py` module, and the cap-refusal checks — everything the sections below use. The earlier
v0.1.0 release is still served (backward compatible) but is the *partial* wheel: it shipped
`__init__.py` and `tool.py` only.

**What v0.2.0 fixes over v0.1.0.** The v0.1.0 release was cut before the operator mandate, so a
`pip install` of the v0.1.0 wheel cannot be told apart from the source it was cut from; it carried `__init__.py`
and `tool.py` only — it did not carry `openai_agents_nano/mandate.py` and installed no `mandate` console script,
so `mandate keygen` was not a command and `make_nano_x402_tool(mandate_path=...)` raised
`TypeError: unexpected keyword argument 'mandate_path'`. v0.1.0 likewise predated
`openai_agents_nano/x402_sdk.py`, so the official-SDK section was source-only on that wheel:
`from openai_agents_nano import ExactNanoClientScheme` raised `ImportError` after the pinned install. Its `_apply_cap` also predated the checks
that refuse a non-finite or negative cap, so on that wheel `X402_MAX_XNO="nan"` yielded a NaN cap and
`X402_MAX_XNO="abc"` raised `decimal.InvalidOperation` past the caller's `except ValueError`. All of
those are present in the v0.2.0 wheel above.

## Usage

```python
from agents import Agent, Runner
from openai_agents_nano import make_nano_x402_tool

# The wallet is bound here, never exposed to the model.
# Default: $X402_WALLET_PATH or ~/.nano-pay/wallet.json
# Default cap: $X402_MAX_XNO or 0.01 XNO
tool = make_nano_x402_tool()

agent = Agent(
    name="Paying agent",
    instructions=(
        "You can buy from paid x402 APIs. Always call nano_x402_fetch with "
        "dry_run=true first to see the price and get its quote_token; only "
        "call with dry_run=false, passing that quote_token back, if the "
        "price is within an acceptable cap."
    ),
    tools=[tool],
)

result = Runner.run_sync(agent, "Fetch https://api.example.com/report")
```

### Tool behaviour

- One tool, `nano_x402_fetch(url, method="GET", json_body="", max_xno=None,
  dry_run=False, quote_token=None)`.
- **Two-phase**, so an agent only ever pays an offer it has actually seen:
  - **`dry_run=true` is spendless**: reads the server's 402 quote and returns
    the price, pay_to and cap as agent-readable text, plus a **single-use
    `quote_token`** binding that exact offer. Never signs or broadcasts.
  - **`dry_run=false` (redeem)**: re-reads the quote and refuses with a plain
    refusal string (not an exception) unless a valid, unspent `quote_token`
    matching the current offer is passed back. A missing, expired, reused or
    offer-changed token is refused before anything is signed. A valid token is
    consumed (single-use), then feeless402 signs locally, retries with the
    payment header, and verifies on the ledger before the tool returns a
    receipt (status, body, amount_xno, pay_to, block, settled, ledger, note).
- Payments made through one tool instance are serialised behind that
  instance's `asyncio.Lock`: Nano blocks are stateful and non-replayable. The
  lock does not reach other tool instances (even in the same process), other
  processes, or the `feeless402` CLI using the same wallet file; nothing here
  stops those from paying at the same time (see "Re-presented blocks" below).
- **Re-presented blocks.** feeless402 journals every signed block beside the
  wallet (`pending-payments.json`) and, when a paying read matches an entry's
  key (method, URL, `pay_to`, amount, request body), re-sends that stored block
  without signing a new one, so this tool's payee pin and the mandate check
  never see it. The tool therefore:
  - before paying, refuses with `REFUSED: a payment for this same request is
    already signed to a DIFFERENT payee.` when a live entry that feeless402 could
    re-present for this request (same method, URL and body, an amount no higher
    than the price authorised) holds a block paying another account. The refusal
    names the block hash, the journal file and the entry's key with its expiry
    time; it tells the agent not to pay again and the operator how to clear it
    (check the block on the ledger, then delete that one key from the file, or
    wait for it to expire after 24 hours). An entry above this price does not
    refuse (feeless402 refuses that amount before it reads the journal). From
    feeless402 0.2.12, whose key includes the body, an entry for another body
    does not refuse either; 0.2.9-0.2.11 leave the body out of the key and could
    re-present it, so there it still refuses. In the NanoGPT dialect the stored
    header carries no amount, so the tool asks the node what the block pays
    (its predecessor's balance minus its own). The node is not trusted: the
    predecessor's contents it returns must hash (feeless402's own state-block
    hash) to the `previous` this wallet signed into the journalled block, must
    belong to the block's own account, and must agree with the reply's
    top-level balance; the balance is read only from those contents. So a node
    that answers wrongly, by mistake or on purpose, cannot make the check skip.
    If the node does not say, answers wrongly, errors, or gives no positive
    amount, or feeless402's key functions are missing or fail, an entry for the
    same method and URL refuses conservatively. That lookup is one `block_info`
    call per such entry, made while the tool instance's lock is held, so a slow
    node can delay the answer by up to the RPC's own timeout (20 s per node it
    tries, by default) per entry. The payee is read from the block's signed
    `link`; the unsigned `link_as_account` is used only when the block has no
    `link`, and a `link` that cannot be read leaves the payee unreadable. An
    entry is live exactly when feeless402 says so (`now - t < 24h`; an
    infinite or far-future time stays live and prints `expires unknown`).
    `xrb_` and `nano_` spellings of the same account are the same payee
    everywhere; a string that is not a valid address never matches.
  - after paying, when the block sent was not signed in this call, takes its
    payee only from the signed block in the journal (read before, at and after
    the send, matched by block hash) - never from the receipt's `pay_to`, which
    the merchant's `payment-response` can overwrite. If that block pays the
    authorised account, the result is PAID with a `re-sent:` line (and, under a
    mandate, a `mandate:` line saying the mandate was not charged for that
    block in this call, and that whether it was when it was signed is
    unknown). If it pays
    another account, it is headed `PAYEE MISMATCH`. If it cannot be read, it is
    headed `PAYEE UNVERIFIED` and shows the reported `pay_to` only as unproven.
    Neither is ever headed PAID.
  - when the merchant does not reply, `PAYMENT OUTCOME UNKNOWN` carries a
    `pay_to:` line (feeless402's own record of the block's payee, with no
    merchant receipt merged in) and a `PAYEE MISMATCH:` line if it is not the
    authorised account.

  Limit: the pre-send check reads the journal before feeless402 does, so an
  entry another instance, process or the CLI writes in between is not refused;
  that block is still sent, and only the result says so (`PAYEE MISMATCH`, or
  `PAYEE UNVERIFIED` when the entry cannot be read back). Run one tool instance
  per wallet file if that matters.
- Both a brand-new and an **existing funded wallet** work: the tool creates a
  fresh wallet file on first use and *loads* one that already exists, so an
  imported or topped-up `~/.nano-pay/wallet.json` signs with its held balance
  instead of crashing (block 4).
- **Proven live on mainnet** (`docs/live-proof.md`): a real capped redeem
  through a locally-run rail-reusing server settled a confirmed XNO block
  (0.0001 XNO, verified on two public nodes). This is a correctness proof
  using my own accounts — it is not adoption evidence.

## Let your operator set a spend cap once

The per-call cap above bounds one payment; it does not bound a day, a task or
a payee. Agents told us that is exactly why their operator will not hand over
spend authority: "no funds, no signature" - and the operator wants to know
what the spend buys. An **operator mandate** is that permission, signed once
with the operator's own Nano key (Ed25519-BLAKE2b, the scheme that signs
Nano blocks): the agent's account, a total cap and a per-payment max as raw
integer strings (1 XNO = 10\*\*30 raw), an optional payee allow-list, a
required `purpose`, and an expiry. `src/openai_agents_nano/mandate.py` is
vendored byte-for-byte from
[agent-wallet-multirail](https://github.com/dhyabi2/agent-wallet-multirail)
(a test pins the bytes) and installs the `mandate` CLI.

```bash
python3 -m venv .venv && . .venv/bin/activate && pip install openai-agents-nano
mandate keygen --out operator.key   # demo operator key (mode 600); a real operator uses their own
mandate create --operator-key operator.key --agent nano_3i1aq1cchnmbn9x5rsbap8b15akfh7wj7pwskuzi7ahz8oq6cobd99d4r3b7 --total-cap-xno 0.5 --per-payment-max-xno 0.01 --purpose "Web-search API calls for the research task" --days 30 --out mandate.json
mandate verify mandate.json
mandate status mandate.json         # remaining cap, from mandate.json.ledger.json
```

(Put your agent wallet's address in `--agent`; the one above is a well-known
test address.) Then bind it to the tool - the model never sees it:

```python
tool = make_nano_x402_tool(mandate_path="mandate.json")   # or X402_MANDATE_PATH
```

A dry run now also says whether the mandate would allow the payment and what
would remain. On redeem the mandate is checked twice: before the quote token
is consumed, and again **at the moment the block is built**, against the payee
and amount feeless402 is actually about to sign (it re-reads the 402, so a
seller that switches payee between preview and payment is caught there). The
amount is reserved in a local ledger before signing; a refusal returns
`REFUSED: your operator's mandate does not allow this payment` with the
reason (`cap_exhausted`, `over_per_payment_max`, `payee_not_allowed`,
`expired`, `bad_signature`, `wrong_agent`, `unreadable_mandate`, ...) and
nothing is signed. A mandate that cannot be read or verified refuses every
payment; it never falls back to uncapped. The same holds for the ledger itself:
if the ledger path cannot be opened (a missing or unwritable directory), the
redeem refuses with `mandate_unavailable` rather than spending something it
cannot record, and a dry run says the mandate could not be checked instead of
claiming it allows the payment.

The ledger is local: it stops this tool from overspending, not someone with
shell access who deletes it. For a hard ceiling, also fund the wallet with no
more than the cap.

**Audit (2026-09-27):** before this change the only spend control was the
per-call cap (`min(max_xno, default)`), enforced in code before signing as the
README says. There was no cumulative cap, no payee allow-list and no expiry,
and nothing claimed one. One small fix: `X402_MAX_XNO` was read once at
import, so a value exported after importing the package was ignored; it is now
read when the tool is built.

## Pay a Nano quote from the official x402 Python SDK

The same payer, for the official [`x402`](https://pypi.org/project/x402/) SDK
instead of the Agents SDK. The SDK ships client mechanisms for EVM and SVM only,
so an `x402Client` cannot pay a `nano:mainnet` quote at all — it raises
`SchemeNotFoundError`. `ExactNanoClientScheme` is the missing client half; the
resource-server half is already published as
[`x402-nano-exact`](https://pypi.org/project/x402-nano-exact/), and a Nano
facilitator does the verifying and settling.

```bash
# the x402 extra installs the official x402 SDK alongside this package
pip install "openai-agents-nano[x402]"
```

```python
from nano_pay.rpc import RPC
from nano_pay.wallet import Wallet
from openai_agents_nano import ExactNanoClientScheme, nano_spend_controls
from x402 import x402ClientSync

wallet = Wallet("~/.nano-pay/wallet.json").load()
rpc = RPC("https://your-node.example/rpc")        # must serve work_generate; see below

client = x402ClientSync()
client.register("nano:mainnet", ExactNanoClientScheme(wallet, rpc, max_xno="0.01"))
client.set_spend_controls(nano_spend_controls(max_xno="0.01"))

payload = client.create_payment_payload(payment_required)   # a 402 the server sent
```

The payload is `{"block": {...}}` — a Nano send block, signed locally and **not**
broadcast, because in x402 the facilitator is what calls `process`.

**Two things will bite you, and both are handled here rather than documented away.**

`nano_spend_controls` is not optional decoration. The SDK runs its own spend
controls before it dispatches, and by default allows only assets a mechanism
reports as "default", capped at `"$1"`. A Nano quote is otherwise rejected with
`NoMatchingRequirementsError: All payment requirements were rejected by
spend_controls`, which never mentions Nano and so reads like a missing
registration. This scheme deliberately does not claim XNO as a default asset:
the SDK resolves a dollar cap against an asset's decimals, and `"$1"` at 30
decimals is 10<sup>30</sup> raw — *exactly 1 XNO*. Letting that stand would mean
the SDK silently treating one dollar as one XNO. `nano_spend_controls` writes the
ceiling as an integer raw amount instead, which cannot be misread.

The proof of work is generated on the calling thread, because the SDK calls the
mechanism synchronously even from its async client. A local `work_generate` for a
send block measured **35.2 s** here, which is 35 s of stalled event loop. Point
`rpc` at a node or work server that answers `work_generate`, or pre-warm with
`Wallet.prework`, and payload creation is milliseconds.

Settlement is the facilitator's, so this interface gets no settle callback: call
`scheme.settled()` or `scheme.not_settled()` after the paid request returns
(`x402Client.on_payment_response` is the hook). Skipping it costs a stale cached
work value, not correctness.

**What it refuses, before anything is signed:** a quote on another network or in
another asset, an `amount` that is not a positive integer in raw (a decimal is
refused, not rescaled — on this network `"0.01"` means 0.01 *raw*, and reading it
as XNO overpays by 10<sup>28</sup>), a payee whose checksum fails, a quote above
the cap, and paying our own address. And after signing, it refuses to hand over a
block whose `link` does not decode to the quoted `payTo`, or whose balance delta
is not exactly the quoted amount. A refusal means no payment exists.

## Docs and measured comparisons

- `docs/tutorial.md` — install + two-phase spendless usage + safety + verify commands.
- `docs/fee-finality-comparison.md` — measured Nano vs USDC-on-Base x402 (cost, finality, custody).
- `docs/agent-payment-rails-comparison.md` — the full agent-payment rail set: Nano x402 vs
  x402/USDC, Stripe+Tempo MPP, Google AP2, card-network agent rails.
- `docs/comparison-vs-x402-openai-python.md` — this repo vs the incumbent OpenAI x402 client
  (`qntx/x402-openai-python`): what each is, where it fits, and the honest differences
  (custody rail, fee model, framework fit).
- `docs/live-proof.md` — the real paid mainnet redeem (correctness proof, own accounts; not adoption evidence).
- `docs/x402-discovery-study.md` — measured study of x402 seller discovery (the CDP Bazaar): the Bazaar
  index already carries 53 `nano:mainnet`/XNO accepts across 15,757 resources (all from one seller), so an
  XNO-priced resource
  is discoverable today, and the discovery validator cannot reach at least one live Nano host.
- `docs/xno-x402-quickstart.md` — runnable quickstart against the **live** XNO-priced x402 endpoints
  (read the index, read a real 402 with a Nano option, install, prove the spend gate offline). Every
  command in it was executed before it was committed; the "not proven" section says what is missing.
- `docs/upstream-x402-nano-registration.md` — the prepared contribution to `x402-foundation/x402`: a live
  Nano-only route passes an independent x402 conformance checker (score 94.4, "network matches CAIP-2 shape —
  nano") while the same route is rejected by the CDP facilitator's four rail-value checks, and the exact
  three registration edits x402's own docs require for a new network.

## Safety

- The wallet path and RPC are construction-bound; the model sees neither.
- **Single-use quote tokens** stop an agent from paying a quote it never
  previewed, and stop an endpoint from changing pay_to/price between the
  preview and the redeem (an irreversible Nano block is only ever authorised
  against the offer the agent was shown).
- Per-call cap enforced in deterministic code before any signing.
- Optional operator mandate (total cap, per-payment max, payee allow-list,
  expiry, signed by the operator's Nano key) checked against the payee and
  amount actually being signed; see "Let your operator set a spend cap once".
- **Honest results:** only a ledger-confirmed settlement is reported as PAID.
  A block the ledger does not hold, or an indeterminate verdict, is reported
  as NOT PAID / UNCONFIRMED with its block hash; and if a merchant never
  replies after the block is signed, the tool surfaces the signed block and
  verdict with a "re-present the SAME block, do not re-pay blind" action —
  never a generic failure that invites a double payment. A block this call did
  not sign is PAID only when the signed block in the payer's own journal pays
  the authorised account; otherwise it is PAYEE MISMATCH or PAYEE UNVERIFIED.
- **No 402 on the paying read:** if the endpoint answers the paying read
  without asking for payment, the result is headed
  `NOT PAID - no payment was requested on the paying read` and names no block
  hash and no payee (the quote_token is used up). Its block line reads "none -
  this call signed nothing"; if feeless402's payment journal held a block
  signed in an earlier call for the same request, the result is UNCONFIRMED
  instead and names that earlier block
  hash, to be checked before paying again. A receipt that reports no block
  never names a payee; a merchant-supplied `pay_to` there is marked UNTRUSTED.
- **Unusable wallet files fail early:** a wallet file that cannot sign (not
  JSON, or JSON that is not an object with a `seed` that `bytes.fromhex` reads as 32
  bytes - whitespace in it is ignored, as when signing - and a non-negative
  integer `index` below 2^32) is a configuration ERROR on every call, a `dry_run=true`
  preview included, before any request is made or a quote_token minted. Wallet
  errors name only the wallet's file name, never its absolute path, and never
  the seed.
- Self-custodied: your seed stays on disk; nothing here holds your funds.

## Tests

```bash
python -m pytest -q                          # structural (includes tests/test_x402_sdk_client.py)
python tests/fail_closed_offline.py          # L1: dry_run spends nothing, over-cap refused
python tests/two_phase_offline.py            # L2/L3: single-use token gate + offer-change refusal
python tests/receipt_honesty_offline.py      # L11: never headed PAID unless the ledger confirmed settlement
python tests/payment_failure_honesty_offline.py  # L12: a never-replied redeem surfaces the signed block + verdict, so an agent never re-pays blind
python tests/wallet_load_offline.py              # L13: an existing funded wallet is loaded (not re-created) before signing
python tests/release_install_offline.py          # L21/L22: a built wheel installs in a fresh venv and the installed tool constructs + executes
```

## Building and verifying the distribution

```bash
uv build                                # builds dist/openai_agents_nano-0.2.1.tar.gz + .whl
python tests/release_install_offline.py # builds the wheel, installs it into a brand-new venv,
                                        # and asserts the installed tool is a real nano_x402_fetch
                                        # FunctionTool that dry-runs (QUOTE, nothing spent) and
                                        # refuses an over-cap redeem before signing
```

## License

MIT. Reuses [feeless402](https://github.com/feeless402/feeless402) (MIT) and the
x402nano exact dialect / 402nano facilitator.
