# Runtime spending budgets and merchant sessions

These controls limit two different authorities. A local checkout budget limits admission of new prepared-offer payment authorizations. A merchant session limits which service APIs a delegated worker may call. Neither creates funds, runs a worker or grants wallet signing authority.

Check `merchantSessions` in [capabilities](/v1/capabilities) for server support. The checkout budget requires **unpublished checkout source 0.3.0**; npm checkout 0.2.1 does not include it. Merchant session helpers are published in SDK 0.7.0. HTTP and hosted MCP also support the session API.

## Buyer runtime: one shared budget

Choose a lifetime allowance, per-purchase cap, expiry and allowed sellers from the buyer's existing spending authority. This example is a policy template, not permission to spend. Replace both addresses and the expiry before creating it. `allowedOfferIds: null` allows any prepared offer from the listed sellers; use an explicit UUID list to narrow it.

```json
{
  "protocol": "402mob.spending-budget.v1",
  "origin": "https://evidence.contact",
  "buyerWallet": "0x1111111111111111111111111111111111111111",
  "network": "eip155:8453",
  "asset": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
  "maxTotalUSDC": "0.10",
  "maxPerPurchaseUSDC": "0.02",
  "allowedPayees": ["0x2222222222222222222222222222222222222222"],
  "allowedOfferIds": null,
  "expiresAt": "2026-12-01T00:00:00.000Z"
}
```

Amounts are positive decimal USDC strings with up to six fractional digits and at most 999999.999999; the per-purchase cap cannot exceed the total. Use lowercase addresses, native Base USDC, an exact HTTPS service origin (loopback HTTP is allowed for local tests), 1–100 distinct sellers, and either null or 1–100 distinct offer IDs. Expiry is UTC with milliseconds. Unknown fields are rejected. [Policy JSON schema](/spending-budget.schema.json).

From the checkout source directory:

```sh
node bin/402mob-checkout.js budget-create --dir /absolute/private/shared-budget --file policy.json
node bin/402mob-checkout.js budget-bind --dir /absolute/private/buyer-checkouts --budget-dir /absolute/private/shared-budget
node bin/402mob-checkout.js budget-status --dir /absolute/private/shared-budget
```

Bind every participating checkout directory to the **same budget directory** before any payment starts. JavaScript callers use `SpendingBudget.create({directory, policy})`, then `AgentCheckout.open({directory: checkoutDirectory, budgetDirectory})`. Binding is retained; later opens need only the original checkout directory. A runtime already open rereads the binding before execution. A different policy cannot replace that binding. Existing started purchases cannot be retrospectively covered; recover them through their original directories.

Prepare, review the exact `termsHash`, execute and resume as described in [Payment Links](/payment-links.md). Budget configuration is an additional limit, not payment consent. The CLI also exposes ordinary lock inspection and recovery; a crashed budget lock must be inspected in the budget directory. Do not remove a live or unverified lock.

```text
exact offer + buyer's accepted terms
                  |
                  v
  shared policy: wallet / origin / Base USDC
                 seller / offer / expiry
                  |
                  v
  spent + reserved + new amount <= total
                  |
          persist reservation
                  |
         return challenge to signer
                  |
          +-------+------------------+
          |                          |
       settled                    uncertain
          |                          |
    count as spent            keep reservation
                              resume same payment
```

Reservations commit under a shared filesystem lock before the wallet receives its unsigned payment challenge. Competing processes cannot both consume the same remaining allowance. A busy ledger fails without signing; retry the same checkout later. A confirmed payment remains counted even if its result fails content validation. Settlement uses the existing wallet's validated service receipt; it is not a new independent chain audit.

Only a failure where the unsigned challenge never reached the signer can release a reservation automatically. Timeouts, missing journals, rejected signed submissions, expired authorizations and expired policies do **not** prove that no payment occurred and do not release capacity. After policy expiry, original payments may still recover and settle; new authorizations stop. Signed payments already admitted may be submitted after expiry. There is no periodic reset, top-up, general reservation-release command or automatic replacement policy. The retained ledger is bounded to 1,000 reservation records. `availableAtomic` is unused policy capacity, not wallet balance or permission to spend after expiry.

Keep the budget ledger, its binding, checkout directory and wallet journal together in backups. Missing or corrupt budget files fail closed. The integrity digest detects corruption, not deliberate rewriting by the filesystem owner. Restore the ledger and participating journals from a consistent point: an older valid ledger can omit later reservations, so do not authorize new payments from a stale restore before reconciling those records. An interrupted initialization leaves a binding that must be restored or investigated; creation does not reset it. Local code, a filesystem owner, another policy directory, direct wallet calls, Work Tickets, escrow funding and other payment clients are outside this enforcement boundary. This is not a sandbox against the wallet owner, a multi-host consensus ledger or a chain-level allowance. It does not constrain ETH gas or spending through other wallets.

## Seller runtime: short-lived API sessions

Use the parent merchant credential with `merchant:manage` to create a session:

```http
POST /v1/agent/merchant/sessions
Authorization: Bearer PARENT_MERCHANT_KEY
Content-Type: application/json

{"name":"delivery-worker","scopes":["merchant:work"],"expiresInSeconds":3600}
```

The response is `{session, token}`. Store `token` privately before delegating it; it is returned only once. Use it as the ordinary `Authorization: Bearer ...` header. The service stores only its keyed hash. Session names are 1–64 UTF-16 code units after trimming. Expiry is 60–86,400 seconds. A merchant may have at most 100 active sessions and 1,000 retained records. When needed, creation prunes the oldest expired or revoked session metadata; work and payment records are unaffected. An expired token is never renewed in place.

| Scope | Access |
| --- | --- |
| `merchant:work` | Merchant work inbox, claims, quotes, delivery and related work reads |
| `merchant:sales:read` | Seller's sales and settled-sale evidence |
| `merchant:manage` | Offer/profile/discovery management and applicable proposal APIs |

Scopes cover the merchant's resources, not one specific ticket. Choose only those required by the worker. A session cannot manage other sessions, obtain an operator's assigned-operation scope, recover a parent key, or sign a wallet payment. Effective scopes are intersected with the active parent's permissions on every authenticated call.

The parent credential can list metadata with `GET /v1/agent/merchant/sessions` and revoke one session with `DELETE /v1/agent/merchant/sessions/{id}`. Repeating revocation of a retained session is safe; a pruned session returns 404. Listing never returns tokens. Expiry/revocation blocks subsequent authenticated calls, not work already completed by an admitted request. Revoking a session does not revoke the merchant, unpublish its offers, delete a work ticket or release a buyer's payment reservation. Another authorized credential can continue the retained work. Rotating or revoking the **parent** credential invalidates all its sessions.

Hosted MCP provides `create_merchant_session`, `list_merchant_sessions` and `revoke_merchant_session`, using the parent credential in the transport header. A worker can use its session with the existing MCP tools permitted by its scopes. SDK 0.7.0 exposes `createMerchantSession`, `listMerchantSessions` and `revokeMerchantSession`. Sessions are optional; existing merchant keys remain supported.

## Validation scope

Local tests cover competing budget processes, exhaustion, policy mismatch, retained uncertainty, restart, expiry, recovery, missing/corrupted ledgers and session scope/expiry/revocation through HTTP and MCP. Payment settlement is simulated. This work makes no claim of live-money validation, production deployment or package publication.
