Metadata-Version: 2.5
Name: getaccord
Version: 0.9.2
Summary: Payments AI agents can't get wrong: sellers paid together in one step when the purchase completes; called off, only work already accepted is paid and every other hold comes back; within limits enforced when money moves, with a public record of each purchase.
Project-URL: Homepage, https://useaccord.ai
Project-URL: Repository, https://github.com/MystenLabs/accord
Project-URL: Issues, https://github.com/MystenLabs/accord/issues
Author: Accord
License-Expression: Apache-2.0
Keywords: ai agents,payments,sui,x402
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: cryptography>=42
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# getaccord (Python)

Payments AI agents can't get wrong. Sellers paid as agreed, or your money comes back: hold money with sellers. Sellers are paid together, in one step, when your agent completes the purchase. If it's called off instead, only work it already accepted is paid, and every other hold comes back. Within limits: they're enforced when money moves, so the agent can't talk its way past them. On the record: every purchase gets a public record that buyer and seller can both check. The same API as [`@getaccord/sdk`](https://www.npmjs.com/package/@getaccord/sdk), for Python 3.9+.

Test mode: test dollars only.

## Quickstart

1. Make an agent key in your project folder. It's created on your machine and never leaves it:

   ```bash
   npx @getaccord/cli init
   ```

   This writes `ACCORD_AGENT_KEY` to `.env`, which the Python SDK reads as is.

2. Install:

   ```bash
   pip install getaccord
   ```

3. Buy something: hold money with each seller, then commit.

   ```python
   from getaccord import Accord

   accord = Accord()                        # reads ACCORD_AGENT_KEY and ACCORD_URL from the env or ./.env
   intent = accord.intent(budget=4500)      # whole cents; budget_micros= for exact sub-cent amounts
   intent.hold("skyfare", 3000, ref="SFO to JFK")
   intent.hold("stayco", 1500, ref="2 nights")
   result = intent.commit()                 # every seller is paid, or none is
   print(result.status, result.intent["proofUrl"])
   ```

Amounts are whole cents (`int`) or exact micros (`amount_micros=`, millionths of a dollar). Floats are refused, so no amount is ever rounded.

## Buying

| | |
|---|---|
| `accord.intent(budget, *, budget_micros, coin, mode, expires_in, key)` | Opens a purchase. `coin`: the usual dollar coin or `"USDC"`. `mode`: `"all"` (everyone or no one) or `"each"`. |
| `intent.hold(seller, amount, *, amount_micros, ref, type)` | Locks money with one seller. `type`: `"reserve"` or `"deliver"`. |
| `intent.holds([...])` | Several holds in one step (one transaction). |
| `intent.commit(wait="60s")` | Waits for every seller to confirm, then pays them all. In `"all"` mode a decline or timeout releases everything. |
| `intent.abort()` | Calls it off; every held dollar comes back. |
| `intent.results()`, `intent.accept(i)`, `intent.reject(i)` | Deliver holds: check the work before anyone is paid. |
| `accord.resume(intent_id)` | A purchase made earlier, by its ID: commit, abort or add holds after a restart. |
| `accord.balance()` | What's available, what's left of the key's weekly budget, and the sellers it may pay (`allowedSellers`). |
| `accord.list_sellers(key=None, query=None, include_inactive=False)` | Accord's seller directory: who sells what, and whether this key may pay each one. Paused sellers only with `include_inactive=True`. |
| `accord.link(condition, members, key=None, expires_in=None)` | A linked purchase: several purchases settled together under one condition. |

Errors are `AccordError` with a stable `.code` (`limit_exceeded`, `seller_not_allowed`, `insufficient_balance`, `awaiting_approval`, `too_many_holds`, ...) and a message that says what to do. Also:

| Code | When |
|---|---|
| `tx_mismatch` | The service's transaction isn't exactly the step asked for, its objects aren't this agent's on chain, or the SDK can't tell which package to trust. Nothing was signed. |
| `intent_mismatch` | A purchase opened, but the service named a different purchase from the one on chain. The step ran; use the ID in the message. |
| `busy_prepare_again` | The network turned a step away after the service had used its preparation. The SDK checks the step didn't land, then prepares, checks, signs and sends it once more; you see this only if that also fails. Nothing was changed or paid. |
| `bad_condition` | A linked purchase's condition can't be read, doesn't name exactly its members, or a member is wrong (2 to 10 members, each with holds). |
| `condition_unmet` | `settle()` before the condition is decided. Nothing was paid; wait, or `cancel()`. |

`condition_impossible` isn't raised: it starts the `"reason"` of a `settle()` that called everything off. On the dashboard and its API, a cash-out whose payout account changed since the last one is refused with `payout_changed` until the person confirms the new account.

A purchase over the key's sign-off limit waits for a person: `hold()` raises `awaiting_approval` and no money is locked. For a test key, the owner approves it with `accord.test.approve(intent.id, owner_token)`, passing the owner token `init` saved to `~/.accord/owner-<key id>`. The file holds comment lines and one line `ACCORD_OWNER_TOKEN=own_…`: pass only the `own_…` value. The SDK never reads that file itself, so an agent with only its key can't approve its own purchases. Dashboard keys are approved at app.useaccord.ai.

After a restart, `accord.resume(intent_id)` picks a purchase up again to commit or abort it.

Async: `AsyncAccord` has the same methods, awaitable.

```python
import asyncio
from getaccord import AsyncAccord

async def main():
    accord = AsyncAccord()
    intent = await accord.intent(budget=4500)
    await intent.hold("skyfare", 3000)
    result = await intent.commit()
    print(result.status)

asyncio.run(main())
```

## Finding sellers

`list_sellers` reads Accord's seller directory: each seller's description, its offers (a price or a price range, paid when the seller confirms or once you accept delivered work), and whether it takes payments now. With a key (yours from `.env`, or `key=`), each seller also has `allowed`, and for one this key can't pay, `howToAllow`: how its owner allows it. `query` keeps the sellers whose name, description or offers mention it.

```python
for s in accord.list_sellers(query="price data"):        # uses the key in .env
    print(s["seller"], [o["name"] for o in s["offers"]], "may pay" if s["allowed"] else s["howToAllow"])

b = accord.balance()
print([s["name"] for s in b["allowedSellers"]])           # the sellers this key may pay
print(b["allowSellersAt"])                                # where its owner allows more: the dashboard, or "cli" for a test key
```

The directory's fields keep the service's names (`displayName`, `paidOn`, `priceFrom`, `priceToMicros`, ...). Only the key's owner can allow a seller: `npx @getaccord/cli allow <seller>` for a test key, or the dashboard. `getaccord.how_to_allow(seller, at)` gives the same sentence.

Sellers set a description and offers with `accord.sellers.register(..., description=..., offers=[...])` or `accord.sellers.update(name, seller_token, description=..., offers=[...])`. An offer is `{"name": ..., "paidOn": "confirm" or "delivery", "price": cents}` or `{"name": ..., "paidOn": ..., "priceFrom": cents, "priceTo": cents}`; up to 10 offers, names up to 80 characters, a description up to 280. Sending `offers` replaces the whole list.

## Linked purchases

Some jobs need several sellers, but not all of them. A linked purchase settles several purchases (members) together under one condition. Each member is its own purchase (every hold or none); nothing is paid until `settle()`, which pays the chosen members and calls off the rest in one step.

A research brief needs research from scout, and price data from marketpulse or quantfeed, whichever is ready (marketpulse if both are), never both:

```python
import json

link = accord.link("scout and (marketpulse or quantfeed)", {
    "scout": {"holds": [{"seller": "scout", "amount": 20000, "type": "deliver", "ref": "Research brief: agent payments"}]},
    "marketpulse": {"holds": [{"seller": "marketpulse", "amount": 3000, "ref": "EUR/USD prices, last 24h"}]},
    "quantfeed": {"holds": [{"seller": "quantfeed", "amount": 3000, "ref": "EUR/USD prices, last 24h"}]},
})

status = link.wait()                       # until it's decided, or delivered work needs your decision
for m in status["members"]:
    for h in m["to_decide"]:
        good = my_check(json.loads(h["result"]))
        (link.accept if good else link.reject)(m["name"], h["index"])
status = link.wait()

result = link.settle()
# {"status": "paid", "paid": ["scout", "marketpulse"], "cancelled": ["quantfeed"], "digest": ..., "reason": None}
```

- **The condition** names every member once, with `and`, `or` and parentheses; `and` binds tighter than `or`. Member names are lowercase letters, digits, `-` and `_`. A link has 2 to 10 members. A condition that can't be read, or doesn't name exactly the members, is `bad_condition`.
- **Members**: each name maps to `{"holds": [{"seller", "amount" or "amount_micros", "type", "ref"}]}`, with an optional `"budget"` or `"budget_micros"` (default: the total of its holds) and `"coin"`.
- **`or` is a preference order**: the first option listed that is ready is paid, and the others are called off. An `or` never pays both.
- **`status()`** returns a dict with snake_case keys: `id`, `condition`, `members` (each with `name`, `intent_id`, `status`, `state`: `"ready"`, `"pending"` or `"failed"`, `to_decide`: delivered work waiting for your decision, `proof_url`) and `evaluation` (`{"state": "met", "pay": [...]}`, `{"state": "impossible"}` or `{"state": "pending"}`). The holds in `to_decide` are the service's hold dicts (`index`, `seller`, `result`, ...). `wait(timeout="60s")` returns once it isn't pending, or work needs a decision, or the time is up. It doesn't settle.
- **`settle()`**: condition met, it pays the chosen members and calls off the others in one transaction. If a paid hold isn't ready after all, the whole transaction fails and nobody is paid. If the condition can't be met any more (a needed seller declined, its work was rejected, a member expired), it calls everything off: `{"status": "cancelled", "reason": "condition_impossible: ..."}`, and the held money goes back. Before either, it raises `condition_unmet` and nothing is paid.
- **`cancel()`** calls every open member off in one transaction. `accept(member, index)` and `reject(member, index)` decide on a member's delivered work. `link.members` has each member's purchase by name.
- Each member waits at most `expires_in` (default `"15m"`, at most `"24h"`). A member over the key's sign-off limit waits for approval; once it's approved, the next `status()` or `wait()` places its holds.
- `AsyncAccord.link(...)` has the same methods, awaitable.

## Check before signing

Accord's service builds every transaction your agent key signs, and pays its network fee. The SDK doesn't take that on trust. Before signing, it decodes the transaction and signs it only if it does exactly the step you asked for. Anything else raises `tx_mismatch`, and nothing is signed. The message ends "Money already held for this purchase stays held until you abort() it or its deadline passes."

What it guarantees: the service can't change what your agent signs.

- **Exactly one transaction.** The bytes must decode and encode back to exactly the same bytes: nothing extra, nothing ambiguous.
- **Only Accord's package.** Every step is a call into Accord's contracts, whose package IDs are pinned in this SDK for each network (`getaccord.verify.ACCORD_PACKAGES`). No transfers, splits, merges, or calls into anything else.
- **Exactly the step asked for, and nothing more.** The purchase, budget, mode and expiry; each hold's seller, amount, kind (reserve or deliver) and ref; the hold number for `accept` and `reject`; for a linked purchase, which members are paid and which are called off.
- **The agent's own coins never pay.** The agent key is the sender, someone else pays the network fee, and holds draw on the owner's allowance, never the key's own money.
- **Seller names are checked on chain.** Each seller in the transaction must be Accord's seller registered under the name you asked for.
- **On chain, the objects are the agent's.** The SDK reads them before signing: the policy is this agent key's and allows the coin; each allowance drawn on is from the policy's owner, for this agent key, in this coin, under Accord's policy; a purchase the step works on is this agent key's, on that policy and in that coin. If the chain can't be read, nothing is signed.
- **The coin you name is that coin.** `coin="USDC"` must be USDC, by the coin types pinned in this SDK for each network (`getaccord.verify.ACCORD_COINS`); with no coin named, it must be one of Accord's dollar coins. A service on this machine lists its own coins in `/health`.
- **The chain's word, not the service's.** After a lost answer, whether a step landed is read from the chain. After a purchase opens, its ID is read from the chain too; if it differs from the service's, the SDK raises `intent_mismatch`. That one comes after signing: the step ran, and the message names the ID to use. `tx_mismatch` always means nothing was signed.

What it doesn't cover:

- **A stolen agent key.** Whoever has it can spend within the key's limits. The limits, enforced on chain, are what bound it: keep them tight, and revoke a key you think is exposed.
- **Mainnet, until a release pins it.** Mainnet's package is pinned in an SDK release at its publish. Until then this SDK signs nothing on mainnet ("This SDK doesn't know Accord's mainnet package yet. Update it: …"). A new test package also comes in an SDK release.
- **Services other than Accord's.** For a service on this machine (`127.0.0.1`, `localhost`), the SDK trusts the package its `/health` names: it's yours. For any other host, set `ACCORD_PACKAGE_IDS` (comma-separated) to the Accord package IDs it uses, or nothing is signed. The SDK reads the chain directly (Sui's public node for the network, or the local node at `127.0.0.1:9000` for a local network); `ACCORD_SUI_RPC` sets another.

The chain enforces the rest: the key's limits, its allowed sellers, and each purchase's rules.

## Paying x402 sellers

Sellers that charge per request with [x402](https://www.x402.org) can add an Accord option to their 402.

```python
from getaccord.x402 import pay

response = pay("https://seller.example/report")   # quote, hold, commit, fetch with the proof
print(response.status, response.json())
```

Several sellers in one purchase: `quote(url)`, `hold(intent, offer)` for each, `intent.commit()`, then `fetch_paid(offer, intent.id, result.digest, indexes)`.

Selling with x402: add `accord_requirement(pay_to=..., usd_cents=25, public_url='https://api.example.com')` (the URL buyers reach you at; required) to your 402's `accepts`, then check each paid request with `verify_accord_payment(header, requirement, resource=url)`. See `examples/x402_gateway.py`.

## Selling (webhooks)

Accord tells your server about each hold with a signed webhook. Answer whether you can deliver:

```python
from getaccord import Handler

handler = Handler(
    on_hold=lambda event: True,                 # ready (or False, or {"declined": "why"})
    on_commit=lambda event: print("paid", event["intentId"]),
)                                               # reads ACCORD_WEBHOOK_SECRET

# Flask
@app.post("/accord")
def accord_webhook():
    status, body = handler.handle(request.get_data(), request.headers)
    return body, status
```

With `async def` callbacks (FastAPI, aiohttp), use `status, body = await handler.handle_async(raw, headers)`.

`handle()` checks the `Accord-Signature` header (HMAC-SHA256, a 5-minute window against replays, old and new secrets during a rotation) and answers each event once. Give it the raw request body. `verify_signature(raw, header, secret)` is there on its own too.

## Examples

- `examples/trip_booker.py`: a flight, a hotel and a car, all paid or none (`--fail ridenow` to see a decline release everything).
- `examples/seller_webhook.py`: a seller answering webhooks with no framework.
- `examples/x402_gateway.py`: an x402 gateway paid through Accord.

## Tests

```bash
pip install -e '.[dev]'
pytest                                                    # unit tests
ACCORD_LIVE=1 ACCORD_URL=https://api.useaccord.ai pytest  # plus a live test-mode purchase
```

Signatures are checked byte-for-byte against the TypeScript SDK's.

## License

Apache-2.0
