@redditech/provider-kit 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Dockerfile ADDED
@@ -0,0 +1,33 @@
1
+ # Build from the repository root:
2
+ # docker build -f packages/provider-kit/Dockerfile -t rap-provider .
3
+ # Run with your config and key mounted read-only:
4
+ # docker run -p 8787:8787 -v $PWD/provider.json:/app/provider.json:ro \
5
+ # -v $HOME/.config/solana/provider.json:/keys/provider.json:ro \
6
+ # -v rap-provider-data:/app/.rap-provider \
7
+ # -e RAP_PROVIDER_KEYPAIR_PATH=/keys/provider.json -e UPSTREAM_API_KEY rap-provider
8
+ FROM node:24-alpine AS build
9
+ WORKDIR /workspace
10
+ COPY packages/x402-solana/package*.json packages/x402-solana/
11
+ RUN cd packages/x402-solana && npm ci --ignore-scripts
12
+ COPY packages/x402-solana/ packages/x402-solana/
13
+ RUN cd packages/x402-solana && npm run build
14
+ # agent-protocol has no dependencies and ships its built dist/ in the repository.
15
+ COPY packages/agent-protocol/package.json packages/agent-protocol/
16
+ COPY packages/agent-protocol/dist/ packages/agent-protocol/dist/
17
+ COPY packages/provider-kit/package*.json packages/provider-kit/
18
+ RUN cd packages/provider-kit && npm ci --ignore-scripts
19
+ COPY packages/provider-kit/ packages/provider-kit/
20
+ RUN cd packages/provider-kit && npm run build
21
+
22
+ FROM node:24-alpine
23
+ ENV NODE_ENV=production
24
+ COPY --from=build /workspace/packages/x402-solana /workspace/packages/x402-solana
25
+ COPY --from=build /workspace/packages/agent-protocol /workspace/packages/agent-protocol
26
+ COPY --from=build /workspace/packages/provider-kit /workspace/packages/provider-kit
27
+ # The provider reads its config from /app and keeps its payment memory in /app/.rap-provider.
28
+ WORKDIR /app
29
+ RUN mkdir -p /app/.rap-provider && chown -R node:node /app
30
+ USER node
31
+ EXPOSE 8787
32
+ ENTRYPOINT ["node", "/workspace/packages/provider-kit/dist/src/cli.js"]
33
+ CMD ["start"]
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Redditech Pty Ltd
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,214 @@
1
- # Temporary Holding Version
1
+ # @redditech/provider-kit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run your own paid provider on Reddi Agent Protocol: one config file, one command, any OpenAI-compatible model.
4
+
5
+ You bring a model (OpenRouter, a hosted API, or a local Ollama or vLLM server) and a Solana wallet. The kit puts a paid endpoint in front of it. Buyers pay per token through a metered escrow, and every paid answer carries a receipt signed by your wallet.
6
+
7
+ ```bash
8
+ npm install -g @redditech/provider-kit
9
+ rap-provider --help
10
+ ```
11
+
12
+ Mainnet is coming soon. Until the V1 escrow program is live there, run your provider on `solana-devnet`: the walk-through below takes you from a new wallet to a paid, receipted call.
13
+
14
+ ## How a paid call works
15
+
16
+ 1. A buyer sends an ordinary chat completion request. With no payment, the provider answers **402** with its price per million input and output tokens, an estimate for this request, and the maximum to lock (twice the estimate by default).
17
+ 2. The buyer locks that maximum in a metered escrow payable to your wallet, and repeats the request naming the lock.
18
+ 3. The provider checks the lock on chain: right program, right wallet, right mint, enough to cover the estimate, at least 10 minutes of refund window left, and not used before.
19
+ 4. The model answers. The provider counts the tokens it reports and settles the **actual cost**. The escrow program pays you, sends the protocol fee to the treasury, and returns the unused part of the maximum to the buyer, all in one transaction.
20
+ 5. The buyer gets the answer with a `reddi.receipt.v2` receipt naming the settle transaction, the tokens used and the amount charged.
21
+
22
+ The buyer is charged only after the model has answered, and the answer is sent only after the settle has confirmed. If the model fails, the provider declines the lock and the buyer gets everything back.
23
+
24
+ ### The money, in one place
25
+
26
+ | | |
27
+ |---|---|
28
+ | Your price | Per million input tokens and per million output tokens, in USDC, AUDD, PYUSD or USDG. You choose it. |
29
+ | The buyer's maximum | What the buyer locks. Twice the estimate by default; never below the estimate. The charge can never exceed it. |
30
+ | The charge | Tokens used times your price, rounded up to the smallest unit. |
31
+ | Protocol fee | Planned at 5% of the charge, with a 2.5% launch rate for payouts up to the end of 31 March 2027 (UTC), rounded down, taken out of your share. The buyer pays nothing on top. |
32
+ | A lock is not payment | You are paid when your settle confirms. Until then the buyer's refund window is running, which is why the provider wants 10 minutes left before it starts work. See `docs/ESCROW-PAYOUT-SAFETY.md`. |
33
+ | What you pay | The transaction fee for each settle. Nothing is created for anyone by default: a lock is refused up front if the buyer's token account, the treasury's or yours could not receive. You may opt in to paying a buyer's token account rent (about 0.002 SOL, not returned) with `refundAccountSubsidy`. |
34
+
35
+ ## Quickstart on devnet
36
+
37
+ You need Node 20 or newer and the Solana CLI (https://solana.com/docs/intro/installation). Devnet SOL and USDC come from web faucets: the command-line airdrop is closed on devnet.
38
+
39
+ ```bash
40
+ npm install -g @redditech/provider-kit
41
+
42
+ # 1. A wallet for the provider. Fund its address with 0.5 devnet SOL at
43
+ # https://faucet.solana.com, then create its USDC token account.
44
+ solana-keygen new --outfile ~/.config/solana/provider.json
45
+ solana address -k ~/.config/solana/provider.json
46
+ solana balance -k ~/.config/solana/provider.json --url devnet # after the faucet
47
+ spl-token create-account 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU \
48
+ --owner "$(solana address -k ~/.config/solana/provider.json)" --url devnet
49
+
50
+ # 2. A config. It starts with mock answers so you can try the payment flow first.
51
+ rap-provider init --wallet "$(solana address -k ~/.config/solana/provider.json)"
52
+ # init points keypairPath at the Solana CLI default, ~/.config/solana/id.json.
53
+ # Set "keypairPath": "~/.config/solana/provider.json" in provider.json instead.
54
+
55
+ # 3. Check the setup. This reads only; it sends and spends nothing. It opens the
56
+ # key file named in keypairPath to check it matches your wallet, and says which
57
+ # file it read; nothing from it is printed or sent.
58
+ rap-provider doctor
59
+
60
+ # 4. Serve.
61
+ rap-provider start
62
+ ```
63
+
64
+ In another terminal, make a paid call as a buyer with the example scripts in this repository (clone it, then run `npm ci && npm run build` in `packages/x402-solana` and `packages/provider-kit`). Use a second, devnet-only wallet: give it 0.5 devnet SOL at https://faucet.solana.com for fees, and devnet USDC at https://faucet.circle.com (choose Solana Devnet), which also creates its USDC token account.
65
+
66
+ ```bash
67
+ solana-keygen new --outfile ~/.config/solana/buyer.json
68
+ solana address -k ~/.config/solana/buyer.json # fund this address at both faucets
69
+ BUYER_KEYPAIR_PATH=~/.config/solana/buyer.json \
70
+ node packages/provider-kit/examples/paid-call.mjs http://localhost:8787 "Write a haiku about escrow"
71
+ ```
72
+
73
+ It prints the price, the quote, the lock transaction, the answer, what was charged and refunded, the settle transaction, and whether the receipt verified.
74
+
75
+ To try a session (one lock, several calls, one settle), run `node packages/provider-kit/examples/session-call.mjs http://localhost:8787 3` with the same `BUYER_KEYPAIR_PATH`. It checks the whole receipt chain at the end.
76
+
77
+ ### Switch to a real model
78
+
79
+ In `provider.json`:
80
+
81
+ ```json
82
+ "upstream": { "baseUrl": "https://openrouter.ai/api/v1", "apiKeyEnv": "UPSTREAM_API_KEY", "mock": false },
83
+ "model": "openai/gpt-4o-mini"
84
+ ```
85
+
86
+ then `UPSTREAM_API_KEY=... rap-provider start`. For a local model, point `baseUrl` at it, for example `http://localhost:11434/v1` for Ollama, and set `model` to its name. No API key is needed.
87
+
88
+ To sell more than a raw model, add instructions with `"systemPrompt"` or, for long or private ones, `"systemPromptFile": "prompt.txt"` (a path next to the config). The prompt stays on your server. Its tokens are part of every call, so they are counted in the quote the buyer sees.
89
+
90
+ RAP's own first-party providers, the video script writer and the humaniser, are set up this way: see [examples/first-party](examples/first-party/README.md) for their configs, prices and an outline of their private instructions.
91
+
92
+ ## List your provider
93
+
94
+ Buyers and the app find a provider through two records: the on-chain registry, and the app's listing with your price. One command writes both.
95
+
96
+ ```bash
97
+ rap-provider register --dry-run # prints the registry accounts and the listing; signs and sends nothing
98
+ rap-provider register # registers, signs in with your wallet, lists
99
+ rap-provider status # reads both back
100
+ rap-provider adl # prints your ADL document
101
+ ```
102
+
103
+ What `register` does, in order, and what it costs:
104
+
105
+ 1. Checks the key file is your configured wallet's, the RPC endpoint is your network, and the app serves the same network. If any is wrong it stops before sending anything.
106
+ 2. If your wallet has no registry record, sends `register_agent`. The program burns a 0.01 SOL registration fee and your wallet pays the record's rent. Run again, it does not register twice.
107
+ 3. Signs one sign-in message with your wallet (it moves no funds), sent to the sign-in service the app names, and then creates or updates your listing: name, public address, model, currency and per-token price, with your ADL document. A paused currency is listed as paused.
108
+
109
+ ### Your ADL document
110
+
111
+ Every provider describes itself in [Agent Definition Language](https://agent-protocol.reddi.tech/adl) v0.3, made from `provider.json`: the model it declares, a live charge on the Solana rail settled through metered escrow, its per-token price, the most one call can cost, the wallet that is paid, the protocol fee (5%, at the 2.5% launch rate for payouts before 1 April 2027 UTC, capped at 0.1 SOL on SOL), and a `reddi.receipt.v2` receipt for every paid answer. It passes ADL Level 3.
112
+
113
+ The provider serves it at `/.well-known/adl.yaml`, `/.well-known/reddi-agent.json` links to it, and `register` sends it with the listing. The app checks it and refuses a listing whose ADL fails Level 3 or says something different from the listing. Because both come from the same config, they cannot drift. `rap-provider adl` prints it, `--json` prints the Level 3 report, and `rap-provider doctor` checks it.
114
+
115
+ The most one call can cost is the price of every input token a request can hold (a 1 MB body, about 250,000 tokens, plus your system prompt) and the full `maxOutputTokens`. Buyers lock less for an ordinary call; this is the ceiling they never need to go above.
116
+
117
+ `publicUrl` must be a public https address before you list. Set `listing.capabilities` to say what the provider is for, for example `{ "taskTypes": ["writing"] }`, and `listing.appUrl` (or `RAP_APP_URL`) for another deployment of the app.
118
+
119
+ The wallet sign-in works against the devnet app: a message signed by the kit is accepted and the app confirms the session for that wallet.
120
+
121
+ ## Configuration
122
+
123
+ | Field | Meaning |
124
+ |---|---|
125
+ | `name`, `description` | Shown to buyers. |
126
+ | `network` | `solana-devnet` or `solana-mainnet-beta`. |
127
+ | `wallet` | Your provider wallet's address. Payouts go to its token account for the currency. |
128
+ | `publicUrl` | Where buyers reach you. Must be `https` unless it is localhost. |
129
+ | `model` | The model you declare. Receipts name it. It is a declaration, not proof of which model ran. |
130
+ | `upstream.baseUrl` | An OpenAI-compatible base URL. |
131
+ | `upstream.model` | The name to send upstream, when it differs from `model`. |
132
+ | `upstream.apiKeyEnv` | Name of the environment variable holding the API key. Default `UPSTREAM_API_KEY`. The key itself never goes in the file. |
133
+ | `upstream.mock` | `true` answers with canned text. Refused on mainnet. |
134
+ | `price.currency` | `USDC`, `AUDD`, `PYUSD` or `USDG`. |
135
+ | `price.inputPerMillion`, `price.outputPerMillion` | Decimal prices per million tokens. |
136
+ | `price.maxOutputTokens` | The most output tokens one call may use. Default 1000. |
137
+ | `systemPrompt`, `systemPromptFile` | Instructions placed before every request. |
138
+ | `keypairPath` | The wallet's keypair file. Must not be readable by other users (`chmod 600`). |
139
+ | `replayFile` | Where accepted escrows are remembered. Default `.rap-provider/accepted-escrows.log`. Keep it on a disk that survives restarts. |
140
+ | `rpcUrl`, `port` | Also settable as `SOLANA_RPC_URL` and `PORT`. An RPC endpoint is required on mainnet. It must answer `getSignatureStatuses` with `searchTransactionHistory`, which is how the kit tells whether a recorded settle landed after a restart; an endpoint without transaction history leaves those settles pending. Helius does. |
141
+ | `listing.appUrl`, `listing.capabilities` | For `register`: the app to list in, and what the listing says the provider can do. |
142
+ | `mint` | Devnet only, for currencies other than USDC. On mainnet the mints are fixed. |
143
+ | `pausedCurrencies` | Currencies you have stopped taking new locks in, for example `["PYUSD"]`. Also `RAP_PROVIDER_PAUSED_CURRENCIES=PYUSD,USDG`. See "Pausing a currency". |
144
+ | `payoutAccount` | Recovery only: another token account of the currency that your wallet owns. Payouts go there when your usual token account is closed or frozen. |
145
+ | `refundAccountSubsidy.maxPerDay` | Off unless set. How many buyer token accounts you will pay to create in a UTC day, when a buyer closed its own after you accepted its lock. |
146
+ | `lockBoundDelegations` | Off unless `true`. Also accepts a payer's consent given as a memo it signed in the lock transaction, which is how a phone wallet pays through a Solana Pay QR code (it signs a transaction but no separate message). Each new delegation costs one transaction read from your RPC before the lock is checked, and anyone can make the kit try one, so this spends RPC credits; the kit keeps what it read for the same transaction (up to 1,000) and remembers one not found for 5 seconds. The memo counts only for the lock its transaction made: a lock made again at the same address needs a new delegation. If the read fails the call is refused with `payment_check_unavailable` and nothing is charged. |
147
+ | `sessions.enabled` | `false` by default: session calls are refused with `sessions_not_offered` and single calls are unchanged. Set `true` to offer sessions, and watch for log lines with `"alert": true` (`session_settle_waiting`, `session_refunded_unpaid`). |
148
+ | `sessions.idleSeconds` | How long a session may sit without a call before the kit settles it. 30 to 3600, default 600. |
149
+ | `sessions.file` | Where open sessions are remembered. Default `.rap-provider/sessions.jsonl`. Keep it on a disk that survives restarts. |
150
+
151
+ ## Pausing a currency
152
+
153
+ An issuer can change how its token moves: PYUSD and USDG are Token-2022 mints whose issuer can add a transfer hook, change a fee, or freeze accounts. When that happens, stop taking new locks in that currency until you have read the change:
154
+
155
+ ```bash
156
+ RAP_PROVIDER_PAUSED_CURRENCIES=PYUSD rap-provider start
157
+ # or, in provider.json: "pausedCurrencies": ["PYUSD"]
158
+ ```
159
+
160
+ While your price currency is paused, paid calls are refused with `currency_paused` before any lock is read, no price is offered, and `/.well-known/reddi-agent.json` and `/healthz` report `"acceptingPayments": false`, which is what a listing should show. `rap-provider doctor` shows the pause. Remove the currency from the list and restart to resume. `docs/ESCROW-PAYOUT-SAFETY.md` says when to pause.
161
+
162
+ ## Sessions: several calls, one settle
163
+
164
+ An agent that makes many small calls to you can lock one escrow and use it for all of them, so it pays one lock and you send one settle. The buyer sends the same `x402-payment` header on every call, plus `x402-session-sequence: 1`, `2`, `3` and so on.
165
+
166
+ A lock's escrow, payer and nonce are public once it confirms, so they do not show who is calling. The buyer therefore makes a fresh session key and has its payer wallet sign, once, a delegation naming the network (by its genesis hash), the escrow, your wallet, that key and an expiry of at most seven days (`x402-session-delegation`). Every call, close and read also carries that key's signature over the network, the action, the escrow, the call number and the SHA-256 of the body (`x402-session-signature`). A call that sends `x402-session: close` is signed as `call-close` (`sessionCallAction(true)`), so a close cannot be added or removed in transit, and a signature made for one network is refused on every other. `sessionDelegationHeaderValue` and `sessionSignatureHeaderValue` in `@redditech/x402-solana` build both. A request without them, or signed by anyone else, is refused with `401` before the lock is read, and a session keeps the key it started with.
167
+
168
+ The kit then:
169
+
170
+ - checks before each call that the cost so far plus this call's worst case still fits under the lock, and refuses with `session_max_reached` when it does not;
171
+ - answers every call with a signed receipt whose `session` block carries the sequence, this call's tokens, the running totals and cost, and the hash of the previous receipt, so the buyer can check the chain (`verifyReddiReceiptV2Session` in `@redditech/agent-protocol`);
172
+ - writes the session to `sessions.file` before it answers, so a restart goes on from the last answered call;
173
+ - settles once, for the total, when the buyer sends `x402-session: close` on a call or `POST /v1/session/close`, when the lock is used up, after `sessions.idleSeconds` without a call, or before the lock's refund window opens. The closing receipt is the one with `closed: true` and a `payment` block for the amount settled.
174
+
175
+ A call number that is out of order or used before is refused with `session_sequence_invalid`, and a request signed by another key than the session started with with `session_key_mismatch`; a call the model could not answer is not counted and can be sent again with the same number. A lock used for a session cannot also pay for a single call, or the other way round. If no call was answered, closing the session declines the lock and the buyer gets it all back. `GET /v1/session/<escrow>` shows a session's totals and, once closed, its closing receipt.
176
+
177
+ The settle is signed and written to `sessions.file` before it is sent, and only that signature can count as the session's settle. If the kit cannot tell whether it landed (an RPC outage, a restart), the session stays pending and the same signed transaction is looked up and sent again on the next sweep; it is never marked settled on a guess. If the buyer has closed the account that funded the lock, the settle returns the unused part to the buyer's associated token account. When that account does not exist either, the settle creates it at your cost (about 0.002 SOL) only within `refundAccountSubsidy.maxPerDay`; once the day's bound is spent the session waits, logged as `refund_account_subsidy_spent` and `session_settle_waiting` with `"alert": true`, so you can raise the bound or settle it by hand. If the escrow is gone and no settle of yours landed (the buyer refunded once the refund window opened), the session is recorded as `refunded_unpaid` and logged as `session_refunded_unpaid` with `"alert": true`, because the calls served were not paid. A lock made again at the same address with the same nonce is a different lock and is never charged for an earlier session's calls. The kit settles ahead of the refund window to avoid all this.
178
+
179
+ The worst case of a call counts four characters of input as one token. A model that bills more input than that can take a session's total past the lock; the charge is capped at the lock, so you absorb the difference and the buyer never pays more than it locked.
180
+
181
+ ## What the kit does to protect you and your buyers
182
+
183
+ - **It refuses to start half-working**: no key, a key for another wallet, a key file others can read, a payment memory file another process holds, or mock answers on mainnet.
184
+ - **Only the payer's own call is served.** The lock is public on chain, so a paid call must also carry the payer's signature over that exact request (`x402-session-delegation` and `x402-session-signature`, action `single`; `paidCallAuthHeaders` in `@redditech/x402-solana` builds them). A call without it, or signed by anyone else, is refused with `401` before the lock is read, and the lock stays usable by its payer. Hardware wallets such as Ledger sign Solana off-chain messages with a header prefix, which this check does not accept yet; since the payer wallet must sign the delegation, a buyer paying from one is refused, so pay from a software wallet for now. Buyer clients should delegate for a day (`delegationExpiresAt()`), not the seven-day maximum, and keep the session key in memory only.
185
+ - **One lock pays for one call**, including after a restart. Accepted escrows are written to disk before the model is called.
186
+ - **It checks the cluster** before trusting any account, so a lock on another network is never taken as payment.
187
+ - **It checks that the payout can land before doing any work.** With the lock it reads your token account, the treasury's and the account the buyer funded the lock from: each must exist, be initialised, not frozen, belong to the right owner and not require a memo. If one fails, the call is refused, the lock is not used up, and the buyer can present it again once the account is fixed.
188
+ - **It creates nothing at your cost for a single call by default.** If a buyer closes its account after you accepted the lock, the settle is tried once more with the buyer's associated token account; if that is gone too, the settle is held and the answer withheld, unless you opted in to `refundAccountSubsidy`. A session's settle uses the same daily bound; see above.
189
+ - **A settle counts only under its own signature.** The kit signs the settle and records it (`pending-settles.jsonl` beside the payment memory) before sending it. If sending reports a failure, the kit looks up that signature: landed means the buyer paid and gets the answer; failed or expired means nothing was charged by it, and the kit tries once more while the escrow is still locked. An escrow closed by anything else is never taken as paid: the answer is withheld (`escrow_closed`). If the chain cannot say, the answer is held for ten minutes (`503 settle_pending`): the buyer sends the same signed request again and gets it once the settle is known to have landed. A pending settle whose answer is no longer held is looked up by the sweep: if it landed the log says `paid_answer_lost` with `"alert": true` so you can make it right; if it cannot land the lock is declined so the buyer gets it all back.
190
+ - **Receipts state what the chain shows.** After the settle confirms, the kit reads the transaction back and signs a receipt for what actually moved: your credit plus the treasury's fee as the amount, and the model's token counts separately. If the transaction cannot be read back, or the amounts do not add up, the buyer still gets the answer it paid for, the response says `"confirmed": false`, and no receipt is signed.
191
+ - **Your key signs two things only**: settle (or decline) transactions for escrows payable to you, and receipts. It is read once from the key file and is never logged or sent anywhere.
192
+ - **Run one process per payment memory file.** For several instances behind a load balancer, use a shared database store (`DatabaseReplayStore` in `@redditech/x402-solana`) through the library API.
193
+
194
+ ## Good to know
195
+
196
+ - Single paid calls and multi-call sessions run end to end on devnet. Mainnet is coming soon; `rap-provider doctor` checks that your token account and the treasury's are ready for your currency before you take payment.
197
+ - A single-call settle that did not land is logged as `settle_failed` with the escrow's address. The lock stays open until its refund window, so you can settle it by hand in that time. (A session's settle is retried by the sweep.)
198
+ - Calls take text messages and answer in one piece; `stream: true` is refused.
199
+ - Prices are in token currencies (USDC, AUDD, PYUSD, USDG).
200
+ - The estimate counts four characters as one token, and the same count is used when a model reports no usage. A buyer who locks exactly the minimum caps your payment at that estimate, so text that tokenises more densely can cost you the difference.
201
+
202
+ On the roadmap: streaming responses, SOL-priced metered calls, sessions on rated escrows, automatic retry of a single-call settle, and hardware wallet payers.
203
+
204
+ ## Library use
205
+
206
+ ```ts
207
+ import { createProviderHandler, parseProviderConfig, createProviderChain, FileReplayStore } from "@redditech/provider-kit";
208
+ ```
209
+
210
+ `createProviderHandler(config, deps)` returns a `(Request) => Promise<Response>` you can mount in any server. The seller-side payment logic on its own is in `@redditech/x402-solana/provider`.
211
+
212
+ ## License
213
+
214
+ MIT
@@ -0,0 +1,25 @@
1
+ /**
2
+ * This provider's Agent Definition Language (ADL v0.3) document, made from
3
+ * its config. The listing the app shows and the document the provider serves
4
+ * at /.well-known/adl.yaml come from the same config, so they cannot say
5
+ * different things, and the app refuses a listing whose ADL does not pass
6
+ * Level 3 or does not match it.
7
+ */
8
+ import { type AdlConformanceReport, type AdlDocument } from "@redditech/agent-protocol/adl";
9
+ import { type ProviderConfig } from "./config.js";
10
+ /** Where the provider serves its ADL document. */
11
+ export declare const ADL_PATH = "/.well-known/adl.yaml";
12
+ /**
13
+ * The most one call can cost: every input token a request body can hold (the
14
+ * provider prices about four characters a token, plus its system prompt) and
15
+ * the full output limit, at the listed price. A buyer never needs to
16
+ * authorise more for a single call.
17
+ */
18
+ export declare function maxPerCall(config: ProviderConfig): string;
19
+ /** The provider's ADL v0.3 document. */
20
+ export declare function providerAdl(config: ProviderConfig): AdlDocument;
21
+ /** The document as YAML, with its Level 3 check. */
22
+ export declare function providerAdlText(config: ProviderConfig): {
23
+ text: string;
24
+ report: AdlConformanceReport;
25
+ };
@@ -0,0 +1,48 @@
1
+ /**
2
+ * This provider's Agent Definition Language (ADL v0.3) document, made from
3
+ * its config. The listing the app shows and the document the provider serves
4
+ * at /.well-known/adl.yaml come from the same config, so they cannot say
5
+ * different things, and the app refuses a listing whose ADL does not pass
6
+ * Level 3 or does not match it.
7
+ */
8
+ import { ADL_V03_LAUNCH_RATE, ADL_V03_PROTOCOL_FEE_BPS, buildProviderAdl, checkAdlConformance, formatAdlDocument } from "@redditech/agent-protocol/adl";
9
+ import { baseUnitsToDecimal, directPaymentCurrency, estimateInputTokens, LAUNCH_PROTOCOL_FEE_BPS, LAUNCH_RATE_ENDS_AT_MS, PROTOCOL_FEE_BPS, tokenCostBaseUnits } from "@redditech/x402-solana";
10
+ import { MAX_BODY_BYTES } from "./config.js";
11
+ /** Where the provider serves its ADL document. */
12
+ export const ADL_PATH = "/.well-known/adl.yaml";
13
+ // The ADL fee rules and the payment library must name the same rates.
14
+ if (ADL_V03_PROTOCOL_FEE_BPS !== PROTOCOL_FEE_BPS || ADL_V03_LAUNCH_RATE.bps !== LAUNCH_PROTOCOL_FEE_BPS || Date.parse(ADL_V03_LAUNCH_RATE.endsAt) !== LAUNCH_RATE_ENDS_AT_MS) {
15
+ throw new Error("The ADL protocol fee and @redditech/x402-solana disagree; update both packages together.");
16
+ }
17
+ /**
18
+ * The most one call can cost: every input token a request body can hold (the
19
+ * provider prices about four characters a token, plus its system prompt) and
20
+ * the full output limit, at the listed price. A buyer never needs to
21
+ * authorise more for a single call.
22
+ */
23
+ export function maxPerCall(config) {
24
+ const { terms } = config;
25
+ const inputTokens = estimateInputTokens([{ content: "x".repeat(MAX_BODY_BYTES) }]) + (config.systemPrompt ? estimateInputTokens([{ content: config.systemPrompt }]) : 0);
26
+ const units = tokenCostBaseUnits(terms.price, { inputTokens, outputTokens: terms.maxOutputTokens });
27
+ return baseUnitsToDecimal(units, directPaymentCurrency(terms.price.currency).decimals);
28
+ }
29
+ /** The provider's ADL v0.3 document. */
30
+ export function providerAdl(config) {
31
+ const { terms } = config;
32
+ return buildProviderAdl({
33
+ name: config.name,
34
+ ...(config.description ? { description: config.description } : {}),
35
+ model: config.model,
36
+ network: config.network,
37
+ currency: terms.price.currency,
38
+ mint: terms.mint.toBase58(),
39
+ payTo: config.wallet,
40
+ price: { per: "token", inputPerMillion: terms.price.inputPerMillion, outputPerMillion: terms.price.outputPerMillion, maxPerCall: maxPerCall(config) },
41
+ endpointUrl: config.publicUrl,
42
+ });
43
+ }
44
+ /** The document as YAML, with its Level 3 check. */
45
+ export function providerAdlText(config) {
46
+ const document = providerAdl(config);
47
+ return { text: formatAdlDocument(document), report: checkAdlConformance(document, { requestedLevel: 3 }) };
48
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The provider's view of the chain: read accounts, read the slot, and send a
3
+ * transaction the provider wallet signs. Everything the request handler needs
4
+ * from Solana goes through this, so tests replace it whole.
5
+ */
6
+ import { PublicKey, type Keypair, type TransactionInstruction } from "@solana/web3.js";
7
+ import { type ConfirmedTransactionFacts, type SettlementRecord } from "@redditech/x402-solana";
8
+ export interface ProviderChain {
9
+ readGenesisHash(): Promise<string>;
10
+ readAccount(address: PublicKey): Promise<{
11
+ owner: PublicKey;
12
+ data: Uint8Array;
13
+ lamports: bigint;
14
+ executable: boolean;
15
+ } | null>;
16
+ readSlot(): Promise<bigint>;
17
+ /** Signs with the provider wallet, sends, and resolves with the signature once confirmed. Rejects when it did not land. */
18
+ sendInstructions(instructions: TransactionInstruction[]): Promise<string>;
19
+ /**
20
+ * Signs with the provider wallet without sending, so the signature can be
21
+ * recorded first. `transaction` is the signed transaction in base64.
22
+ */
23
+ signInstructions(instructions: TransactionInstruction[]): Promise<SignedTransaction>;
24
+ /** Sends a transaction signed by `signInstructions` (again, if it was sent before) and resolves with its signature once confirmed. Rejects when it is not known to have landed. */
25
+ sendSigned(signed: SignedTransaction): Promise<string>;
26
+ /**
27
+ * Where one signature stands. `landed`: confirmed without error. `failed`:
28
+ * confirmed with an error, so it moved nothing. `expired`: not found and its
29
+ * blockhash can no longer land, so it never will. `unknown`: anything else,
30
+ * including an RPC that cannot be reached.
31
+ */
32
+ signatureState(signature: string, lastValidBlockHeight: number): Promise<"landed" | "failed" | "expired" | "unknown">;
33
+ /** What a confirmed transaction did: the programs it called, its top-level instructions, the accounts it named and each token balance before and after. Null when it cannot be found. */
34
+ readSettlement(signature: string): Promise<SettlementRecord | null>;
35
+ /** Who signed a confirmed transaction, the accounts it named and its Memo instructions. Null when it cannot be found. Needed only with `lockBoundDelegations`. */
36
+ readTransactionFacts?(signature: string): Promise<ConfirmedTransactionFacts | null>;
37
+ }
38
+ export interface SignedTransaction {
39
+ signature: string;
40
+ transaction: string;
41
+ lastValidBlockHeight: number;
42
+ }
43
+ /** Base58 text of a transaction signature, as the cluster names it. */
44
+ export declare function base58(bytes: Uint8Array): string;
45
+ export declare function createProviderChain(rpcUrl: string, keypair?: Keypair): ProviderChain;
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The provider's view of the chain: read accounts, read the slot, and send a
3
+ * transaction the provider wallet signs. Everything the request handler needs
4
+ * from Solana goes through this, so tests replace it whole.
5
+ */
6
+ import { Connection, Transaction } from "@solana/web3.js";
7
+ import { transactionFactsReader } from "@redditech/x402-solana";
8
+ const pause = (ms) => new Promise((done) => setTimeout(done, ms));
9
+ const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
10
+ /** Base58 text of a transaction signature, as the cluster names it. */
11
+ export function base58(bytes) {
12
+ let value = 0n;
13
+ for (const byte of bytes)
14
+ value = value * 256n + BigInt(byte);
15
+ let text = "";
16
+ while (value > 0n) {
17
+ text = ALPHABET[Number(value % 58n)] + text;
18
+ value /= 58n;
19
+ }
20
+ for (const byte of bytes) {
21
+ if (byte !== 0)
22
+ break;
23
+ text = `1${text}`;
24
+ }
25
+ return text;
26
+ }
27
+ export function createProviderChain(rpcUrl, keypair) {
28
+ const connection = new Connection(rpcUrl, "confirmed");
29
+ const readFacts = transactionFactsReader(connection);
30
+ return {
31
+ readTransactionFacts: (signature) => readFacts(signature),
32
+ readGenesisHash: () => connection.getGenesisHash(),
33
+ async readAccount(address) {
34
+ const info = await connection.getAccountInfo(address, "confirmed");
35
+ return info ? { owner: info.owner, data: new Uint8Array(info.data), lamports: BigInt(info.lamports), executable: info.executable } : null;
36
+ },
37
+ async readSlot() {
38
+ return BigInt(await connection.getSlot("confirmed"));
39
+ },
40
+ async readSettlement(signature) {
41
+ // A transaction that has just confirmed can take a moment to be served.
42
+ for (let attempt = 0; attempt < 4; attempt += 1) {
43
+ if (attempt > 0)
44
+ await pause(500 * attempt);
45
+ const found = await connection.getTransaction(signature, { commitment: "confirmed", maxSupportedTransactionVersion: 0 });
46
+ if (!found || !found.meta)
47
+ continue;
48
+ const { meta } = found;
49
+ const message = found.transaction.message;
50
+ const keys = message.getAccountKeys(meta.loadedAddresses ? { accountKeysFromLookups: meta.loadedAddresses } : undefined);
51
+ const key = (index) => keys.get(index)?.toBase58() ?? "";
52
+ const accounts = Array.from({ length: keys.length }, (_, index) => key(index));
53
+ const balances = new Map();
54
+ const row = (index, mint) => {
55
+ const id = `${index}:${mint}`;
56
+ if (!balances.has(id))
57
+ balances.set(id, { account: key(index), mint, before: 0n, after: 0n });
58
+ return balances.get(id);
59
+ };
60
+ for (const b of meta.preTokenBalances ?? [])
61
+ row(b.accountIndex, b.mint).before = BigInt(b.uiTokenAmount.amount);
62
+ for (const b of meta.postTokenBalances ?? [])
63
+ row(b.accountIndex, b.mint).after = BigInt(b.uiTokenAmount.amount);
64
+ return {
65
+ failed: meta.err !== null,
66
+ programIds: message.compiledInstructions.map((instruction) => key(instruction.programIdIndex)),
67
+ accounts,
68
+ tokenBalances: [...balances.values()],
69
+ instructions: message.compiledInstructions.map((instruction) => ({
70
+ programId: key(instruction.programIdIndex),
71
+ accounts: instruction.accountKeyIndexes.map((index) => key(index)),
72
+ data: Buffer.from(instruction.data).toString("base64"),
73
+ })),
74
+ };
75
+ }
76
+ return null;
77
+ },
78
+ async signInstructions(instructions) {
79
+ if (!keypair)
80
+ throw new Error("no provider key is loaded");
81
+ const latest = await connection.getLatestBlockhash("confirmed");
82
+ const transaction = new Transaction({ feePayer: keypair.publicKey, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }).add(...instructions);
83
+ transaction.sign(keypair);
84
+ return { signature: base58(transaction.signature), transaction: transaction.serialize().toString("base64"), lastValidBlockHeight: latest.lastValidBlockHeight };
85
+ },
86
+ async sendSigned(signed) {
87
+ const raw = Buffer.from(signed.transaction, "base64");
88
+ const signature = await connection.sendRawTransaction(raw, { preflightCommitment: "confirmed", skipPreflight: false });
89
+ if (signature !== signed.signature)
90
+ throw new Error("the cluster reported another signature");
91
+ const blockhash = Transaction.from(raw).recentBlockhash;
92
+ try {
93
+ const confirmation = await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight: signed.lastValidBlockHeight }, "confirmed");
94
+ if (confirmation.value.err)
95
+ throw new Error("the transaction failed on chain");
96
+ return signature;
97
+ }
98
+ catch (error) {
99
+ const status = await connection.getSignatureStatus(signature, { searchTransactionHistory: true }).catch(() => undefined);
100
+ const value = status?.value;
101
+ if (value && !value.err && (value.confirmationStatus === "confirmed" || value.confirmationStatus === "finalized"))
102
+ return signature;
103
+ throw error;
104
+ }
105
+ },
106
+ async signatureState(signature, lastValidBlockHeight) {
107
+ try {
108
+ const status = (await connection.getSignatureStatus(signature, { searchTransactionHistory: true })).value;
109
+ if (status && (status.confirmationStatus === "confirmed" || status.confirmationStatus === "finalized"))
110
+ return status.err ? "failed" : "landed";
111
+ if (status)
112
+ return "unknown";
113
+ // Not found. Once the chain is past the blockhash's last valid height it can never land.
114
+ const height = await connection.getBlockHeight("confirmed");
115
+ if (height <= lastValidBlockHeight)
116
+ return "unknown";
117
+ // Look once more, in case it landed between the two reads.
118
+ const again = (await connection.getSignatureStatus(signature, { searchTransactionHistory: true })).value;
119
+ if (again)
120
+ return again.err ? "failed" : again.confirmationStatus === "processed" ? "unknown" : "landed";
121
+ return "expired";
122
+ }
123
+ catch {
124
+ return "unknown";
125
+ }
126
+ },
127
+ async sendInstructions(instructions) {
128
+ if (!keypair)
129
+ throw new Error("no provider key is loaded");
130
+ const latest = await connection.getLatestBlockhash("confirmed");
131
+ const transaction = new Transaction({ feePayer: keypair.publicKey, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }).add(...instructions);
132
+ transaction.sign(keypair);
133
+ const signature = await connection.sendRawTransaction(transaction.serialize(), { preflightCommitment: "confirmed" });
134
+ try {
135
+ const confirmation = await connection.confirmTransaction({ signature, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, "confirmed");
136
+ if (confirmation.value.err)
137
+ throw new Error("the transaction failed on chain");
138
+ return signature;
139
+ }
140
+ catch (error) {
141
+ // The confirmation can fail while the transaction lands. Look once more before calling it lost.
142
+ const status = await connection.getSignatureStatus(signature, { searchTransactionHistory: true }).catch(() => undefined);
143
+ const value = status?.value;
144
+ if (value && !value.err && (value.confirmationStatus === "confirmed" || value.confirmationStatus === "finalized"))
145
+ return signature;
146
+ throw error;
147
+ }
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ import { type ProviderChain } from "./chain.js";
3
+ import { type ListingFetch } from "./listing.js";
4
+ import { type ProviderConfig } from "./config.js";
5
+ export interface CliIo {
6
+ out: (text: string) => void;
7
+ err: (text: string) => void;
8
+ env: Record<string, string | undefined>;
9
+ /** Replaced in tests. */
10
+ chain?: (config: ProviderConfig, keypair?: import("@solana/web3.js").Keypair) => ProviderChain;
11
+ fetchImpl?: ListingFetch;
12
+ }
13
+ /** Runs one command. Resolves with the exit code; `start` resolves only when it fails to start. */
14
+ export declare function runCli(args: string[], io: CliIo): Promise<number>;