@redditech/provider-kit 0.0.0-stage → 0.2.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/Dockerfile +33 -0
- package/LICENSE +21 -0
- package/README.md +211 -2
- package/dist/src/adl.d.ts +25 -0
- package/dist/src/adl.js +48 -0
- package/dist/src/chain.d.ts +45 -0
- package/dist/src/chain.js +150 -0
- package/dist/src/cli.d.ts +14 -0
- package/dist/src/cli.js +257 -0
- package/dist/src/config.d.ts +165 -0
- package/dist/src/config.js +248 -0
- package/dist/src/doctor.d.ts +38 -0
- package/dist/src/doctor.js +163 -0
- package/dist/src/handler.d.ts +32 -0
- package/dist/src/handler.js +1051 -0
- package/dist/src/index.d.ts +10 -0
- package/dist/src/index.js +10 -0
- package/dist/src/keys.d.ts +21 -0
- package/dist/src/keys.js +53 -0
- package/dist/src/listing.d.ts +57 -0
- package/dist/src/listing.js +117 -0
- package/dist/src/pending.d.ts +27 -0
- package/dist/src/pending.js +61 -0
- package/dist/src/registry.d.ts +25 -0
- package/dist/src/registry.js +52 -0
- package/dist/src/replay.d.ts +19 -0
- package/dist/src/replay.js +116 -0
- package/dist/src/server.d.ts +28 -0
- package/dist/src/server.js +123 -0
- package/dist/src/sessions.d.ts +10 -0
- package/dist/src/sessions.js +52 -0
- package/dist/src/upstream.d.ts +40 -0
- package/dist/src/upstream.js +56 -0
- package/examples/first-party/README.md +30 -0
- package/examples/first-party/humaniser.provider.json +15 -0
- package/examples/first-party/script-writer.provider.json +15 -0
- package/examples/paid-call.mjs +104 -0
- package/examples/session-call.mjs +111 -0
- package/package.json +50 -4
package/dist/src/cli.js
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* rap-provider: run your own paid provider on Reddi Agent Protocol.
|
|
4
|
+
*
|
|
5
|
+
* rap-provider init [--wallet <address>] [--config provider.json]
|
|
6
|
+
* rap-provider doctor [--config provider.json] [--json]
|
|
7
|
+
* rap-provider start [--config provider.json]
|
|
8
|
+
* rap-provider register [--config provider.json] [--dry-run]
|
|
9
|
+
* rap-provider status [--config provider.json]
|
|
10
|
+
* rap-provider adl [--config provider.json] [--json]
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { dirname, resolve } from "node:path";
|
|
14
|
+
import { pathToFileURL } from "node:url";
|
|
15
|
+
import { PublicKey } from "@solana/web3.js";
|
|
16
|
+
import { createProviderChain } from "./chain.js";
|
|
17
|
+
import { listingBody, publishListing, readListings } from "./listing.js";
|
|
18
|
+
import { AGENT_REGISTRATION_FEE_LAMPORTS, agentAddress, buildRegisterAgentInstruction, readAgentRecord } from "./registry.js";
|
|
19
|
+
import { checkProviderCluster } from "@redditech/x402-solana";
|
|
20
|
+
import { DEFAULT_CONFIG_FILE, exampleConfig, parseProviderConfig } from "./config.js";
|
|
21
|
+
import { formatDoctor, runDoctor } from "./doctor.js";
|
|
22
|
+
import { ADL_PATH, providerAdlText } from "./adl.js";
|
|
23
|
+
import { loadProviderKey } from "./keys.js";
|
|
24
|
+
import { startProvider } from "./server.js";
|
|
25
|
+
const HELP = `rap-provider: run your own paid provider on Reddi Agent Protocol
|
|
26
|
+
|
|
27
|
+
Commands
|
|
28
|
+
init Write a starting provider.json (devnet, USDC, mock answers).
|
|
29
|
+
doctor Check the setup without sending or spending anything.
|
|
30
|
+
start Serve the paid endpoint.
|
|
31
|
+
register Put the provider in the on-chain registry and list it in the app
|
|
32
|
+
with its per-token price. Run it again to update the listing.
|
|
33
|
+
status Show the registry record and the listing.
|
|
34
|
+
adl Print this provider's ADL v0.3 document (also served at
|
|
35
|
+
${ADL_PATH}) and check it passes Level 3.
|
|
36
|
+
|
|
37
|
+
Options
|
|
38
|
+
--config <file> Config file. Default: provider.json
|
|
39
|
+
--wallet <address> With init: the provider wallet's address.
|
|
40
|
+
--force With init: overwrite an existing config.
|
|
41
|
+
--json With doctor: print the checks as JSON. With adl: print the
|
|
42
|
+
Level 3 report as JSON.
|
|
43
|
+
--dry-run With register: print what would be sent and send nothing.
|
|
44
|
+
|
|
45
|
+
Environment
|
|
46
|
+
SOLANA_RPC_URL RPC endpoint. Required on mainnet.
|
|
47
|
+
RAP_PROVIDER_KEYPAIR_PATH The wallet's keypair file, if not in the config.
|
|
48
|
+
UPSTREAM_API_KEY API key for the model (name set by upstream.apiKeyEnv).
|
|
49
|
+
PORT Port to listen on. Default: 8787
|
|
50
|
+
RAP_APP_URL The app to list in. Default: https://app.agent-protocol.reddi.tech
|
|
51
|
+
`;
|
|
52
|
+
function option(args, name) {
|
|
53
|
+
const index = args.indexOf(name);
|
|
54
|
+
return index >= 0 && index + 1 < args.length ? args[index + 1] : undefined;
|
|
55
|
+
}
|
|
56
|
+
function loadConfig(args, io) {
|
|
57
|
+
const path = option(args, "--config") ?? DEFAULT_CONFIG_FILE;
|
|
58
|
+
let raw;
|
|
59
|
+
try {
|
|
60
|
+
raw = JSON.parse(readFileSync(path, "utf8"));
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
io.err(`${path} could not be read as JSON. Run "rap-provider init" to write one.`);
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
const promptFile = raw?.systemPromptFile;
|
|
67
|
+
if (typeof promptFile === "string" && promptFile.trim()) {
|
|
68
|
+
try {
|
|
69
|
+
raw = { ...raw, systemPrompt: readFileSync(resolve(dirname(path), promptFile.trim()), "utf8") };
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
io.err(`systemPromptFile: ${promptFile} could not be read.`);
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const parsed = parseProviderConfig(raw, io.env);
|
|
77
|
+
if (!parsed.ok) {
|
|
78
|
+
io.err(`${path} has ${parsed.errors.length} problem${parsed.errors.length === 1 ? "" : "s"}:\n${parsed.errors.map((e) => ` ${e}`).join("\n")}`);
|
|
79
|
+
return undefined;
|
|
80
|
+
}
|
|
81
|
+
return parsed.config;
|
|
82
|
+
}
|
|
83
|
+
/** Runs one command. Resolves with the exit code; `start` resolves only when it fails to start. */
|
|
84
|
+
export async function runCli(args, io) {
|
|
85
|
+
const command = args[0];
|
|
86
|
+
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
87
|
+
io.out(HELP);
|
|
88
|
+
return command ? 0 : 1;
|
|
89
|
+
}
|
|
90
|
+
if (command === "init") {
|
|
91
|
+
const path = option(args, "--config") ?? DEFAULT_CONFIG_FILE;
|
|
92
|
+
if (existsSync(path) && !args.includes("--force")) {
|
|
93
|
+
io.err(`${path} already exists. Pass --force to overwrite it.`);
|
|
94
|
+
return 1;
|
|
95
|
+
}
|
|
96
|
+
const wallet = option(args, "--wallet") ?? "";
|
|
97
|
+
const file = exampleConfig(wallet || "YOUR_WALLET_ADDRESS");
|
|
98
|
+
if (wallet && !parseProviderConfig(file, {}).ok) {
|
|
99
|
+
io.err("--wallet must be a Solana address.");
|
|
100
|
+
return 1;
|
|
101
|
+
}
|
|
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`);
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
if (command === "doctor") {
|
|
107
|
+
const config = loadConfig(args, io);
|
|
108
|
+
if (!config)
|
|
109
|
+
return 1;
|
|
110
|
+
const key = loadProviderKey({ keypairPath: config.keypairPath, wallet: config.wallet });
|
|
111
|
+
const result = await runDoctor({ config, chain: createProviderChain(config.rpcUrl), key });
|
|
112
|
+
io.out(args.includes("--json") ? JSON.stringify(result, null, 2) : formatDoctor(result));
|
|
113
|
+
return result.ok ? 0 : 1;
|
|
114
|
+
}
|
|
115
|
+
if (command === "adl") {
|
|
116
|
+
const config = loadConfig(args, io);
|
|
117
|
+
if (!config)
|
|
118
|
+
return 1;
|
|
119
|
+
const { text, report } = providerAdlText(config);
|
|
120
|
+
io.out(args.includes("--json") ? JSON.stringify(report, null, 2) : text);
|
|
121
|
+
if (report.status !== "pass")
|
|
122
|
+
io.err("This ADL document does not pass Level 3. Run with --json to see why.");
|
|
123
|
+
return report.status === "pass" ? 0 : 1;
|
|
124
|
+
}
|
|
125
|
+
if (command === "start") {
|
|
126
|
+
const config = loadConfig(args, io);
|
|
127
|
+
if (!config)
|
|
128
|
+
return 1;
|
|
129
|
+
const started = await startProvider(config, { log: (event) => io.out(JSON.stringify({ time: new Date().toISOString(), ...event })) });
|
|
130
|
+
if (!started.ok) {
|
|
131
|
+
io.err(`rap-provider cannot start: ${started.message}`);
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
const { terms } = config;
|
|
135
|
+
io.out(`${config.name} is listening on :${config.port} (${config.network}). ${terms.price.inputPerMillion} in / ${terms.price.outputPerMillion} out ${terms.price.currency} per million tokens.${config.upstream.mock ? " Mock answers are ON." : ""}`);
|
|
136
|
+
const stop = () => void started.close().then(() => process.exit(0));
|
|
137
|
+
process.once("SIGINT", stop);
|
|
138
|
+
process.once("SIGTERM", stop);
|
|
139
|
+
return new Promise(() => undefined);
|
|
140
|
+
}
|
|
141
|
+
if (command === "register" || command === "status") {
|
|
142
|
+
const config = loadConfig(args, io);
|
|
143
|
+
if (!config)
|
|
144
|
+
return 1;
|
|
145
|
+
const dryRun = args.includes("--dry-run");
|
|
146
|
+
const owner = new PublicKey(config.wallet);
|
|
147
|
+
const agent = agentAddress(config.terms.programId, owner);
|
|
148
|
+
const body = listingBody(config);
|
|
149
|
+
const makeChain = io.chain ?? ((c, keypair) => createProviderChain(c.rpcUrl, keypair));
|
|
150
|
+
if (command === "status") {
|
|
151
|
+
const chain = makeChain(config);
|
|
152
|
+
const cluster = await checkProviderCluster(() => chain.readGenesisHash(), config.network, config.genesisHash);
|
|
153
|
+
if (!cluster.ok) {
|
|
154
|
+
io.err(`The RPC endpoint is not ${config.network}, or could not be read.`);
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
const record = await chain.readAccount(agent).catch(() => undefined);
|
|
158
|
+
const held = record && record.owner.equals(config.terms.programId) ? readAgentRecord(record.data) : undefined;
|
|
159
|
+
io.out(record === undefined ? "Registry: could not be read." : held ? `Registry: registered at ${agent.toBase58()} (model ${held.model}).` : `Registry: not registered (${agent.toBase58()} does not exist).`);
|
|
160
|
+
const listed = await readListings({ config, ...(io.fetchImpl ? { fetchImpl: io.fetchImpl } : {}) });
|
|
161
|
+
if (!listed.ok) {
|
|
162
|
+
io.err(`Listing: ${listed.message}`);
|
|
163
|
+
return 1;
|
|
164
|
+
}
|
|
165
|
+
io.out(listed.listing ? `Listing: shown in ${config.appUrl} as ${JSON.stringify(listed.listing)}` : `Listing: not shown in ${config.appUrl}. A paused or draft listing is not public.`);
|
|
166
|
+
return held && listed.listing ? 0 : 1;
|
|
167
|
+
}
|
|
168
|
+
if (!body.ok) {
|
|
169
|
+
io.err(body.message);
|
|
170
|
+
return 1;
|
|
171
|
+
}
|
|
172
|
+
// The key must be the configured wallet's before anything is read or sent.
|
|
173
|
+
const key = loadProviderKey({ keypairPath: config.keypairPath, wallet: config.wallet });
|
|
174
|
+
if (!key.ok && !dryRun) {
|
|
175
|
+
io.err(`rap-provider cannot register: ${key.message}`);
|
|
176
|
+
return 1;
|
|
177
|
+
}
|
|
178
|
+
const chain = makeChain(config, key.ok ? key.key.keypair : undefined);
|
|
179
|
+
const cluster = await checkProviderCluster(() => chain.readGenesisHash(), config.network, config.genesisHash);
|
|
180
|
+
if (!cluster.ok) {
|
|
181
|
+
io.err(`The RPC endpoint is not ${config.network}, or could not be read. Nothing was sent.`);
|
|
182
|
+
return 1;
|
|
183
|
+
}
|
|
184
|
+
let existing;
|
|
185
|
+
try {
|
|
186
|
+
existing = await chain.readAccount(agent);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
io.err("The registry could not be read. Nothing was sent.");
|
|
190
|
+
return 1;
|
|
191
|
+
}
|
|
192
|
+
if (existing && (!existing.owner.equals(config.terms.programId) || !readAgentRecord(existing.data)?.owner.equals(owner))) {
|
|
193
|
+
io.err(`${agent.toBase58()} exists but is not this wallet's registry record. Nothing was sent.`);
|
|
194
|
+
return 1;
|
|
195
|
+
}
|
|
196
|
+
let instruction;
|
|
197
|
+
if (!existing) {
|
|
198
|
+
try {
|
|
199
|
+
instruction = buildRegisterAgentInstruction(config.terms.programId, owner, config.model);
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
io.err(`model: ${error instanceof Error ? error.message : "cannot be registered"}.`);
|
|
203
|
+
return 1;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (dryRun) {
|
|
207
|
+
io.out(JSON.stringify({
|
|
208
|
+
dryRun: true,
|
|
209
|
+
network: config.network,
|
|
210
|
+
registry: existing
|
|
211
|
+
? { alreadyRegistered: true, account: agent.toBase58() }
|
|
212
|
+
: { instruction: "register_agent", program: config.terms.programId.toBase58(), accounts: instruction.keys.map((k) => ({ address: k.pubkey.toBase58(), signer: k.isSigner, writable: k.isWritable })), model: config.model, burnsLamports: AGENT_REGISTRATION_FEE_LAMPORTS.toString() },
|
|
213
|
+
listing: { app: config.appUrl, request: "PUT /api/listings", body: body.body },
|
|
214
|
+
}, null, 2));
|
|
215
|
+
io.out(key.ok ? "Dry run: nothing was signed or sent." : `Dry run: nothing was signed or sent. Before a real run: ${key.message}`);
|
|
216
|
+
return 0;
|
|
217
|
+
}
|
|
218
|
+
if (!key.ok)
|
|
219
|
+
return 1;
|
|
220
|
+
if (instruction) {
|
|
221
|
+
try {
|
|
222
|
+
const signature = await chain.sendInstructions([instruction]);
|
|
223
|
+
io.out(`Registered on chain at ${agent.toBase58()} (transaction ${signature}). 0.01 SOL was burned as the registration fee.`);
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
io.err("The registration transaction did not confirm. Check the wallet's SOL balance (rap-provider doctor) and run register again; it sends nothing twice.");
|
|
227
|
+
return 1;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
io.out(`Already registered on chain at ${agent.toBase58()}.`);
|
|
232
|
+
}
|
|
233
|
+
const published = await publishListing({ config, body: body.body, signMessage: key.key.signMessage, ...(io.fetchImpl ? { fetchImpl: io.fetchImpl } : {}) });
|
|
234
|
+
if (!published.ok) {
|
|
235
|
+
io.err(`${published.message}\nThe on-chain registration stands. Run register again to retry the listing.`);
|
|
236
|
+
return 1;
|
|
237
|
+
}
|
|
238
|
+
io.out(`Listed in ${config.appUrl} as "${body.body.displayName}" (${body.body.status}): ${config.terms.price.inputPerMillion} in / ${config.terms.price.outputPerMillion} out ${config.terms.price.currency} per million tokens.`);
|
|
239
|
+
return 0;
|
|
240
|
+
}
|
|
241
|
+
io.err(`Unknown command "${command}".\n\n${HELP}`);
|
|
242
|
+
return 1;
|
|
243
|
+
}
|
|
244
|
+
function invokedDirectly() {
|
|
245
|
+
if (!process.argv[1])
|
|
246
|
+
return false;
|
|
247
|
+
try {
|
|
248
|
+
// npm runs the command through a symlink, so compare real paths.
|
|
249
|
+
return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (invokedDirectly()) {
|
|
256
|
+
runCli(process.argv.slice(2), { out: (t) => console.log(t), err: (t) => console.error(t), env: process.env }).then((code) => process.exit(code));
|
|
257
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { type MeteredTerms } from "@redditech/x402-solana";
|
|
2
|
+
export type ProviderNetwork = "solana-devnet" | "solana-mainnet-beta";
|
|
3
|
+
/** The V1 escrow and registry program. The same id on devnet and mainnet. */
|
|
4
|
+
export declare const DEFAULT_ESCROW_PROGRAM_ID = "DcfW3CxtZ6GnDU9xgA3sB7X4iFSvKRneYJ2Kvgdj5Ucu";
|
|
5
|
+
export declare const DEFAULT_DEVNET_RPC_URL = "https://api.devnet.solana.com";
|
|
6
|
+
export declare const DEFAULT_CONFIG_FILE = "provider.json";
|
|
7
|
+
export declare const DEFAULT_REPLAY_FILE = ".rap-provider/accepted-escrows.log";
|
|
8
|
+
export declare const DEFAULT_SESSION_FILE = ".rap-provider/sessions.jsonl";
|
|
9
|
+
export declare const DEFAULT_PORT = 8787;
|
|
10
|
+
export declare const DEFAULT_APP_URL = "https://app.agent-protocol.reddi.tech";
|
|
11
|
+
/** The largest request body the provider reads. It bounds the input tokens one call can be priced on. */
|
|
12
|
+
export declare const MAX_BODY_BYTES = 1000000;
|
|
13
|
+
export interface ProviderConfigFile {
|
|
14
|
+
name: string;
|
|
15
|
+
description?: string;
|
|
16
|
+
network: ProviderNetwork;
|
|
17
|
+
/** The provider wallet's address. Payments settle to its token account. */
|
|
18
|
+
wallet: string;
|
|
19
|
+
/** Where buyers reach this provider. Must be https unless it is localhost. */
|
|
20
|
+
publicUrl: string;
|
|
21
|
+
/** The model this provider declares it serves. Receipts name it. */
|
|
22
|
+
model: string;
|
|
23
|
+
upstream: {
|
|
24
|
+
/** An OpenAI-compatible base URL, for example https://openrouter.ai/api/v1 or http://localhost:11434/v1. */
|
|
25
|
+
baseUrl?: string;
|
|
26
|
+
/** The model name to send upstream when it differs from `model`. */
|
|
27
|
+
model?: string;
|
|
28
|
+
/** Name of the environment variable holding the upstream API key. Defaults to UPSTREAM_API_KEY. */
|
|
29
|
+
apiKeyEnv?: string;
|
|
30
|
+
/** Answer with a canned reply instead of calling a model. For trying the payment flow. */
|
|
31
|
+
mock?: boolean;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
};
|
|
34
|
+
price: {
|
|
35
|
+
currency: string;
|
|
36
|
+
/** Decimal price per million input and output tokens, in `currency`. */
|
|
37
|
+
inputPerMillion: string;
|
|
38
|
+
outputPerMillion: string;
|
|
39
|
+
maxOutputTokens?: number;
|
|
40
|
+
};
|
|
41
|
+
/** A system prompt placed before every request. Optional. */
|
|
42
|
+
systemPrompt?: string;
|
|
43
|
+
/**
|
|
44
|
+
* A text file holding the system prompt, relative to the config file. Use it
|
|
45
|
+
* for long or private instructions you do not want in the config. It
|
|
46
|
+
* replaces `systemPrompt`.
|
|
47
|
+
*/
|
|
48
|
+
systemPromptFile?: string;
|
|
49
|
+
rpcUrl?: string;
|
|
50
|
+
/** Override only for a local validator or a test deployment. */
|
|
51
|
+
programId?: string;
|
|
52
|
+
/** The mint for `price.currency`. Needed on devnet for anything but USDC; fixed on mainnet. */
|
|
53
|
+
mint?: string;
|
|
54
|
+
/**
|
|
55
|
+
* Currencies this provider has stopped taking new locks in, for example
|
|
56
|
+
* ["PYUSD"] after its issuer changes how transfers work. While the price
|
|
57
|
+
* currency is listed, paid calls are refused before any lock is read and the
|
|
58
|
+
* provider's metadata says it is not accepting payments. Locks already
|
|
59
|
+
* accepted still settle. `RAP_PROVIDER_PAUSED_CURRENCIES` (comma-separated)
|
|
60
|
+
* adds to this list without editing the file.
|
|
61
|
+
*/
|
|
62
|
+
pausedCurrencies?: string[];
|
|
63
|
+
/**
|
|
64
|
+
* Recovery only: another token account of the mint that the provider wallet
|
|
65
|
+
* owns. Payouts go here when the wallet's usual token account is closed or
|
|
66
|
+
* frozen.
|
|
67
|
+
*/
|
|
68
|
+
payoutAccount?: string;
|
|
69
|
+
/**
|
|
70
|
+
* Off unless set. Lets the provider pay the rent (about 0.002 SOL, not
|
|
71
|
+
* returned) to create a buyer's token account when the buyer closed its own
|
|
72
|
+
* after the lock was accepted, so the settle can still land. `maxPerDay`
|
|
73
|
+
* bounds how many it pays for in a UTC day.
|
|
74
|
+
*/
|
|
75
|
+
refundAccountSubsidy?: {
|
|
76
|
+
maxPerDay: number;
|
|
77
|
+
};
|
|
78
|
+
/** 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
|
+
listing?: {
|
|
80
|
+
appUrl?: string;
|
|
81
|
+
capabilities?: Record<string, unknown>;
|
|
82
|
+
};
|
|
83
|
+
/** For a local validator only: the genesis hash to expect instead of the public devnet one. */
|
|
84
|
+
genesisHash?: string;
|
|
85
|
+
/**
|
|
86
|
+
* Off unless true. Also accept a payer's delegation proved by a memo in its
|
|
87
|
+
* lock transaction (Solana Pay transaction requests, where the wallet signs a
|
|
88
|
+
* transaction but no separate message). Each such request costs one
|
|
89
|
+
* transaction read from your RPC before the lock is checked.
|
|
90
|
+
*/
|
|
91
|
+
lockBoundDelegations?: boolean;
|
|
92
|
+
/**
|
|
93
|
+
* Sessions: one lock pays for many calls and is settled once. Off unless
|
|
94
|
+
* `enabled` is true. A session is settled after `idleSeconds` without a call
|
|
95
|
+
* (default 600), when the buyer closes it, or before its refund window opens.
|
|
96
|
+
* `file` keeps the sessions across restarts.
|
|
97
|
+
*/
|
|
98
|
+
sessions?: {
|
|
99
|
+
enabled?: boolean;
|
|
100
|
+
idleSeconds?: number;
|
|
101
|
+
file?: string;
|
|
102
|
+
};
|
|
103
|
+
keypairPath?: string;
|
|
104
|
+
replayFile?: string;
|
|
105
|
+
port?: number;
|
|
106
|
+
}
|
|
107
|
+
export interface ProviderConfig {
|
|
108
|
+
name: string;
|
|
109
|
+
description: string;
|
|
110
|
+
network: ProviderNetwork;
|
|
111
|
+
wallet: string;
|
|
112
|
+
publicUrl: string;
|
|
113
|
+
model: string;
|
|
114
|
+
upstream: {
|
|
115
|
+
baseUrl?: string;
|
|
116
|
+
model: string;
|
|
117
|
+
apiKey?: string;
|
|
118
|
+
apiKeyEnv: string;
|
|
119
|
+
mock: boolean;
|
|
120
|
+
timeoutMs: number;
|
|
121
|
+
};
|
|
122
|
+
terms: MeteredTerms;
|
|
123
|
+
/** True while the price currency is in the paused list: no new locks are taken. */
|
|
124
|
+
paused: boolean;
|
|
125
|
+
pausedCurrencies: string[];
|
|
126
|
+
/** Buyer token accounts the provider will pay to create in a UTC day. 0: never. */
|
|
127
|
+
refundAccountsPerDay: number;
|
|
128
|
+
/** The app `register` lists in. An https origin. */
|
|
129
|
+
appUrl: string;
|
|
130
|
+
listingCapabilities: Record<string, unknown>;
|
|
131
|
+
systemPrompt?: string;
|
|
132
|
+
rpcUrl: string;
|
|
133
|
+
genesisHash?: string;
|
|
134
|
+
/** Accept delegations proved by a memo in the lock transaction. */
|
|
135
|
+
lockBoundDelegations: boolean;
|
|
136
|
+
keypairPath?: string;
|
|
137
|
+
replayFile: string;
|
|
138
|
+
sessions: {
|
|
139
|
+
enabled: boolean;
|
|
140
|
+
idleMs: number;
|
|
141
|
+
file: string;
|
|
142
|
+
};
|
|
143
|
+
port: number;
|
|
144
|
+
}
|
|
145
|
+
export type ConfigResult = {
|
|
146
|
+
ok: true;
|
|
147
|
+
config: ProviderConfig;
|
|
148
|
+
} | {
|
|
149
|
+
ok: false;
|
|
150
|
+
errors: string[];
|
|
151
|
+
};
|
|
152
|
+
/** An http(s) URL with no credentials, query or fragment, or undefined. Plain http is for localhost only. */
|
|
153
|
+
export declare function serviceUrl(value: string, options?: {
|
|
154
|
+
allowHttpAnywhere?: boolean;
|
|
155
|
+
}): URL | undefined;
|
|
156
|
+
/** The mint the escrow program accepts for a currency on a network, when it is fixed. */
|
|
157
|
+
export declare function knownMint(network: ProviderNetwork, currency: string): string | undefined;
|
|
158
|
+
/**
|
|
159
|
+
* Turns the config file's contents and the environment into a checked
|
|
160
|
+
* configuration. `RAP_PROVIDER_KEYPAIR_PATH`, `SOLANA_RPC_URL` and `PORT`
|
|
161
|
+
* override the file; the upstream API key is read only from the environment.
|
|
162
|
+
*/
|
|
163
|
+
export declare function parseProviderConfig(file: unknown, env?: Record<string, string | undefined>): ConfigResult;
|
|
164
|
+
/** A starting config for `rap-provider init`. Mock upstream, devnet, USDC. */
|
|
165
|
+
export declare function exampleConfig(wallet: string): ProviderConfigFile;
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A provider's configuration: one JSON file, plus a few environment variables
|
|
3
|
+
* for things that should not sit in a file (the upstream API key) or that
|
|
4
|
+
* differ per machine (the RPC endpoint, the key file path).
|
|
5
|
+
*
|
|
6
|
+
* Parsing fails closed: anything missing or malformed is an error that names
|
|
7
|
+
* the field, and the provider does not start.
|
|
8
|
+
*/
|
|
9
|
+
import { PublicKey } from "@solana/web3.js";
|
|
10
|
+
import { directPaymentCurrency, ESCROW_DEVNET_MINTS, ESCROW_MAINNET_MINTS, providerMeteredTerms } from "@redditech/x402-solana";
|
|
11
|
+
/** The V1 escrow and registry program. The same id on devnet and mainnet. */
|
|
12
|
+
export const DEFAULT_ESCROW_PROGRAM_ID = "DcfW3CxtZ6GnDU9xgA3sB7X4iFSvKRneYJ2Kvgdj5Ucu";
|
|
13
|
+
export const DEFAULT_DEVNET_RPC_URL = "https://api.devnet.solana.com";
|
|
14
|
+
export const DEFAULT_CONFIG_FILE = "provider.json";
|
|
15
|
+
export const DEFAULT_REPLAY_FILE = ".rap-provider/accepted-escrows.log";
|
|
16
|
+
export const DEFAULT_SESSION_FILE = ".rap-provider/sessions.jsonl";
|
|
17
|
+
export const DEFAULT_PORT = 8787;
|
|
18
|
+
export const DEFAULT_APP_URL = "https://app.agent-protocol.reddi.tech";
|
|
19
|
+
/** The largest request body the provider reads. It bounds the input tokens one call can be priced on. */
|
|
20
|
+
export const MAX_BODY_BYTES = 1_000_000;
|
|
21
|
+
const isRecord = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
22
|
+
const text = (value) => (typeof value === "string" ? value.trim() : "");
|
|
23
|
+
function isAddress(value) {
|
|
24
|
+
try {
|
|
25
|
+
return new PublicKey(value).toBase58() === value;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** An http(s) URL with no credentials, query or fragment, or undefined. Plain http is for localhost only. */
|
|
32
|
+
export function serviceUrl(value, options = {}) {
|
|
33
|
+
let url;
|
|
34
|
+
try {
|
|
35
|
+
url = new URL(value);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
if (url.username || url.password || url.search || url.hash)
|
|
41
|
+
return undefined;
|
|
42
|
+
const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
|
|
43
|
+
if (url.protocol === "https:")
|
|
44
|
+
return url;
|
|
45
|
+
if (url.protocol === "http:" && (local || options.allowHttpAnywhere))
|
|
46
|
+
return url;
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
/** The mint the escrow program accepts for a currency on a network, when it is fixed. */
|
|
50
|
+
export function knownMint(network, currency) {
|
|
51
|
+
if (network === "solana-mainnet-beta")
|
|
52
|
+
return ESCROW_MAINNET_MINTS.find((m) => m.symbol === currency)?.mint.toBase58();
|
|
53
|
+
return currency === "USDC" ? ESCROW_DEVNET_MINTS[0]?.mint.toBase58() : undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Turns the config file's contents and the environment into a checked
|
|
57
|
+
* configuration. `RAP_PROVIDER_KEYPAIR_PATH`, `SOLANA_RPC_URL` and `PORT`
|
|
58
|
+
* override the file; the upstream API key is read only from the environment.
|
|
59
|
+
*/
|
|
60
|
+
export function parseProviderConfig(file, env = {}) {
|
|
61
|
+
const errors = [];
|
|
62
|
+
if (!isRecord(file))
|
|
63
|
+
return { ok: false, errors: ["the config must be a JSON object"] };
|
|
64
|
+
const name = text(file.name);
|
|
65
|
+
if (!name || name.length > 80)
|
|
66
|
+
errors.push("name: give the provider a name of at most 80 characters");
|
|
67
|
+
const description = text(file.description);
|
|
68
|
+
const network = text(file.network);
|
|
69
|
+
if (network !== "solana-devnet" && network !== "solana-mainnet-beta")
|
|
70
|
+
errors.push('network: must be "solana-devnet" or "solana-mainnet-beta"');
|
|
71
|
+
const wallet = text(file.wallet);
|
|
72
|
+
if (!isAddress(wallet))
|
|
73
|
+
errors.push("wallet: must be the provider wallet's Solana address");
|
|
74
|
+
const publicUrl = text(file.publicUrl).replace(/\/+$/, "");
|
|
75
|
+
if (!serviceUrl(publicUrl))
|
|
76
|
+
errors.push("publicUrl: must be an https address (http is accepted for localhost only), with no query or credentials");
|
|
77
|
+
const model = text(file.model);
|
|
78
|
+
if (!model || model.length > 200)
|
|
79
|
+
errors.push("model: name the model this provider serves");
|
|
80
|
+
const upstreamRaw = isRecord(file.upstream) ? file.upstream : {};
|
|
81
|
+
const mock = upstreamRaw.mock === true;
|
|
82
|
+
const baseUrl = text(upstreamRaw.baseUrl).replace(/\/+$/, "");
|
|
83
|
+
// 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 }))
|
|
85
|
+
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
|
+
const apiKeyEnv = text(upstreamRaw.apiKeyEnv) || "UPSTREAM_API_KEY";
|
|
87
|
+
if (!/^[A-Z_][A-Z0-9_]*$/.test(apiKeyEnv))
|
|
88
|
+
errors.push("upstream.apiKeyEnv: must be the name of an environment variable");
|
|
89
|
+
const timeoutMs = upstreamRaw.timeoutMs === undefined ? 120_000 : Number(upstreamRaw.timeoutMs);
|
|
90
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1_000 || timeoutMs > 600_000)
|
|
91
|
+
errors.push("upstream.timeoutMs: must be between 1000 and 600000");
|
|
92
|
+
const priceRaw = isRecord(file.price) ? file.price : {};
|
|
93
|
+
const currency = text(priceRaw.currency);
|
|
94
|
+
const programId = text(file.programId) || DEFAULT_ESCROW_PROGRAM_ID;
|
|
95
|
+
if (!isAddress(programId))
|
|
96
|
+
errors.push("programId: must be a Solana address");
|
|
97
|
+
if (network === "solana-mainnet-beta" && programId !== DEFAULT_ESCROW_PROGRAM_ID)
|
|
98
|
+
errors.push("programId: cannot be changed on mainnet");
|
|
99
|
+
let mint = text(file.mint);
|
|
100
|
+
if (!directPaymentCurrency(currency)) {
|
|
101
|
+
errors.push("price.currency: must be USDC, AUDD, PYUSD or USDG");
|
|
102
|
+
}
|
|
103
|
+
else if (!directPaymentCurrency(currency)?.tokenProgram) {
|
|
104
|
+
errors.push(`price.currency: ${currency} is not a token currency; use USDC, AUDD, PYUSD or USDG`);
|
|
105
|
+
}
|
|
106
|
+
else if (network === "solana-devnet" || network === "solana-mainnet-beta") {
|
|
107
|
+
const known = knownMint(network, currency);
|
|
108
|
+
if (network === "solana-mainnet-beta") {
|
|
109
|
+
if (!known)
|
|
110
|
+
errors.push(`price.currency: ${currency} is not accepted by the escrow program on mainnet`);
|
|
111
|
+
else if (mint && mint !== known)
|
|
112
|
+
errors.push(`mint: on mainnet ${currency} is ${known} and cannot be changed`);
|
|
113
|
+
else
|
|
114
|
+
mint = known;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
mint = mint || known || "";
|
|
118
|
+
if (!mint)
|
|
119
|
+
errors.push(`mint: on devnet, name the mint to accept for ${currency}`);
|
|
120
|
+
else if (!isAddress(mint))
|
|
121
|
+
errors.push("mint: must be a Solana address");
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const pausedRaw = [...(Array.isArray(file.pausedCurrencies) ? file.pausedCurrencies : file.pausedCurrencies === undefined ? [] : [file.pausedCurrencies]), ...text(env.RAP_PROVIDER_PAUSED_CURRENCIES).split(",")];
|
|
125
|
+
const pausedCurrencies = [];
|
|
126
|
+
for (const entry of pausedRaw) {
|
|
127
|
+
const symbol = text(entry).toUpperCase();
|
|
128
|
+
if (!symbol && typeof entry === "string")
|
|
129
|
+
continue;
|
|
130
|
+
if (!directPaymentCurrency(symbol)?.tokenProgram)
|
|
131
|
+
errors.push("pausedCurrencies: list currency symbols such as PYUSD or USDG");
|
|
132
|
+
else if (!pausedCurrencies.includes(symbol))
|
|
133
|
+
pausedCurrencies.push(symbol);
|
|
134
|
+
}
|
|
135
|
+
const payoutAccount = text(file.payoutAccount);
|
|
136
|
+
if (payoutAccount && !isAddress(payoutAccount))
|
|
137
|
+
errors.push("payoutAccount: must be the address of a token account the provider wallet owns");
|
|
138
|
+
let refundAccountsPerDay = 0;
|
|
139
|
+
if (file.refundAccountSubsidy !== undefined) {
|
|
140
|
+
const maxPerDay = isRecord(file.refundAccountSubsidy) ? Number(file.refundAccountSubsidy.maxPerDay) : NaN;
|
|
141
|
+
if (!Number.isSafeInteger(maxPerDay) || maxPerDay < 0 || maxPerDay > 1_000)
|
|
142
|
+
errors.push("refundAccountSubsidy.maxPerDay: must be a whole number from 0 to 1000");
|
|
143
|
+
else
|
|
144
|
+
refundAccountsPerDay = maxPerDay;
|
|
145
|
+
}
|
|
146
|
+
const listingRaw = isRecord(file.listing) ? file.listing : {};
|
|
147
|
+
const appUrlRaw = text(env.RAP_APP_URL) || text(listingRaw.appUrl) || DEFAULT_APP_URL;
|
|
148
|
+
const appUrl = serviceUrl(appUrlRaw)?.origin;
|
|
149
|
+
if (!appUrl || new URL(appUrlRaw).pathname.replace(/\/+$/, "") !== "")
|
|
150
|
+
errors.push("listing.appUrl: must be the app's address, such as https://app.agent-protocol.reddi.tech");
|
|
151
|
+
if (listingRaw.capabilities !== undefined && !isRecord(listingRaw.capabilities))
|
|
152
|
+
errors.push("listing.capabilities: must be an object");
|
|
153
|
+
const listingCapabilities = isRecord(listingRaw.capabilities) ? listingRaw.capabilities : {};
|
|
154
|
+
const sessionsRaw = file.sessions === undefined ? {} : isRecord(file.sessions) ? file.sessions : undefined;
|
|
155
|
+
if (!sessionsRaw)
|
|
156
|
+
errors.push("sessions: must be an object");
|
|
157
|
+
// Off by default: turn on only for a provider that watches its session alerts.
|
|
158
|
+
const sessionsEnabled = sessionsRaw?.enabled === true;
|
|
159
|
+
if (sessionsRaw?.enabled !== undefined && typeof sessionsRaw.enabled !== "boolean")
|
|
160
|
+
errors.push("sessions.enabled: must be true or false");
|
|
161
|
+
const idleSeconds = sessionsRaw?.idleSeconds === undefined ? 600 : Number(sessionsRaw.idleSeconds);
|
|
162
|
+
if (!Number.isSafeInteger(idleSeconds) || idleSeconds < 30 || idleSeconds > 3_600)
|
|
163
|
+
errors.push("sessions.idleSeconds: must be a whole number from 30 to 3600");
|
|
164
|
+
const genesisHash = text(file.genesisHash) || undefined;
|
|
165
|
+
if (file.lockBoundDelegations !== undefined && typeof file.lockBoundDelegations !== "boolean")
|
|
166
|
+
errors.push("lockBoundDelegations: must be true or false");
|
|
167
|
+
if (genesisHash && network === "solana-mainnet-beta")
|
|
168
|
+
errors.push("genesisHash: cannot be set on mainnet");
|
|
169
|
+
const rpcUrl = text(env.SOLANA_RPC_URL) || text(file.rpcUrl) || (network === "solana-devnet" ? DEFAULT_DEVNET_RPC_URL : "");
|
|
170
|
+
if (!rpcUrl)
|
|
171
|
+
errors.push("rpcUrl: on mainnet, set SOLANA_RPC_URL (or rpcUrl) to your RPC provider's endpoint");
|
|
172
|
+
else {
|
|
173
|
+
try {
|
|
174
|
+
const url = new URL(rpcUrl);
|
|
175
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
176
|
+
throw new Error("protocol");
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
errors.push("rpcUrl: must be an http(s) address");
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const portRaw = text(env.PORT) || (file.port === undefined ? "" : String(file.port));
|
|
183
|
+
const port = portRaw ? Number(portRaw) : DEFAULT_PORT;
|
|
184
|
+
if (!Number.isSafeInteger(port) || port < 1 || port > 65_535)
|
|
185
|
+
errors.push("port: must be between 1 and 65535");
|
|
186
|
+
let terms;
|
|
187
|
+
if (errors.length === 0) {
|
|
188
|
+
try {
|
|
189
|
+
terms = providerMeteredTerms({
|
|
190
|
+
currency,
|
|
191
|
+
inputPerMillion: text(priceRaw.inputPerMillion),
|
|
192
|
+
outputPerMillion: text(priceRaw.outputPerMillion),
|
|
193
|
+
...(priceRaw.maxOutputTokens === undefined ? {} : { maxOutputTokens: Number(priceRaw.maxOutputTokens) }),
|
|
194
|
+
programId,
|
|
195
|
+
mint,
|
|
196
|
+
payee: wallet,
|
|
197
|
+
...(payoutAccount ? { payoutAccount } : {}),
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
errors.push(`price: ${error instanceof Error ? error.message : "could not be read"}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (errors.length > 0 || !terms)
|
|
205
|
+
return { ok: false, errors };
|
|
206
|
+
const systemPrompt = text(file.systemPrompt) || undefined;
|
|
207
|
+
const apiKey = text(env[apiKeyEnv]) || undefined;
|
|
208
|
+
return {
|
|
209
|
+
ok: true,
|
|
210
|
+
config: {
|
|
211
|
+
name,
|
|
212
|
+
description,
|
|
213
|
+
network,
|
|
214
|
+
wallet,
|
|
215
|
+
publicUrl,
|
|
216
|
+
model,
|
|
217
|
+
upstream: { ...(baseUrl ? { baseUrl } : {}), model: text(upstreamRaw.model) || model, ...(apiKey ? { apiKey } : {}), apiKeyEnv, mock, timeoutMs },
|
|
218
|
+
terms,
|
|
219
|
+
paused: pausedCurrencies.includes(currency),
|
|
220
|
+
pausedCurrencies,
|
|
221
|
+
refundAccountsPerDay,
|
|
222
|
+
appUrl: appUrl ?? DEFAULT_APP_URL,
|
|
223
|
+
listingCapabilities,
|
|
224
|
+
...(systemPrompt ? { systemPrompt } : {}),
|
|
225
|
+
rpcUrl,
|
|
226
|
+
...(genesisHash ? { genesisHash } : {}),
|
|
227
|
+
lockBoundDelegations: file.lockBoundDelegations === true,
|
|
228
|
+
...(text(env.RAP_PROVIDER_KEYPAIR_PATH) || text(file.keypairPath) ? { keypairPath: text(env.RAP_PROVIDER_KEYPAIR_PATH) || text(file.keypairPath) } : {}),
|
|
229
|
+
replayFile: text(file.replayFile) || DEFAULT_REPLAY_FILE,
|
|
230
|
+
sessions: { enabled: sessionsEnabled, idleMs: idleSeconds * 1_000, file: text(sessionsRaw?.file) || DEFAULT_SESSION_FILE },
|
|
231
|
+
port,
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** A starting config for `rap-provider init`. Mock upstream, devnet, USDC. */
|
|
236
|
+
export function exampleConfig(wallet) {
|
|
237
|
+
return {
|
|
238
|
+
name: "My provider",
|
|
239
|
+
description: "Describe what this provider is good at.",
|
|
240
|
+
network: "solana-devnet",
|
|
241
|
+
wallet,
|
|
242
|
+
publicUrl: `http://localhost:${DEFAULT_PORT}`,
|
|
243
|
+
model: "openai/gpt-4o-mini",
|
|
244
|
+
upstream: { baseUrl: "https://openrouter.ai/api/v1", apiKeyEnv: "UPSTREAM_API_KEY", mock: true },
|
|
245
|
+
price: { currency: "USDC", inputPerMillion: "0.15", outputPerMillion: "0.60", maxOutputTokens: 1000 },
|
|
246
|
+
keypairPath: "~/.config/solana/id.json",
|
|
247
|
+
};
|
|
248
|
+
}
|