@redditech/provider-kit 0.2.0 → 0.3.0
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/README.md +65 -30
- package/dist/src/adl.d.ts +2 -2
- package/dist/src/adl.js +4 -4
- package/dist/src/capacity.d.ts +61 -0
- package/dist/src/capacity.js +67 -0
- package/dist/src/cli.js +2 -2
- package/dist/src/config.d.ts +20 -0
- package/dist/src/config.js +49 -4
- package/dist/src/doctor.d.ts +3 -1
- package/dist/src/doctor.js +25 -2
- package/dist/src/handler.d.ts +21 -1
- package/dist/src/handler.js +184 -57
- package/dist/src/index.d.ts +4 -0
- package/dist/src/index.js +4 -0
- package/dist/src/keys.d.ts +10 -0
- package/dist/src/keys.js +29 -4
- package/dist/src/pending.d.ts +9 -3
- package/dist/src/postgres.d.ts +78 -0
- package/dist/src/postgres.js +186 -0
- package/dist/src/server.d.ts +3 -0
- package/dist/src/server.js +21 -7
- package/dist/src/serverless.d.ts +42 -0
- package/dist/src/serverless.js +115 -0
- package/dist/src/state.d.ts +48 -0
- package/dist/src/state.js +98 -0
- package/dist/src/upstream.d.ts +30 -2
- package/dist/src/upstream.js +71 -2
- package/package.json +7 -4
package/README.md
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
# @redditech/provider-kit
|
|
2
2
|
|
|
3
|
-
Run your own paid provider on Reddi Agent Protocol: one config file, one command, any OpenAI-compatible model.
|
|
4
|
-
|
|
5
|
-
> Payments prove transfer; RAP Assurance proves paid work.
|
|
3
|
+
Run your own paid provider on Reddi Agent Protocol: one config file, one command, any OpenAI-compatible model or Claude.
|
|
6
4
|
|
|
7
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.
|
|
8
6
|
|
|
9
|
-
|
|
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.
|
|
10
13
|
|
|
11
14
|
## How a paid call works
|
|
12
15
|
|
|
@@ -27,17 +30,14 @@ The buyer is charged only after the model has answered, and the answer is sent o
|
|
|
27
30
|
| The charge | Tokens used times your price, rounded up to the smallest unit. |
|
|
28
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. |
|
|
29
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`. |
|
|
30
|
-
| 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
|
|
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 for a new buyer token account (about 0.002 SOL, not returned) with `refundAccountSubsidy`. |
|
|
31
34
|
|
|
32
35
|
## Quickstart on devnet
|
|
33
36
|
|
|
34
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.
|
|
35
38
|
|
|
36
39
|
```bash
|
|
37
|
-
|
|
38
|
-
npm --prefix packages/x402-solana ci && npm --prefix packages/x402-solana run build
|
|
39
|
-
npm --prefix packages/provider-kit ci && npm --prefix packages/provider-kit run build
|
|
40
|
-
alias rap-provider="node $PWD/packages/provider-kit/dist/src/cli.js"
|
|
40
|
+
npm install -g @redditech/provider-kit
|
|
41
41
|
|
|
42
42
|
# 1. A wallet for the provider. Fund its address with 0.5 devnet SOL at
|
|
43
43
|
# https://faucet.solana.com, then create its USDC token account.
|
|
@@ -49,16 +49,19 @@ spl-token create-account 4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU \
|
|
|
49
49
|
|
|
50
50
|
# 2. A config. It starts with mock answers so you can try the payment flow first.
|
|
51
51
|
rap-provider init --wallet "$(solana address -k ~/.config/solana/provider.json)"
|
|
52
|
-
#
|
|
52
|
+
# init points keypairPath at the Solana CLI default, ~/.config/solana/id.json.
|
|
53
|
+
# Set "keypairPath": "~/.config/solana/provider.json" in provider.json instead.
|
|
53
54
|
|
|
54
|
-
# 3. Check the setup. This reads only; it sends and spends nothing.
|
|
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.
|
|
55
58
|
rap-provider doctor
|
|
56
59
|
|
|
57
60
|
# 4. Serve.
|
|
58
61
|
rap-provider start
|
|
59
62
|
```
|
|
60
63
|
|
|
61
|
-
In another terminal, make a paid call as a buyer. 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.
|
|
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.
|
|
62
65
|
|
|
63
66
|
```bash
|
|
64
67
|
solana-keygen new --outfile ~/.config/solana/buyer.json
|
|
@@ -109,11 +112,11 @@ Every provider describes itself in [Agent Definition Language](https://agent-pro
|
|
|
109
112
|
|
|
110
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.
|
|
111
114
|
|
|
112
|
-
The most one call can cost is the price of every input token a request can hold (a 1 MB body,
|
|
115
|
+
The most one call can cost is the price of every input token a request can hold (a 1 MB body, at most 1,000,000 tokens at one a byte, 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.
|
|
113
116
|
|
|
114
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.
|
|
115
118
|
|
|
116
|
-
The wallet sign-in
|
|
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.
|
|
117
120
|
|
|
118
121
|
## Configuration
|
|
119
122
|
|
|
@@ -124,7 +127,10 @@ The wallet sign-in was checked against the devnet app on 21 November 2026: a mes
|
|
|
124
127
|
| `wallet` | Your provider wallet's address. Payouts go to its token account for the currency. |
|
|
125
128
|
| `publicUrl` | Where buyers reach you. Must be `https` unless it is localhost. |
|
|
126
129
|
| `model` | The model you declare. Receipts name it. It is a declaration, not proof of which model ran. |
|
|
127
|
-
| `upstream.
|
|
130
|
+
| `upstream.provider` | `openai-compatible` (the default) or `anthropic` for Claude through the Anthropic API. |
|
|
131
|
+
| `upstream.baseUrl` | An OpenAI-compatible base URL. Not used with `anthropic`. |
|
|
132
|
+
| `upstream.effort` | Claude only: `low`, `medium`, `high`, `xhigh` or `max`. Lower effort means fewer thinking tokens, so a lower bill for the buyer. |
|
|
133
|
+
| `upstream.thinking` | Claude only: `off` turns thinking off where the model allows it. Claude Opus 5.5 always thinks; lower `effort` instead. |
|
|
128
134
|
| `upstream.model` | The name to send upstream, when it differs from `model`. |
|
|
129
135
|
| `upstream.apiKeyEnv` | Name of the environment variable holding the API key. Default `UPSTREAM_API_KEY`. The key itself never goes in the file. |
|
|
130
136
|
| `upstream.mock` | `true` answers with canned text. Refused on mainnet. |
|
|
@@ -139,9 +145,12 @@ The wallet sign-in was checked against the devnet app on 21 November 2026: a mes
|
|
|
139
145
|
| `mint` | Devnet only, for currencies other than USDC. On mainnet the mints are fixed. |
|
|
140
146
|
| `pausedCurrencies` | Currencies you have stopped taking new locks in, for example `["PYUSD"]`. Also `RAP_PROVIDER_PAUSED_CURRENCIES=PYUSD,USDG`. See "Pausing a currency". |
|
|
141
147
|
| `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. |
|
|
142
|
-
| `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. |
|
|
148
|
+
| `refundAccountSubsidy.maxPerDay` | Off unless set. How many buyer token accounts you will pay to create in a UTC day, when a buyer closed, froze or handed over its own after you accepted its lock. |
|
|
149
|
+
| `capacity.requestsPerMinute` | Off unless set. Calls your model takes in any 60 seconds. Past it the provider answers `503 provider_busy` with `retry-after` before a buyer locks anything. Set it to a free model's rate limit. |
|
|
150
|
+
| `capacity.requestsPerDay` | Off unless set. Calls your model takes in a UTC day, a cap on your model bill. Past it the provider is offline until midnight UTC. |
|
|
151
|
+
| `capacity.cooldownSeconds` | Default 60. How long the provider stays busy after the model answers 429. The call that hit the 429 is refunded in full. |
|
|
143
152
|
| `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. |
|
|
144
|
-
| `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`). |
|
|
153
|
+
| `sessions.enabled` | Devnet only for now; refused on mainnet. `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`). |
|
|
145
154
|
| `sessions.idleSeconds` | How long a session may sit without a call before the kit settles it. 30 to 3600, default 600. |
|
|
146
155
|
| `sessions.file` | Where open sessions are remembered. Default `.rap-provider/sessions.jsonl`. Keep it on a disk that survives restarts. |
|
|
147
156
|
|
|
@@ -171,9 +180,9 @@ The kit then:
|
|
|
171
180
|
|
|
172
181
|
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.
|
|
173
182
|
|
|
174
|
-
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
|
|
183
|
+
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 cannot receive either, the settle creates a new token account for the buyer at your cost (about 0.002 SOL), only within `refundAccountSubsidy.maxPerDay`. Its address comes from your key and this lock, so the buyer cannot reach it before the settle lands, and a later lock at the same escrow address gets another; 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.
|
|
175
184
|
|
|
176
|
-
The worst case of a call counts
|
|
185
|
+
The worst case of a call counts every UTF-8 byte of input as one token, which no byte-level tokenizer exceeds, so a session's total stays under its lock.
|
|
177
186
|
|
|
178
187
|
## What the kit does to protect you and your buyers
|
|
179
188
|
|
|
@@ -182,22 +191,21 @@ The worst case of a call counts four characters of input as one token. A model t
|
|
|
182
191
|
- **One lock pays for one call**, including after a restart. Accepted escrows are written to disk before the model is called.
|
|
183
192
|
- **It checks the cluster** before trusting any account, so a lock on another network is never taken as payment.
|
|
184
193
|
- **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.
|
|
185
|
-
- **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
|
|
194
|
+
- **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 cannot receive either, the settle is held and the answer withheld, unless you opted in to `refundAccountSubsidy`, in which case the settle creates a new account for the buyer as above. A session's settle uses the same daily bound; see above.
|
|
186
195
|
- **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.
|
|
187
196
|
- **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.
|
|
188
197
|
- **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.
|
|
189
|
-
- **Run one process per payment memory file.** For several instances
|
|
198
|
+
- **Run one process per payment memory file.** For several instances at once, such as a serverless host, use the Postgres stores below: every instance then shares one record of what has been paid for and settled.
|
|
199
|
+
|
|
200
|
+
## Good to know
|
|
190
201
|
|
|
191
|
-
|
|
202
|
+
- 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.
|
|
203
|
+
- 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.)
|
|
204
|
+
- Calls take text messages and answer in one piece; `stream: true` is refused.
|
|
205
|
+
- Prices are in token currencies (USDC, AUDD, PYUSD, USDG).
|
|
206
|
+
- The quoted estimate counts four characters as one token, and the same count is used when a model reports no usage. The minimum lock counts one token a UTF-8 byte, so dense text (CJK, emoji, digits) still pays your full price.
|
|
192
207
|
|
|
193
|
-
|
|
194
|
-
- A single-call settle known not to have landed is not retried later by itself (a session's settle is retried by the sweep until the refund window). The log line `settle_failed` names the escrow; the lock stays open until its refund window, and you can settle it by hand within that time.
|
|
195
|
-
- No streaming responses. Requests with `stream: true` are refused.
|
|
196
|
-
- Message content must be text.
|
|
197
|
-
- Token currencies only. SOL-priced metered calls are not offered.
|
|
198
|
-
- The estimate counts four characters as one token. A buyer who locks exactly the minimum caps your payment at that estimate, so text that tokenises more densely can cost you the difference.
|
|
199
|
-
- When the model reports no usage, tokens are estimated the same way.
|
|
200
|
-
- Sessions on a rated escrow are not offered yet.
|
|
208
|
+
On the roadmap: streaming responses, SOL-priced metered calls, sessions on rated escrows, automatic retry of a single-call settle, and hardware wallet payers.
|
|
201
209
|
|
|
202
210
|
## Library use
|
|
203
211
|
|
|
@@ -207,6 +215,33 @@ import { createProviderHandler, parseProviderConfig, createProviderChain, FileRe
|
|
|
207
215
|
|
|
208
216
|
`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`.
|
|
209
217
|
|
|
218
|
+
## Serverless hosts (Vercel and similar)
|
|
219
|
+
|
|
220
|
+
A serverless host runs many short-lived copies of your provider at once, with no disk and no long-running timer. `createServerlessProvider` keeps everything the provider remembers in Postgres, so a lock pays for one call across every copy, one request at a time settles a lock, and the model's limits count calls on all of them.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import pg from "pg";
|
|
224
|
+
import { createServerlessProvider } from "@redditech/provider-kit";
|
|
225
|
+
import file from "./humaniser.provider.json" with { type: "json" };
|
|
226
|
+
|
|
227
|
+
const created = createServerlessProvider({
|
|
228
|
+
file,
|
|
229
|
+
env: process.env,
|
|
230
|
+
pool: new pg.Pool({ connectionString: process.env.PROVIDER_KIT_DATABASE_URL }),
|
|
231
|
+
keyEnv: "HUMANISER_KEYPAIR", // the wallet keypair, a JSON array of 64 numbers
|
|
232
|
+
promptEnv: "HUMANISER_PROMPT", // the private system prompt, never published
|
|
233
|
+
basePath: "/humaniser", // publicUrl must end with it
|
|
234
|
+
});
|
|
235
|
+
if (!created.ok) throw new Error(created.message);
|
|
236
|
+
export const { handle, sweep } = created.provider;
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
- Apply the `provider_kit` migration (`supabase/migrations/20261123120000_provider_kit_state.sql` in this repository) first. It creates a `provider_kit_app` role that can use these tables and nothing else; give it a login yourself and connect as it (through your database's pooler), never as the database owner. No client role can read the tables.
|
|
240
|
+
- Call `sweep()` every minute or so (a cron job behind a secret). It looks again at settles whose outcome was not known.
|
|
241
|
+
- An answer waiting for its settle to land is kept in the database for up to ten minutes, for the buyer to collect with the same request.
|
|
242
|
+
- Sessions and the refund-account subsidy are not offered on a serverless host yet; the provider refuses to start with them on.
|
|
243
|
+
- `postgresProviderStores(pool, providerId)` gives you the stores on their own, for any other host.
|
|
244
|
+
|
|
210
245
|
## License
|
|
211
246
|
|
|
212
247
|
MIT
|
package/dist/src/adl.d.ts
CHANGED
|
@@ -10,8 +10,8 @@ import { type ProviderConfig } from "./config.js";
|
|
|
10
10
|
/** Where the provider serves its ADL document. */
|
|
11
11
|
export declare const ADL_PATH = "/.well-known/adl.yaml";
|
|
12
12
|
/**
|
|
13
|
-
* The most one call can cost: every input token a request body can hold (
|
|
14
|
-
*
|
|
13
|
+
* The most one call can cost: every input token a request body can hold (at
|
|
14
|
+
* most one a UTF-8 byte, the bound the minimum lock uses, plus its system prompt) and
|
|
15
15
|
* the full output limit, at the listed price. A buyer never needs to
|
|
16
16
|
* authorise more for a single call.
|
|
17
17
|
*/
|
package/dist/src/adl.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* Level 3 or does not match it.
|
|
7
7
|
*/
|
|
8
8
|
import { ADL_V03_LAUNCH_RATE, ADL_V03_PROTOCOL_FEE_BPS, buildProviderAdl, checkAdlConformance, formatAdlDocument } from "@redditech/agent-protocol/adl";
|
|
9
|
-
import { baseUnitsToDecimal, directPaymentCurrency,
|
|
9
|
+
import { baseUnitsToDecimal, directPaymentCurrency, inputTokenBound, LAUNCH_PROTOCOL_FEE_BPS, LAUNCH_RATE_ENDS_AT_MS, PROTOCOL_FEE_BPS, tokenCostBaseUnits } from "@redditech/x402-solana";
|
|
10
10
|
import { MAX_BODY_BYTES } from "./config.js";
|
|
11
11
|
/** Where the provider serves its ADL document. */
|
|
12
12
|
export const ADL_PATH = "/.well-known/adl.yaml";
|
|
@@ -15,14 +15,14 @@ if (ADL_V03_PROTOCOL_FEE_BPS !== PROTOCOL_FEE_BPS || ADL_V03_LAUNCH_RATE.bps !==
|
|
|
15
15
|
throw new Error("The ADL protocol fee and @redditech/x402-solana disagree; update both packages together.");
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* The most one call can cost: every input token a request body can hold (
|
|
19
|
-
*
|
|
18
|
+
* The most one call can cost: every input token a request body can hold (at
|
|
19
|
+
* most one a UTF-8 byte, the bound the minimum lock uses, plus its system prompt) and
|
|
20
20
|
* the full output limit, at the listed price. A buyer never needs to
|
|
21
21
|
* authorise more for a single call.
|
|
22
22
|
*/
|
|
23
23
|
export function maxPerCall(config) {
|
|
24
24
|
const { terms } = config;
|
|
25
|
-
const inputTokens =
|
|
25
|
+
const inputTokens = MAX_BODY_BYTES + (config.systemPrompt ? inputTokenBound([{ content: config.systemPrompt }]) : 0);
|
|
26
26
|
const units = tokenCostBaseUnits(terms.price, { inputTokens, outputTokens: terms.maxOutputTokens });
|
|
27
27
|
return baseUnitsToDecimal(units, directPaymentCurrency(terms.price.currency).decimals);
|
|
28
28
|
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many calls the model behind this provider can take, so the provider
|
|
3
|
+
* says it is busy before a buyer locks anything, rather than taking a lock it
|
|
4
|
+
* then has to give back. Built for free or rate-limited models (a busy answer
|
|
5
|
+
* is the normal case there), and for a daily cap on a paid model's bill.
|
|
6
|
+
*
|
|
7
|
+
* The default store is in memory, per process. A host that runs several
|
|
8
|
+
* instances passes a shared one.
|
|
9
|
+
*/
|
|
10
|
+
export interface CapacityLimits {
|
|
11
|
+
/** Calls the model takes in any 60 seconds. */
|
|
12
|
+
requestsPerMinute?: number;
|
|
13
|
+
/** Calls the model takes in a UTC day. Past it the provider is offline until midnight UTC. */
|
|
14
|
+
requestsPerDay?: number;
|
|
15
|
+
/** How long to stay busy after the model answers 429 (too many requests). */
|
|
16
|
+
cooldownSeconds: number;
|
|
17
|
+
}
|
|
18
|
+
export type CapacityCheck = {
|
|
19
|
+
ok: true;
|
|
20
|
+
} | {
|
|
21
|
+
ok: false;
|
|
22
|
+
reason: "cooling_down" | "minute_limit" | "day_limit";
|
|
23
|
+
retryAfterSeconds: number;
|
|
24
|
+
};
|
|
25
|
+
export interface CapacityState {
|
|
26
|
+
/** Start times (ms) of calls in the last minute. */
|
|
27
|
+
recent: number[];
|
|
28
|
+
/** The UTC day (YYYY-MM-DD) `today` counts. */
|
|
29
|
+
day: string;
|
|
30
|
+
today: number;
|
|
31
|
+
/** Busy until this time (ms) after a 429. */
|
|
32
|
+
coolingUntil: number;
|
|
33
|
+
}
|
|
34
|
+
export interface CapacityStore {
|
|
35
|
+
/** Runs `update` on the current state and saves what it returns, as one step. */
|
|
36
|
+
update<T>(update: (state: CapacityState) => {
|
|
37
|
+
state: CapacityState;
|
|
38
|
+
result: T;
|
|
39
|
+
}): Promise<T>;
|
|
40
|
+
}
|
|
41
|
+
export declare class MemoryCapacityStore implements CapacityStore {
|
|
42
|
+
private state;
|
|
43
|
+
update<T>(update: (state: CapacityState) => {
|
|
44
|
+
state: CapacityState;
|
|
45
|
+
result: T;
|
|
46
|
+
}): Promise<T>;
|
|
47
|
+
}
|
|
48
|
+
export declare class Capacity {
|
|
49
|
+
private readonly limits;
|
|
50
|
+
private readonly store;
|
|
51
|
+
constructor(limits: CapacityLimits, store?: CapacityStore);
|
|
52
|
+
/** Whether a call could start now. Takes nothing. */
|
|
53
|
+
check(nowMs: number): Promise<CapacityCheck>;
|
|
54
|
+
/** Counts a call against the limits if there is room for it. */
|
|
55
|
+
take(nowMs: number): Promise<CapacityCheck>;
|
|
56
|
+
/** The model said it is overloaded: stay busy for the cooldown. */
|
|
57
|
+
coolDown(nowMs: number): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
export declare const BUSY_MESSAGES: Record<Exclude<CapacityCheck, {
|
|
60
|
+
ok: true;
|
|
61
|
+
}>["reason"], string>;
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How many calls the model behind this provider can take, so the provider
|
|
3
|
+
* says it is busy before a buyer locks anything, rather than taking a lock it
|
|
4
|
+
* then has to give back. Built for free or rate-limited models (a busy answer
|
|
5
|
+
* is the normal case there), and for a daily cap on a paid model's bill.
|
|
6
|
+
*
|
|
7
|
+
* The default store is in memory, per process. A host that runs several
|
|
8
|
+
* instances passes a shared one.
|
|
9
|
+
*/
|
|
10
|
+
export class MemoryCapacityStore {
|
|
11
|
+
state = { recent: [], day: "", today: 0, coolingUntil: 0 };
|
|
12
|
+
async update(update) {
|
|
13
|
+
const { state, result } = update(structuredClone(this.state));
|
|
14
|
+
this.state = state;
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const utcDay = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
19
|
+
const secondsUntilNextUtcDay = (ms) => Math.max(1, Math.ceil((Date.UTC(new Date(ms).getUTCFullYear(), new Date(ms).getUTCMonth(), new Date(ms).getUTCDate() + 1) - ms) / 1000));
|
|
20
|
+
function current(state, nowMs) {
|
|
21
|
+
const day = utcDay(nowMs);
|
|
22
|
+
return { recent: state.recent.filter((t) => t > nowMs - 60_000), day, today: state.day === day ? state.today : 0, coolingUntil: state.coolingUntil };
|
|
23
|
+
}
|
|
24
|
+
function verdict(state, limits, nowMs) {
|
|
25
|
+
if (state.coolingUntil > nowMs)
|
|
26
|
+
return { ok: false, reason: "cooling_down", retryAfterSeconds: Math.ceil((state.coolingUntil - nowMs) / 1000) };
|
|
27
|
+
if (limits.requestsPerDay !== undefined && state.today >= limits.requestsPerDay)
|
|
28
|
+
return { ok: false, reason: "day_limit", retryAfterSeconds: secondsUntilNextUtcDay(nowMs) };
|
|
29
|
+
if (limits.requestsPerMinute !== undefined && state.recent.length >= limits.requestsPerMinute) {
|
|
30
|
+
return { ok: false, reason: "minute_limit", retryAfterSeconds: Math.max(1, Math.ceil((state.recent[0] + 60_000 - nowMs) / 1000)) };
|
|
31
|
+
}
|
|
32
|
+
return { ok: true };
|
|
33
|
+
}
|
|
34
|
+
export class Capacity {
|
|
35
|
+
limits;
|
|
36
|
+
store;
|
|
37
|
+
constructor(limits, store = new MemoryCapacityStore()) {
|
|
38
|
+
this.limits = limits;
|
|
39
|
+
this.store = store;
|
|
40
|
+
}
|
|
41
|
+
/** Whether a call could start now. Takes nothing. */
|
|
42
|
+
check(nowMs) {
|
|
43
|
+
return this.store.update((state) => {
|
|
44
|
+
const s = current(state, nowMs);
|
|
45
|
+
return { state: s, result: verdict(s, this.limits, nowMs) };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/** Counts a call against the limits if there is room for it. */
|
|
49
|
+
take(nowMs) {
|
|
50
|
+
return this.store.update((state) => {
|
|
51
|
+
const s = current(state, nowMs);
|
|
52
|
+
const v = verdict(s, this.limits, nowMs);
|
|
53
|
+
if (!v.ok)
|
|
54
|
+
return { state: s, result: v };
|
|
55
|
+
return { state: { ...s, recent: [...s.recent, nowMs], today: s.today + 1 }, result: v };
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** The model said it is overloaded: stay busy for the cooldown. */
|
|
59
|
+
coolDown(nowMs) {
|
|
60
|
+
return this.store.update((state) => ({ state: { ...current(state, nowMs), coolingUntil: Math.max(state.coolingUntil, nowMs + this.limits.cooldownSeconds * 1000) }, result: undefined }));
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export const BUSY_MESSAGES = {
|
|
64
|
+
cooling_down: "The model behind this provider is cooling down after a rate limit.",
|
|
65
|
+
minute_limit: "This provider has taken all the calls its model allows this minute.",
|
|
66
|
+
day_limit: "This provider has taken all the calls its model allows today and is offline until midnight UTC.",
|
|
67
|
+
};
|
package/dist/src/cli.js
CHANGED
|
@@ -17,7 +17,7 @@ import { createProviderChain } from "./chain.js";
|
|
|
17
17
|
import { listingBody, publishListing, readListings } from "./listing.js";
|
|
18
18
|
import { AGENT_REGISTRATION_FEE_LAMPORTS, agentAddress, buildRegisterAgentInstruction, readAgentRecord } from "./registry.js";
|
|
19
19
|
import { checkProviderCluster } from "@redditech/x402-solana";
|
|
20
|
-
import { DEFAULT_CONFIG_FILE, exampleConfig, parseProviderConfig } from "./config.js";
|
|
20
|
+
import { DEFAULT_CONFIG_FILE, exampleConfig, parseProviderConfig, SOLANA_CLI_DEFAULT_KEY } from "./config.js";
|
|
21
21
|
import { formatDoctor, runDoctor } from "./doctor.js";
|
|
22
22
|
import { ADL_PATH, providerAdlText } from "./adl.js";
|
|
23
23
|
import { loadProviderKey } from "./keys.js";
|
|
@@ -100,7 +100,7 @@ export async function runCli(args, io) {
|
|
|
100
100
|
return 1;
|
|
101
101
|
}
|
|
102
102
|
writeFileSync(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
|
|
103
|
-
io.out(`Wrote ${path}.${wallet ? "" : " Set wallet to your provider wallet's address."}\nNext: rap-provider doctor`);
|
|
103
|
+
io.out(`Wrote ${path}.${wallet ? "" : " Set wallet to your provider wallet's address."}\nIts keypairPath is the Solana CLI default, ${SOLANA_CLI_DEFAULT_KEY}: point it at your provider wallet's key file. doctor reads that file only to check it matches the wallet.\nNext: rap-provider doctor`);
|
|
104
104
|
return 0;
|
|
105
105
|
}
|
|
106
106
|
if (command === "doctor") {
|
package/dist/src/config.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type MeteredTerms } from "@redditech/x402-solana";
|
|
2
|
+
import type { ClaudeEffort, ClaudeThinking } from "./upstream.js";
|
|
3
|
+
import type { CapacityLimits } from "./capacity.js";
|
|
2
4
|
export type ProviderNetwork = "solana-devnet" | "solana-mainnet-beta";
|
|
3
5
|
/** The V1 escrow and registry program. The same id on devnet and mainnet. */
|
|
4
6
|
export declare const DEFAULT_ESCROW_PROGRAM_ID = "DcfW3CxtZ6GnDU9xgA3sB7X4iFSvKRneYJ2Kvgdj5Ucu";
|
|
@@ -21,8 +23,14 @@ export interface ProviderConfigFile {
|
|
|
21
23
|
/** The model this provider declares it serves. Receipts name it. */
|
|
22
24
|
model: string;
|
|
23
25
|
upstream: {
|
|
26
|
+
/** "openai-compatible" (the default) calls `baseUrl`; "anthropic" calls Claude through the Anthropic API. */
|
|
27
|
+
provider?: string;
|
|
24
28
|
/** An OpenAI-compatible base URL, for example https://openrouter.ai/api/v1 or http://localhost:11434/v1. */
|
|
25
29
|
baseUrl?: string;
|
|
30
|
+
/** Claude only: how much effort the model puts into an answer (low, medium, high, xhigh, max). */
|
|
31
|
+
effort?: string;
|
|
32
|
+
/** Claude only: "off" turns thinking off where the model allows it; "adaptive" (the default) leaves it on. */
|
|
33
|
+
thinking?: string;
|
|
26
34
|
/** The model name to send upstream when it differs from `model`. */
|
|
27
35
|
model?: string;
|
|
28
36
|
/** Name of the environment variable holding the upstream API key. Defaults to UPSTREAM_API_KEY. */
|
|
@@ -75,6 +83,12 @@ export interface ProviderConfigFile {
|
|
|
75
83
|
refundAccountSubsidy?: {
|
|
76
84
|
maxPerDay: number;
|
|
77
85
|
};
|
|
86
|
+
/** How many calls the model takes. While full, the provider answers busy before any lock is taken. */
|
|
87
|
+
capacity?: {
|
|
88
|
+
requestsPerMinute?: number;
|
|
89
|
+
requestsPerDay?: number;
|
|
90
|
+
cooldownSeconds?: number;
|
|
91
|
+
};
|
|
78
92
|
/** For `rap-provider register`: the app to list in (default: the Reddi Agent Protocol app) and what the listing says this provider can do. */
|
|
79
93
|
listing?: {
|
|
80
94
|
appUrl?: string;
|
|
@@ -112,12 +126,15 @@ export interface ProviderConfig {
|
|
|
112
126
|
publicUrl: string;
|
|
113
127
|
model: string;
|
|
114
128
|
upstream: {
|
|
129
|
+
provider: "openai-compatible" | "anthropic";
|
|
115
130
|
baseUrl?: string;
|
|
116
131
|
model: string;
|
|
117
132
|
apiKey?: string;
|
|
118
133
|
apiKeyEnv: string;
|
|
119
134
|
mock: boolean;
|
|
120
135
|
timeoutMs: number;
|
|
136
|
+
effort?: ClaudeEffort;
|
|
137
|
+
thinking?: ClaudeThinking;
|
|
121
138
|
};
|
|
122
139
|
terms: MeteredTerms;
|
|
123
140
|
/** True while the price currency is in the paused list: no new locks are taken. */
|
|
@@ -125,6 +142,7 @@ export interface ProviderConfig {
|
|
|
125
142
|
pausedCurrencies: string[];
|
|
126
143
|
/** Buyer token accounts the provider will pay to create in a UTC day. 0: never. */
|
|
127
144
|
refundAccountsPerDay: number;
|
|
145
|
+
capacity: CapacityLimits;
|
|
128
146
|
/** The app `register` lists in. An https origin. */
|
|
129
147
|
appUrl: string;
|
|
130
148
|
listingCapabilities: Record<string, unknown>;
|
|
@@ -162,4 +180,6 @@ export declare function knownMint(network: ProviderNetwork, currency: string): s
|
|
|
162
180
|
*/
|
|
163
181
|
export declare function parseProviderConfig(file: unknown, env?: Record<string, string | undefined>): ConfigResult;
|
|
164
182
|
/** A starting config for `rap-provider init`. Mock upstream, devnet, USDC. */
|
|
183
|
+
/** The Solana CLI's default keypair, which `init` points at until the operator names a dedicated provider key. */
|
|
184
|
+
export declare const SOLANA_CLI_DEFAULT_KEY = "~/.config/solana/id.json";
|
|
165
185
|
export declare function exampleConfig(wallet: string): ProviderConfigFile;
|
package/dist/src/config.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { PublicKey } from "@solana/web3.js";
|
|
10
10
|
import { directPaymentCurrency, ESCROW_DEVNET_MINTS, ESCROW_MAINNET_MINTS, providerMeteredTerms } from "@redditech/x402-solana";
|
|
11
|
+
const CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
|
|
11
12
|
/** The V1 escrow and registry program. The same id on devnet and mainnet. */
|
|
12
13
|
export const DEFAULT_ESCROW_PROGRAM_ID = "DcfW3CxtZ6GnDU9xgA3sB7X4iFSvKRneYJ2Kvgdj5Ucu";
|
|
13
14
|
export const DEFAULT_DEVNET_RPC_URL = "https://api.devnet.solana.com";
|
|
@@ -79,9 +80,19 @@ export function parseProviderConfig(file, env = {}) {
|
|
|
79
80
|
errors.push("model: name the model this provider serves");
|
|
80
81
|
const upstreamRaw = isRecord(file.upstream) ? file.upstream : {};
|
|
81
82
|
const mock = upstreamRaw.mock === true;
|
|
82
|
-
const
|
|
83
|
+
const upstreamProvider = text(upstreamRaw.provider) || "openai-compatible";
|
|
84
|
+
if (upstreamProvider !== "openai-compatible" && upstreamProvider !== "anthropic")
|
|
85
|
+
errors.push('upstream.provider: must be "openai-compatible" or "anthropic"');
|
|
86
|
+
const claude = upstreamProvider === "anthropic";
|
|
87
|
+
const baseUrl = claude ? "" : text(upstreamRaw.baseUrl).replace(/\/+$/, "");
|
|
88
|
+
const effort = text(upstreamRaw.effort);
|
|
89
|
+
if (effort && (!claude || !CLAUDE_EFFORTS.includes(effort)))
|
|
90
|
+
errors.push(`upstream.effort: only for the anthropic provider, one of ${CLAUDE_EFFORTS.join(", ")}`);
|
|
91
|
+
const thinking = text(upstreamRaw.thinking);
|
|
92
|
+
if (thinking && (!claude || (thinking !== "adaptive" && thinking !== "off")))
|
|
93
|
+
errors.push('upstream.thinking: only for the anthropic provider, "adaptive" or "off"');
|
|
83
94
|
// A model on the operator's own network may be plain http; the key is then the operator's concern.
|
|
84
|
-
if (!mock && !serviceUrl(baseUrl, { allowHttpAnywhere: true }))
|
|
95
|
+
if (!mock && !claude && !serviceUrl(baseUrl, { allowHttpAnywhere: true }))
|
|
85
96
|
errors.push('upstream.baseUrl: must be an OpenAI-compatible base URL such as "https://openrouter.ai/api/v1", or set upstream.mock to true');
|
|
86
97
|
const apiKeyEnv = text(upstreamRaw.apiKeyEnv) || "UPSTREAM_API_KEY";
|
|
87
98
|
if (!/^[A-Z_][A-Z0-9_]*$/.test(apiKeyEnv))
|
|
@@ -135,6 +146,23 @@ export function parseProviderConfig(file, env = {}) {
|
|
|
135
146
|
const payoutAccount = text(file.payoutAccount);
|
|
136
147
|
if (payoutAccount && !isAddress(payoutAccount))
|
|
137
148
|
errors.push("payoutAccount: must be the address of a token account the provider wallet owns");
|
|
149
|
+
const capacityRaw = isRecord(file.capacity) ? file.capacity : {};
|
|
150
|
+
if (file.capacity !== undefined && !isRecord(file.capacity))
|
|
151
|
+
errors.push("capacity: must be an object");
|
|
152
|
+
const limit = (name, value, max) => {
|
|
153
|
+
if (value === undefined)
|
|
154
|
+
return undefined;
|
|
155
|
+
const n = Number(value);
|
|
156
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > max) {
|
|
157
|
+
errors.push(`capacity.${name}: must be a whole number from 1 to ${max}`);
|
|
158
|
+
return undefined;
|
|
159
|
+
}
|
|
160
|
+
return n;
|
|
161
|
+
};
|
|
162
|
+
const requestsPerMinute = limit("requestsPerMinute", capacityRaw.requestsPerMinute, 100_000);
|
|
163
|
+
const requestsPerDay = limit("requestsPerDay", capacityRaw.requestsPerDay, 10_000_000);
|
|
164
|
+
const cooldownSeconds = limit("cooldownSeconds", capacityRaw.cooldownSeconds, 86_400) ?? 60;
|
|
165
|
+
const capacity = { ...(requestsPerMinute ? { requestsPerMinute } : {}), ...(requestsPerDay ? { requestsPerDay } : {}), cooldownSeconds };
|
|
138
166
|
let refundAccountsPerDay = 0;
|
|
139
167
|
if (file.refundAccountSubsidy !== undefined) {
|
|
140
168
|
const maxPerDay = isRecord(file.refundAccountSubsidy) ? Number(file.refundAccountSubsidy.maxPerDay) : NaN;
|
|
@@ -158,6 +186,10 @@ export function parseProviderConfig(file, env = {}) {
|
|
|
158
186
|
const sessionsEnabled = sessionsRaw?.enabled === true;
|
|
159
187
|
if (sessionsRaw?.enabled !== undefined && typeof sessionsRaw.enabled !== "boolean")
|
|
160
188
|
errors.push("sessions.enabled: must be true or false");
|
|
189
|
+
// A buyer can leave a session unpaid by making its refund accounts unusable after it has been served
|
|
190
|
+
// (closing them, re-owning them, or requiring memos), so sessions are not offered on mainnet yet.
|
|
191
|
+
if (sessionsEnabled && network === "solana-mainnet-beta")
|
|
192
|
+
errors.push("sessions.enabled: sessions are not offered on mainnet yet; leave this off");
|
|
161
193
|
const idleSeconds = sessionsRaw?.idleSeconds === undefined ? 600 : Number(sessionsRaw.idleSeconds);
|
|
162
194
|
if (!Number.isSafeInteger(idleSeconds) || idleSeconds < 30 || idleSeconds > 3_600)
|
|
163
195
|
errors.push("sessions.idleSeconds: must be a whole number from 30 to 3600");
|
|
@@ -214,11 +246,22 @@ export function parseProviderConfig(file, env = {}) {
|
|
|
214
246
|
wallet,
|
|
215
247
|
publicUrl,
|
|
216
248
|
model,
|
|
217
|
-
upstream: {
|
|
249
|
+
upstream: {
|
|
250
|
+
provider: claude ? "anthropic" : "openai-compatible",
|
|
251
|
+
...(baseUrl ? { baseUrl } : {}),
|
|
252
|
+
model: text(upstreamRaw.model) || model,
|
|
253
|
+
...(apiKey ? { apiKey } : {}),
|
|
254
|
+
apiKeyEnv,
|
|
255
|
+
mock,
|
|
256
|
+
timeoutMs,
|
|
257
|
+
...(effort ? { effort: effort } : {}),
|
|
258
|
+
...(thinking ? { thinking: thinking } : {}),
|
|
259
|
+
},
|
|
218
260
|
terms,
|
|
219
261
|
paused: pausedCurrencies.includes(currency),
|
|
220
262
|
pausedCurrencies,
|
|
221
263
|
refundAccountsPerDay,
|
|
264
|
+
capacity,
|
|
222
265
|
appUrl: appUrl ?? DEFAULT_APP_URL,
|
|
223
266
|
listingCapabilities,
|
|
224
267
|
...(systemPrompt ? { systemPrompt } : {}),
|
|
@@ -233,6 +276,8 @@ export function parseProviderConfig(file, env = {}) {
|
|
|
233
276
|
};
|
|
234
277
|
}
|
|
235
278
|
/** A starting config for `rap-provider init`. Mock upstream, devnet, USDC. */
|
|
279
|
+
/** The Solana CLI's default keypair, which `init` points at until the operator names a dedicated provider key. */
|
|
280
|
+
export const SOLANA_CLI_DEFAULT_KEY = "~/.config/solana/id.json";
|
|
236
281
|
export function exampleConfig(wallet) {
|
|
237
282
|
return {
|
|
238
283
|
name: "My provider",
|
|
@@ -243,6 +288,6 @@ export function exampleConfig(wallet) {
|
|
|
243
288
|
model: "openai/gpt-4o-mini",
|
|
244
289
|
upstream: { baseUrl: "https://openrouter.ai/api/v1", apiKeyEnv: "UPSTREAM_API_KEY", mock: true },
|
|
245
290
|
price: { currency: "USDC", inputPerMillion: "0.15", outputPerMillion: "0.60", maxOutputTokens: 1000 },
|
|
246
|
-
keypairPath:
|
|
291
|
+
keypairPath: SOLANA_CLI_DEFAULT_KEY,
|
|
247
292
|
};
|
|
248
293
|
}
|
package/dist/src/doctor.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { ProviderChain } from "./chain.js";
|
|
2
|
-
import type
|
|
2
|
+
import { type ProviderConfig } from "./config.js";
|
|
3
3
|
import type { ProviderKeyResult } from "./keys.js";
|
|
4
4
|
export type CheckStatus = "pass" | "warn" | "fail";
|
|
5
5
|
export interface DoctorCheck {
|
|
@@ -24,6 +24,8 @@ export interface DoctorInput {
|
|
|
24
24
|
chain: ProviderChain;
|
|
25
25
|
key: ProviderKeyResult;
|
|
26
26
|
fetchImpl?: FetchLike;
|
|
27
|
+
/** Stands in for the network under the Anthropic client, for tests. */
|
|
28
|
+
anthropicFetch?: typeof fetch;
|
|
27
29
|
/** True when the directory can be written. Defaults to a real check. */
|
|
28
30
|
canWrite?: (directory: string) => boolean;
|
|
29
31
|
}
|
package/dist/src/doctor.js
CHANGED
|
@@ -4,8 +4,10 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { accessSync, constants, existsSync } from "node:fs";
|
|
6
6
|
import { dirname, resolve } from "node:path";
|
|
7
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
7
8
|
import { PublicKey } from "@solana/web3.js";
|
|
8
9
|
import { checkProviderCluster, checkTokenAccount, checkTreasuryReadiness, ESCROW_PROTOCOL_TREASURY, token2022MintPosture, treasuryTokenAccount } from "@redditech/x402-solana";
|
|
10
|
+
import { SOLANA_CLI_DEFAULT_KEY } from "./config.js";
|
|
9
11
|
import { ADL_PATH, maxPerCall, providerAdlText } from "./adl.js";
|
|
10
12
|
/** Enough for transaction fees, with room for the rent of a token account. */
|
|
11
13
|
export const WALLET_MIN_LAMPORTS = 10000000n;
|
|
@@ -114,12 +116,33 @@ export async function runDoctor(input) {
|
|
|
114
116
|
add({ name: "Chain accounts", status: "fail", detail: "an account could not be read", fix: "Check the RPC endpoint and try again." });
|
|
115
117
|
return done();
|
|
116
118
|
}
|
|
119
|
+
// Say which file was read, so reading the Solana CLI's default key never comes as a surprise.
|
|
120
|
+
const keyFile = config.keypairPath?.trim();
|
|
121
|
+
const keyNote = keyFile ? ` (read ${keyFile} to compare its public key; nothing from it is printed or sent${keyFile === SOLANA_CLI_DEFAULT_KEY ? ". This is the Solana CLI's default key: set keypairPath to use a dedicated provider wallet" : ""})` : "";
|
|
117
122
|
add(input.key.ok
|
|
118
|
-
? { name: "Signing key", status: "pass", detail:
|
|
119
|
-
: { name: "Signing key", status: "fail", detail: input.key.message
|
|
123
|
+
? { name: "Signing key", status: "pass", detail: `the key file belongs to the configured wallet${keyNote}` }
|
|
124
|
+
: { name: "Signing key", status: "fail", detail: `${input.key.message}${keyNote}`, fix: "Point keypairPath (or RAP_PROVIDER_KEYPAIR_PATH) at the wallet's keypair file." });
|
|
120
125
|
if (config.upstream.mock) {
|
|
121
126
|
add({ name: "Model", status: config.network === "solana-mainnet-beta" ? "fail" : "warn", detail: "mock answers are on, so buyers would pay for canned text", fix: "Set upstream.mock to false and upstream.baseUrl to your model before you list." });
|
|
122
127
|
}
|
|
128
|
+
else if (config.upstream.provider === "anthropic") {
|
|
129
|
+
const model = config.upstream.model;
|
|
130
|
+
if (!config.upstream.apiKey) {
|
|
131
|
+
add({ name: "Model", status: "fail", detail: `${config.upstream.apiKeyEnv} is not set, so Claude cannot be called`, fix: `Set ${config.upstream.apiKeyEnv} to an Anthropic API key in the environment.` });
|
|
132
|
+
}
|
|
133
|
+
else
|
|
134
|
+
try {
|
|
135
|
+
const client = new Anthropic({ apiKey: config.upstream.apiKey, maxRetries: 0, timeout: 10_000, ...(input.anthropicFetch ? { fetch: input.anthropicFetch } : {}) });
|
|
136
|
+
await client.models.retrieve(model);
|
|
137
|
+
add({ name: "Model", status: "pass", detail: `the Anthropic API serves ${model}` });
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
const status = error instanceof Anthropic.APIError ? error.status : undefined;
|
|
141
|
+
add(typeof status === "number"
|
|
142
|
+
? { name: "Model", status: "fail", detail: `the Anthropic API answered ${model} with status ${status}`, fix: status === 401 || status === 403 ? `Set ${config.upstream.apiKeyEnv} to a valid Anthropic API key.` : "Check upstream.model is a current Claude model id." }
|
|
143
|
+
: { name: "Model", status: "fail", detail: "the Anthropic API could not be reached", fix: `Check the network can reach api.anthropic.com and that ${config.upstream.apiKeyEnv} is set.` });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
123
146
|
else {
|
|
124
147
|
try {
|
|
125
148
|
const response = await fetchImpl(`${config.upstream.baseUrl}/models`, { method: "GET", headers: config.upstream.apiKey ? { authorization: `Bearer ${config.upstream.apiKey}` } : {}, signal: AbortSignal.timeout(10_000) });
|