@redditech/provider-kit 0.2.1 → 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 +44 -11
- 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/config.d.ts +18 -0
- package/dist/src/config.js +46 -3
- package/dist/src/doctor.d.ts +2 -0
- package/dist/src/doctor.js +19 -0
- 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 +6 -3
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
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.
|
|
3
|
+
Run your own paid provider on Reddi Agent Protocol: one config file, one command, any OpenAI-compatible model or Claude.
|
|
4
4
|
|
|
5
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
6
|
|
|
@@ -30,7 +30,7 @@ The buyer is charged only after the model has answered, and the answer is sent o
|
|
|
30
30
|
| The charge | Tokens used times your price, rounded up to the smallest unit. |
|
|
31
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
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
|
|
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`. |
|
|
34
34
|
|
|
35
35
|
## Quickstart on devnet
|
|
36
36
|
|
|
@@ -112,7 +112,7 @@ Every provider describes itself in [Agent Definition Language](https://agent-pro
|
|
|
112
112
|
|
|
113
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
114
|
|
|
115
|
-
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.
|
|
116
116
|
|
|
117
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
118
|
|
|
@@ -127,7 +127,10 @@ The wallet sign-in works against the devnet app: a message signed by the kit is
|
|
|
127
127
|
| `wallet` | Your provider wallet's address. Payouts go to its token account for the currency. |
|
|
128
128
|
| `publicUrl` | Where buyers reach you. Must be `https` unless it is localhost. |
|
|
129
129
|
| `model` | The model you declare. Receipts name it. It is a declaration, not proof of which model ran. |
|
|
130
|
-
| `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. |
|
|
131
134
|
| `upstream.model` | The name to send upstream, when it differs from `model`. |
|
|
132
135
|
| `upstream.apiKeyEnv` | Name of the environment variable holding the API key. Default `UPSTREAM_API_KEY`. The key itself never goes in the file. |
|
|
133
136
|
| `upstream.mock` | `true` answers with canned text. Refused on mainnet. |
|
|
@@ -142,9 +145,12 @@ The wallet sign-in works against the devnet app: a message signed by the kit is
|
|
|
142
145
|
| `mint` | Devnet only, for currencies other than USDC. On mainnet the mints are fixed. |
|
|
143
146
|
| `pausedCurrencies` | Currencies you have stopped taking new locks in, for example `["PYUSD"]`. Also `RAP_PROVIDER_PAUSED_CURRENCIES=PYUSD,USDG`. See "Pausing a currency". |
|
|
144
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. |
|
|
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. |
|
|
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. |
|
|
146
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. |
|
|
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`). |
|
|
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`). |
|
|
148
154
|
| `sessions.idleSeconds` | How long a session may sit without a call before the kit settles it. 30 to 3600, default 600. |
|
|
149
155
|
| `sessions.file` | Where open sessions are remembered. Default `.rap-provider/sessions.jsonl`. Keep it on a disk that survives restarts. |
|
|
150
156
|
|
|
@@ -174,9 +180,9 @@ The kit then:
|
|
|
174
180
|
|
|
175
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.
|
|
176
182
|
|
|
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
|
|
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.
|
|
178
184
|
|
|
179
|
-
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.
|
|
180
186
|
|
|
181
187
|
## What the kit does to protect you and your buyers
|
|
182
188
|
|
|
@@ -185,11 +191,11 @@ The worst case of a call counts four characters of input as one token. A model t
|
|
|
185
191
|
- **One lock pays for one call**, including after a restart. Accepted escrows are written to disk before the model is called.
|
|
186
192
|
- **It checks the cluster** before trusting any account, so a lock on another network is never taken as payment.
|
|
187
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.
|
|
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
|
|
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.
|
|
189
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.
|
|
190
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.
|
|
191
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.
|
|
192
|
-
- **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.
|
|
193
199
|
|
|
194
200
|
## Good to know
|
|
195
201
|
|
|
@@ -197,7 +203,7 @@ The worst case of a call counts four characters of input as one token. A model t
|
|
|
197
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.)
|
|
198
204
|
- Calls take text messages and answer in one piece; `stream: true` is refused.
|
|
199
205
|
- 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.
|
|
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.
|
|
201
207
|
|
|
202
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.
|
|
203
209
|
|
|
@@ -209,6 +215,33 @@ import { createProviderHandler, parseProviderConfig, createProviderChain, FileRe
|
|
|
209
215
|
|
|
210
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`.
|
|
211
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
|
+
|
|
212
245
|
## License
|
|
213
246
|
|
|
214
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/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>;
|
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 } : {}),
|
package/dist/src/doctor.d.ts
CHANGED
|
@@ -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,6 +4,7 @@
|
|
|
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";
|
|
9
10
|
import { SOLANA_CLI_DEFAULT_KEY } from "./config.js";
|
|
@@ -124,6 +125,24 @@ export async function runDoctor(input) {
|
|
|
124
125
|
if (config.upstream.mock) {
|
|
125
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." });
|
|
126
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
|
+
}
|
|
127
146
|
else {
|
|
128
147
|
try {
|
|
129
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) });
|
package/dist/src/handler.d.ts
CHANGED
|
@@ -2,8 +2,22 @@ import { type MeteredSessionLedger, type NonceReplayStore } from "@redditech/x40
|
|
|
2
2
|
import type { ProviderChain } from "./chain.js";
|
|
3
3
|
import { type PendingSettleStore } from "./pending.js";
|
|
4
4
|
import { type ProviderConfig } from "./config.js";
|
|
5
|
-
import type
|
|
5
|
+
import { type Upstream } from "./upstream.js";
|
|
6
|
+
import { Capacity } from "./capacity.js";
|
|
7
|
+
import { type HeldAnswerStore, type LockLease } from "./state.js";
|
|
6
8
|
export declare const PROVIDER_RECEIPT_HEADER = "x-reddi-provider-receipt";
|
|
9
|
+
/**
|
|
10
|
+
* Reads a request body as text, stopping as soon as it passes MAX_BODY_BYTES:
|
|
11
|
+
* a chunked body states no length, so the count is kept while reading and the
|
|
12
|
+
* rest is never buffered.
|
|
13
|
+
*/
|
|
14
|
+
export declare function readBodyText(request: Request, limit?: number): Promise<{
|
|
15
|
+
ok: true;
|
|
16
|
+
text: string;
|
|
17
|
+
} | {
|
|
18
|
+
ok: false;
|
|
19
|
+
reason: "too_large" | "unreadable";
|
|
20
|
+
}>;
|
|
7
21
|
/** The closing receipt of a session, on the answer that settled it. */
|
|
8
22
|
export declare const SESSION_RECEIPT_HEADER = "x-reddi-session-receipt";
|
|
9
23
|
/** On an answer that asked to close the session: settled, declined, or pending (tried again shortly). */
|
|
@@ -16,6 +30,12 @@ export interface ProviderDeps {
|
|
|
16
30
|
sessions?: MeteredSessionLedger;
|
|
17
31
|
/** Where single-call settles are recorded before they are sent. In memory when not given. */
|
|
18
32
|
pendingSettles?: PendingSettleStore;
|
|
33
|
+
/** How many calls the model takes. In memory, from the config's limits, when not given. */
|
|
34
|
+
capacity?: Capacity;
|
|
35
|
+
/** One request at a time per lock. In memory when not given; shared by every instance when several serve one provider. */
|
|
36
|
+
lease?: LockLease;
|
|
37
|
+
/** Answers waiting for their settle. In memory when not given; shared by every instance when several serve one provider. */
|
|
38
|
+
heldAnswers?: HeldAnswerStore;
|
|
19
39
|
/** Ed25519 signature by the provider wallet, for receipts. */
|
|
20
40
|
signMessage: (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
|
|
21
41
|
now?: () => Date;
|