@redditech/provider-kit 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Dockerfile +33 -0
- package/LICENSE +21 -0
- package/README.md +213 -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 +167 -0
- package/dist/src/config.js +250 -0
- package/dist/src/doctor.d.ts +38 -0
- package/dist/src/doctor.js +167 -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
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from "./config.js";
|
|
2
|
+
export * from "./upstream.js";
|
|
3
|
+
export * from "./replay.js";
|
|
4
|
+
export * from "./sessions.js";
|
|
5
|
+
export * from "./keys.js";
|
|
6
|
+
export * from "./chain.js";
|
|
7
|
+
export * from "./handler.js";
|
|
8
|
+
export * from "./doctor.js";
|
|
9
|
+
export * from "./server.js";
|
|
10
|
+
export * from "./adl.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from "./config.js";
|
|
2
|
+
export * from "./upstream.js";
|
|
3
|
+
export * from "./replay.js";
|
|
4
|
+
export * from "./sessions.js";
|
|
5
|
+
export * from "./keys.js";
|
|
6
|
+
export * from "./chain.js";
|
|
7
|
+
export * from "./handler.js";
|
|
8
|
+
export * from "./doctor.js";
|
|
9
|
+
export * from "./server.js";
|
|
10
|
+
export * from "./adl.js";
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Keypair } from "@solana/web3.js";
|
|
2
|
+
export interface ProviderKey {
|
|
3
|
+
/** Signs transactions. Hold it only inside the chain adapter. */
|
|
4
|
+
keypair: Keypair;
|
|
5
|
+
/** Ed25519 signature over a message, for receipts. */
|
|
6
|
+
signMessage(message: Uint8Array): Uint8Array;
|
|
7
|
+
}
|
|
8
|
+
export type ProviderKeyResult = {
|
|
9
|
+
ok: true;
|
|
10
|
+
key: ProviderKey;
|
|
11
|
+
} | {
|
|
12
|
+
ok: false;
|
|
13
|
+
message: string;
|
|
14
|
+
};
|
|
15
|
+
export declare function expandHome(path: string): string;
|
|
16
|
+
export declare function loadProviderKey(input: {
|
|
17
|
+
keypairPath: string | undefined;
|
|
18
|
+
wallet: string;
|
|
19
|
+
readFile?: (path: string) => string;
|
|
20
|
+
fileMode?: (path: string) => number;
|
|
21
|
+
}): ProviderKeyResult;
|
package/dist/src/keys.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider wallet's key. It signs two things: the settle transaction that
|
|
3
|
+
* collects a call's payment, and the receipt the buyer gets.
|
|
4
|
+
*
|
|
5
|
+
* The key is read once at start from a Solana keypair file (the JSON array of
|
|
6
|
+
* 64 numbers `solana-keygen` writes). It is never taken from the config file,
|
|
7
|
+
* logged or returned, and a file other users can read is refused.
|
|
8
|
+
*/
|
|
9
|
+
import { createPrivateKey, sign as edSign } from "node:crypto";
|
|
10
|
+
import { readFileSync, statSync } from "node:fs";
|
|
11
|
+
import { homedir } from "node:os";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { Keypair } from "@solana/web3.js";
|
|
14
|
+
const PKCS8_ED25519_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
|
|
15
|
+
export function expandHome(path) {
|
|
16
|
+
return path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
|
|
17
|
+
}
|
|
18
|
+
export function loadProviderKey(input) {
|
|
19
|
+
const raw = input.keypairPath?.trim();
|
|
20
|
+
if (!raw)
|
|
21
|
+
return { ok: false, message: "no key file is configured: set keypairPath in the config or RAP_PROVIDER_KEYPAIR_PATH" };
|
|
22
|
+
const path = expandHome(raw);
|
|
23
|
+
let bytes;
|
|
24
|
+
try {
|
|
25
|
+
const mode = (input.fileMode ?? ((p) => statSync(p).mode))(path);
|
|
26
|
+
if ((mode & 0o077) !== 0)
|
|
27
|
+
return { ok: false, message: "the key file must not be readable by group or others (run: chmod 600 on it)" };
|
|
28
|
+
const parsed = JSON.parse((input.readFile ?? ((p) => readFileSync(p, "utf8")))(path));
|
|
29
|
+
if (!Array.isArray(parsed) || parsed.length !== 64 || !parsed.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {
|
|
30
|
+
return { ok: false, message: "the key file is not a 64-byte Solana keypair" };
|
|
31
|
+
}
|
|
32
|
+
bytes = parsed;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// The error is not echoed: it could carry file contents.
|
|
36
|
+
return { ok: false, message: "the key file could not be read" };
|
|
37
|
+
}
|
|
38
|
+
let keypair;
|
|
39
|
+
try {
|
|
40
|
+
// Refuses a file whose public half does not belong to its secret half.
|
|
41
|
+
keypair = Keypair.fromSecretKey(Uint8Array.from(bytes));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return { ok: false, message: "the key file is not a valid Solana keypair" };
|
|
45
|
+
}
|
|
46
|
+
finally {
|
|
47
|
+
bytes.fill(0);
|
|
48
|
+
}
|
|
49
|
+
if (keypair.publicKey.toBase58() !== input.wallet)
|
|
50
|
+
return { ok: false, message: "the key file does not belong to the wallet in the config" };
|
|
51
|
+
const privateKey = createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from(keypair.secretKey.subarray(0, 32))]), format: "der", type: "pkcs8" });
|
|
52
|
+
return { ok: true, key: { keypair, signMessage: (message) => edSign(null, message, privateKey) } };
|
|
53
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ProviderConfig } from "./config.js";
|
|
2
|
+
/** The same statement the app's own wallet sign-in shows. */
|
|
3
|
+
export declare const SIGN_IN_STATEMENT = "Sign in to Reddi Agent Protocol. This proves you own this wallet. It does not move funds or approve any transaction.";
|
|
4
|
+
export type ListingFetch = (url: string, init: {
|
|
5
|
+
method: string;
|
|
6
|
+
headers?: Record<string, string>;
|
|
7
|
+
body?: string;
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
}) => Promise<{
|
|
10
|
+
ok: boolean;
|
|
11
|
+
status: number;
|
|
12
|
+
json(): Promise<unknown>;
|
|
13
|
+
}>;
|
|
14
|
+
export type ListingResult<T> = ({
|
|
15
|
+
ok: true;
|
|
16
|
+
} & T) | {
|
|
17
|
+
ok: false;
|
|
18
|
+
message: string;
|
|
19
|
+
};
|
|
20
|
+
export interface ListingBody {
|
|
21
|
+
displayName: string;
|
|
22
|
+
endpointUrl: string;
|
|
23
|
+
declaredModels: string[];
|
|
24
|
+
capabilities: Record<string, unknown>;
|
|
25
|
+
priceInputPerMillionBaseUnits: string;
|
|
26
|
+
priceOutputPerMillionBaseUnits: string;
|
|
27
|
+
priceMint: string;
|
|
28
|
+
status: "listed" | "paused";
|
|
29
|
+
/** The provider's ADL v0.3 document as YAML. The app refuses a listing it does not match. */
|
|
30
|
+
adl: string;
|
|
31
|
+
}
|
|
32
|
+
/** What the app calls this provider's network. */
|
|
33
|
+
export declare const appNetwork: (network: ProviderConfig["network"]) => "solana-devnet" | "solana-mainnet";
|
|
34
|
+
/** The listing this config describes. Paused while the price currency is paused, so buyers are not sent to a provider that will refuse them. */
|
|
35
|
+
export declare function listingBody(config: ProviderConfig): ListingResult<{
|
|
36
|
+
body: ListingBody;
|
|
37
|
+
}>;
|
|
38
|
+
/** The sign-in message, in the form the auth service checks. */
|
|
39
|
+
export declare function signInMessage(appUrl: string, wallet: string, issuedAt: Date): string;
|
|
40
|
+
export interface ListingClientInput {
|
|
41
|
+
/** Defaults to the config's app. */
|
|
42
|
+
appUrl?: string;
|
|
43
|
+
config: ProviderConfig;
|
|
44
|
+
signMessage: (message: Uint8Array) => Uint8Array | Promise<Uint8Array>;
|
|
45
|
+
fetchImpl?: ListingFetch;
|
|
46
|
+
now?: () => Date;
|
|
47
|
+
}
|
|
48
|
+
/** The app's listings, after checking the app serves this provider's network. */
|
|
49
|
+
export declare function readListings(input: Pick<ListingClientInput, "appUrl" | "config" | "fetchImpl">): Promise<ListingResult<{
|
|
50
|
+
listing: Record<string, unknown> | null;
|
|
51
|
+
}>>;
|
|
52
|
+
/** Signs in with the provider wallet and creates or updates its listing. */
|
|
53
|
+
export declare function publishListing(input: ListingClientInput & {
|
|
54
|
+
body: ListingBody;
|
|
55
|
+
}): Promise<ListingResult<{
|
|
56
|
+
listing: Record<string, unknown>;
|
|
57
|
+
}>>;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider's listing in the app: sign in with the provider wallet, then
|
|
3
|
+
* create or update the wallet's own listing. Three hosts are contacted, all
|
|
4
|
+
* named by the app the operator chose: the app, and the auth service the app
|
|
5
|
+
* says it uses. The wallet key signs one sign-in message and nothing else.
|
|
6
|
+
*/
|
|
7
|
+
import { decimalToBaseUnits, directPaymentCurrency } from "@redditech/x402-solana";
|
|
8
|
+
import { providerAdlText } from "./adl.js";
|
|
9
|
+
/** The same statement the app's own wallet sign-in shows. */
|
|
10
|
+
export const SIGN_IN_STATEMENT = "Sign in to Reddi Agent Protocol. This proves you own this wallet. It does not move funds or approve any transaction.";
|
|
11
|
+
/** What the app calls this provider's network. */
|
|
12
|
+
export const appNetwork = (network) => (network === "solana-mainnet-beta" ? "solana-mainnet" : "solana-devnet");
|
|
13
|
+
/** The listing this config describes. Paused while the price currency is paused, so buyers are not sent to a provider that will refuse them. */
|
|
14
|
+
export function listingBody(config) {
|
|
15
|
+
const { terms } = config;
|
|
16
|
+
const url = new URL(config.publicUrl);
|
|
17
|
+
if (url.protocol !== "https:" || !url.hostname.includes("."))
|
|
18
|
+
return { ok: false, message: "publicUrl must be a public https address before you list. Buyers and the app's health check call it." };
|
|
19
|
+
const decimals = directPaymentCurrency(terms.price.currency).decimals;
|
|
20
|
+
// The app stores whole base units per million tokens.
|
|
21
|
+
const input = decimalToBaseUnits(terms.price.inputPerMillion, decimals);
|
|
22
|
+
const output = decimalToBaseUnits(terms.price.outputPerMillion, decimals);
|
|
23
|
+
if (input === undefined || output === undefined || input === null || output === null)
|
|
24
|
+
return { ok: false, message: "price: could not be expressed in base units per million tokens." };
|
|
25
|
+
const adl = providerAdlText(config);
|
|
26
|
+
if (adl.report.status !== "pass")
|
|
27
|
+
return { ok: false, message: `The provider's ADL document does not pass Level 3: ${[...adl.report.schemaDiagnostics.map((d) => `${d.path}: ${d.message}`), ...Object.values(adl.report.missingFieldsByLevel).flat()].join("; ")}` };
|
|
28
|
+
return {
|
|
29
|
+
ok: true,
|
|
30
|
+
body: {
|
|
31
|
+
displayName: config.name,
|
|
32
|
+
endpointUrl: config.publicUrl,
|
|
33
|
+
declaredModels: [config.model],
|
|
34
|
+
capabilities: config.listingCapabilities,
|
|
35
|
+
priceInputPerMillionBaseUnits: input.toString(),
|
|
36
|
+
priceOutputPerMillionBaseUnits: output.toString(),
|
|
37
|
+
priceMint: terms.mint.toBase58(),
|
|
38
|
+
status: config.paused ? "paused" : "listed",
|
|
39
|
+
adl: adl.text,
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** The sign-in message, in the form the auth service checks. */
|
|
44
|
+
export function signInMessage(appUrl, wallet, issuedAt) {
|
|
45
|
+
const url = new URL(appUrl);
|
|
46
|
+
return [`${url.host} wants you to sign in with your Solana account:`, wallet, "", SIGN_IN_STATEMENT, "", "Version: 1", `URI: ${url.href}`, `Issued At: ${issuedAt.toISOString()}`].join("\n");
|
|
47
|
+
}
|
|
48
|
+
const record = (value) => (value && typeof value === "object" && !Array.isArray(value) ? value : {});
|
|
49
|
+
const errorText = (body, fallback) => {
|
|
50
|
+
const error = record(record(body).error);
|
|
51
|
+
return typeof error.message === "string" ? error.message : typeof record(body).msg === "string" ? String(record(body).msg) : fallback;
|
|
52
|
+
};
|
|
53
|
+
async function call(fetchImpl, url, init) {
|
|
54
|
+
try {
|
|
55
|
+
const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(15_000) });
|
|
56
|
+
return { ok: response.ok, status: response.status, body: await response.json().catch(() => null) };
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** The app's listings, after checking the app serves this provider's network. */
|
|
63
|
+
export async function readListings(input) {
|
|
64
|
+
const fetchImpl = input.fetchImpl ?? fetch;
|
|
65
|
+
const appUrl = input.appUrl ?? input.config.appUrl;
|
|
66
|
+
const response = await call(fetchImpl, `${appUrl}/api/listings`, { method: "GET" });
|
|
67
|
+
if (!response)
|
|
68
|
+
return { ok: false, message: `${appUrl} could not be reached.` };
|
|
69
|
+
const body = record(response.body);
|
|
70
|
+
if (!response.ok || body.ok !== true)
|
|
71
|
+
return { ok: false, message: errorText(response.body, `${appUrl}/api/listings answered with status ${response.status}.`) };
|
|
72
|
+
if (body.network !== appNetwork(input.config.network))
|
|
73
|
+
return { ok: false, message: `${appUrl} lists ${String(body.network)} providers, and this provider is on ${input.config.network}. Nothing was sent.` };
|
|
74
|
+
const listings = Array.isArray(body.listings) ? body.listings : [];
|
|
75
|
+
const mine = listings.map(record).find((entry) => entry.wallet === input.config.wallet);
|
|
76
|
+
return { ok: true, listing: mine ?? null };
|
|
77
|
+
}
|
|
78
|
+
/** Signs in with the provider wallet and creates or updates its listing. */
|
|
79
|
+
export async function publishListing(input) {
|
|
80
|
+
const fetchImpl = input.fetchImpl ?? fetch;
|
|
81
|
+
const { config } = input;
|
|
82
|
+
const appUrl = input.appUrl ?? config.appUrl;
|
|
83
|
+
const network = await readListings(input);
|
|
84
|
+
if (!network.ok)
|
|
85
|
+
return network;
|
|
86
|
+
const auth = await call(fetchImpl, `${appUrl}/api/auth/config`, { method: "GET" });
|
|
87
|
+
const authBody = record(auth?.body);
|
|
88
|
+
if (!auth?.ok || typeof authBody.authUrl !== "string" || typeof authBody.publishableKey !== "string")
|
|
89
|
+
return { ok: false, message: errorText(auth?.body, `${appUrl} did not say where to sign in.`) };
|
|
90
|
+
let authUrl;
|
|
91
|
+
try {
|
|
92
|
+
authUrl = new URL(authBody.authUrl);
|
|
93
|
+
if (authUrl.protocol !== "https:")
|
|
94
|
+
throw new Error("protocol");
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return { ok: false, message: `${appUrl} named a sign-in address that is not https. Nothing was signed.` };
|
|
98
|
+
}
|
|
99
|
+
const message = signInMessage(appUrl, config.wallet, input.now?.() ?? new Date());
|
|
100
|
+
const signature = Buffer.from(await input.signMessage(new TextEncoder().encode(message))).toString("base64url");
|
|
101
|
+
const signedIn = await call(fetchImpl, `${authUrl.origin}/auth/v1/token?grant_type=web3`, {
|
|
102
|
+
method: "POST",
|
|
103
|
+
headers: { "content-type": "application/json", apikey: authBody.publishableKey },
|
|
104
|
+
body: JSON.stringify({ chain: "solana", message, signature }),
|
|
105
|
+
});
|
|
106
|
+
const token = record(signedIn?.body).access_token;
|
|
107
|
+
if (!signedIn?.ok || typeof token !== "string")
|
|
108
|
+
return { ok: false, message: `Wallet sign-in was refused: ${errorText(signedIn?.body, signedIn ? `status ${signedIn.status}` : "the sign-in service could not be reached")}.` };
|
|
109
|
+
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
|
|
110
|
+
const session = await call(fetchImpl, `${appUrl}/api/auth/session`, { method: "POST", headers });
|
|
111
|
+
if (!session?.ok || record(session.body).wallet !== config.wallet)
|
|
112
|
+
return { ok: false, message: errorText(session?.body, "The app did not confirm the sign-in for this wallet. Nothing was listed.") };
|
|
113
|
+
const saved = await call(fetchImpl, `${appUrl}/api/listings`, { method: "PUT", headers, body: JSON.stringify(input.body) });
|
|
114
|
+
if (!saved?.ok || record(saved.body).ok !== true)
|
|
115
|
+
return { ok: false, message: `The listing was refused: ${errorText(saved?.body, saved ? `status ${saved.status}` : "the app could not be reached")}.` };
|
|
116
|
+
return { ok: true, listing: record(record(saved.body).listing) };
|
|
117
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PendingSettle } from "@redditech/x402-solana";
|
|
2
|
+
export interface PendingCallSettle extends PendingSettle {
|
|
3
|
+
escrow: string;
|
|
4
|
+
/** SHA-256 of the request body the settle pays for: only the same request may collect the answer. */
|
|
5
|
+
requestHash: string;
|
|
6
|
+
/** `pending`: outcome not known. `landed`: it landed. `dropped`: it cannot land, and nothing was charged by it. */
|
|
7
|
+
status: "pending" | "landed" | "dropped";
|
|
8
|
+
}
|
|
9
|
+
export interface PendingSettleStore {
|
|
10
|
+
load(): PendingCallSettle[];
|
|
11
|
+
/** Durable before it returns. */
|
|
12
|
+
save(record: PendingCallSettle): void;
|
|
13
|
+
}
|
|
14
|
+
export declare class FilePendingSettleStore implements PendingSettleStore {
|
|
15
|
+
private readonly path;
|
|
16
|
+
private fd;
|
|
17
|
+
constructor(path: string);
|
|
18
|
+
load(): PendingCallSettle[];
|
|
19
|
+
save(record: PendingCallSettle): void;
|
|
20
|
+
close(): void;
|
|
21
|
+
}
|
|
22
|
+
/** An in-memory store, for tests and for a handler run without a file. */
|
|
23
|
+
export declare class MemoryPendingSettleStore implements PendingSettleStore {
|
|
24
|
+
readonly records: Map<string, PendingCallSettle>;
|
|
25
|
+
load(): PendingCallSettle[];
|
|
26
|
+
save(record: PendingCallSettle): void;
|
|
27
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps the settles of single calls that were sent but whose outcome was not
|
|
3
|
+
* known, one JSON line per change, so a restart can still find out whether
|
|
4
|
+
* each one landed. The last line for an escrow wins. Opened only by the process
|
|
5
|
+
* that holds the payment memory's lock (see replay.ts).
|
|
6
|
+
*/
|
|
7
|
+
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
const isRecord = (value) => {
|
|
10
|
+
const r = value;
|
|
11
|
+
return Boolean(r) && typeof r.escrow === "string" && typeof r.signature === "string" && typeof r.transaction === "string" && typeof r.status === "string" && typeof r.requestHash === "string";
|
|
12
|
+
};
|
|
13
|
+
export class FilePendingSettleStore {
|
|
14
|
+
path;
|
|
15
|
+
fd;
|
|
16
|
+
constructor(path) {
|
|
17
|
+
this.path = path;
|
|
18
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
19
|
+
this.fd = openSync(path, "a", 0o600);
|
|
20
|
+
}
|
|
21
|
+
load() {
|
|
22
|
+
const latest = new Map();
|
|
23
|
+
if (!existsSync(this.path))
|
|
24
|
+
return [];
|
|
25
|
+
for (const line of readFileSync(this.path, "utf8").split("\n")) {
|
|
26
|
+
if (!line.trim())
|
|
27
|
+
continue;
|
|
28
|
+
try {
|
|
29
|
+
const parsed = JSON.parse(line);
|
|
30
|
+
if (isRecord(parsed))
|
|
31
|
+
latest.set(parsed.escrow, parsed);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// A line cut short by a crash: the one before it for that escrow stands.
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return [...latest.values()];
|
|
38
|
+
}
|
|
39
|
+
save(record) {
|
|
40
|
+
if (this.fd === undefined)
|
|
41
|
+
throw new Error("pending settle store is closed");
|
|
42
|
+
appendFileSync(this.fd, `${JSON.stringify(record)}\n`);
|
|
43
|
+
fsyncSync(this.fd);
|
|
44
|
+
}
|
|
45
|
+
close() {
|
|
46
|
+
if (this.fd === undefined)
|
|
47
|
+
return;
|
|
48
|
+
closeSync(this.fd);
|
|
49
|
+
this.fd = undefined;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** An in-memory store, for tests and for a handler run without a file. */
|
|
53
|
+
export class MemoryPendingSettleStore {
|
|
54
|
+
records = new Map();
|
|
55
|
+
load() {
|
|
56
|
+
return [...this.records.values()];
|
|
57
|
+
}
|
|
58
|
+
save(record) {
|
|
59
|
+
this.records.set(record.escrow, { ...record });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The on-chain registry record of a provider: one per owner wallet, at
|
|
3
|
+
* [b"agent", owner] under the V1 program. Registering burns the registration
|
|
4
|
+
* fee and pays the record's rent. Mirrors `register_agent` in
|
|
5
|
+
* programs/pinocchio-escrow/program/src/instructions/registry.rs.
|
|
6
|
+
*/
|
|
7
|
+
import { PublicKey, TransactionInstruction } from "@solana/web3.js";
|
|
8
|
+
/** sha256("global:register_agent")[0..8]. A test recomputes it. */
|
|
9
|
+
export declare const REGISTER_AGENT_DISCRIMINATOR: Uint8Array<ArrayBuffer>;
|
|
10
|
+
/** Burned on registration: 0.01 SOL. */
|
|
11
|
+
export declare const AGENT_REGISTRATION_FEE_LAMPORTS = 10000000n;
|
|
12
|
+
export declare const AGENT_FEE_BURN_ADDRESS: PublicKey;
|
|
13
|
+
export declare const AGENT_MODEL_MAX_BYTES = 64;
|
|
14
|
+
export declare function agentAddress(programId: PublicKey, owner: PublicKey): PublicKey;
|
|
15
|
+
/**
|
|
16
|
+
* `register_agent` for a primary (serving) provider. The registry's own price
|
|
17
|
+
* field is in lamports per call and is left at zero: a kit provider is priced
|
|
18
|
+
* per token in its listing.
|
|
19
|
+
*/
|
|
20
|
+
export declare function buildRegisterAgentInstruction(programId: PublicKey, owner: PublicKey, model: string): TransactionInstruction;
|
|
21
|
+
/** The owner and model of a registry record, or undefined when the data is not one. */
|
|
22
|
+
export declare function readAgentRecord(data: Uint8Array): {
|
|
23
|
+
owner: PublicKey;
|
|
24
|
+
model: string;
|
|
25
|
+
} | undefined;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The on-chain registry record of a provider: one per owner wallet, at
|
|
3
|
+
* [b"agent", owner] under the V1 program. Registering burns the registration
|
|
4
|
+
* fee and pays the record's rent. Mirrors `register_agent` in
|
|
5
|
+
* programs/pinocchio-escrow/program/src/instructions/registry.rs.
|
|
6
|
+
*/
|
|
7
|
+
import { PublicKey, SystemProgram, TransactionInstruction } from "@solana/web3.js";
|
|
8
|
+
/** sha256("global:register_agent")[0..8]. A test recomputes it. */
|
|
9
|
+
export const REGISTER_AGENT_DISCRIMINATOR = Uint8Array.of(135, 157, 66, 195, 2, 113, 175, 30);
|
|
10
|
+
/** Burned on registration: 0.01 SOL. */
|
|
11
|
+
export const AGENT_REGISTRATION_FEE_LAMPORTS = 10000000n;
|
|
12
|
+
export const AGENT_FEE_BURN_ADDRESS = new PublicKey("1nc1nerator11111111111111111111111111111111");
|
|
13
|
+
export const AGENT_MODEL_MAX_BYTES = 64;
|
|
14
|
+
export function agentAddress(programId, owner) {
|
|
15
|
+
return PublicKey.findProgramAddressSync([Buffer.from("agent"), owner.toBuffer()], programId)[0];
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* `register_agent` for a primary (serving) provider. The registry's own price
|
|
19
|
+
* field is in lamports per call and is left at zero: a kit provider is priced
|
|
20
|
+
* per token in its listing.
|
|
21
|
+
*/
|
|
22
|
+
export function buildRegisterAgentInstruction(programId, owner, model) {
|
|
23
|
+
const modelBytes = Buffer.from(model, "utf8");
|
|
24
|
+
if (modelBytes.length === 0 || modelBytes.length > AGENT_MODEL_MAX_BYTES)
|
|
25
|
+
throw new Error(`the registry holds a model name of at most ${AGENT_MODEL_MAX_BYTES} bytes`);
|
|
26
|
+
const data = Buffer.alloc(8 + 1 + 4 + modelBytes.length + 8 + 1);
|
|
27
|
+
Buffer.from(REGISTER_AGENT_DISCRIMINATOR).copy(data, 0);
|
|
28
|
+
data.writeUInt8(0, 8); // primary
|
|
29
|
+
data.writeUInt32LE(modelBytes.length, 9);
|
|
30
|
+
modelBytes.copy(data, 13);
|
|
31
|
+
// rate_lamports (u64) and min_reputation (u8) stay zero.
|
|
32
|
+
return new TransactionInstruction({
|
|
33
|
+
programId,
|
|
34
|
+
data,
|
|
35
|
+
keys: [
|
|
36
|
+
{ pubkey: agentAddress(programId, owner), isWritable: true, isSigner: false },
|
|
37
|
+
{ pubkey: owner, isWritable: true, isSigner: true },
|
|
38
|
+
{ pubkey: AGENT_FEE_BURN_ADDRESS, isWritable: true, isSigner: false },
|
|
39
|
+
{ pubkey: SystemProgram.programId, isWritable: false, isSigner: false },
|
|
40
|
+
],
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/** The owner and model of a registry record, or undefined when the data is not one. */
|
|
44
|
+
export function readAgentRecord(data) {
|
|
45
|
+
const buffer = Buffer.from(data);
|
|
46
|
+
if (buffer.length < 8 + 32 + 1 + 4)
|
|
47
|
+
return undefined;
|
|
48
|
+
const length = buffer.readUInt32LE(41);
|
|
49
|
+
if (length > AGENT_MODEL_MAX_BYTES || 45 + length > buffer.length)
|
|
50
|
+
return undefined;
|
|
51
|
+
return { owner: new PublicKey(buffer.subarray(8, 40)), model: buffer.subarray(45, 45 + length).toString("utf8") };
|
|
52
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { NonceReplayStore } from "@redditech/x402-solana";
|
|
2
|
+
export declare class FileReplayStore implements NonceReplayStore {
|
|
3
|
+
private readonly path;
|
|
4
|
+
private readonly seen;
|
|
5
|
+
private fd;
|
|
6
|
+
private readonly lockPath;
|
|
7
|
+
constructor(path: string);
|
|
8
|
+
private takeLock;
|
|
9
|
+
private releaseLock;
|
|
10
|
+
/** True the first time a key is seen. The key is on disk before this returns true. */
|
|
11
|
+
checkAndStore(key: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Records every key or none, in one write: true when all were new and are now
|
|
14
|
+
* on disk, false when any was already present (nothing is written then).
|
|
15
|
+
*/
|
|
16
|
+
checkAndStoreAll(keys: string[]): boolean;
|
|
17
|
+
get size(): number;
|
|
18
|
+
close(): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Remembers which escrows have already paid for a call, in a file, so the
|
|
3
|
+
* memory survives a restart. One lock pays for one call.
|
|
4
|
+
*
|
|
5
|
+
* This is for a single provider process. Two processes must not share a file:
|
|
6
|
+
* the second refuses to open it. A provider that runs several instances needs
|
|
7
|
+
* a shared database store instead (`DatabaseReplayStore` in the SDK).
|
|
8
|
+
*/
|
|
9
|
+
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { dirname } from "node:path";
|
|
11
|
+
const KEY = /^[\x21-\x7e]{1,200}$/;
|
|
12
|
+
function processAlive(pid) {
|
|
13
|
+
try {
|
|
14
|
+
process.kill(pid, 0);
|
|
15
|
+
return true;
|
|
16
|
+
}
|
|
17
|
+
catch (error) {
|
|
18
|
+
return error.code === "EPERM";
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class FileReplayStore {
|
|
22
|
+
path;
|
|
23
|
+
seen = new Set();
|
|
24
|
+
fd;
|
|
25
|
+
lockPath;
|
|
26
|
+
constructor(path) {
|
|
27
|
+
this.path = path;
|
|
28
|
+
this.lockPath = `${path}.lock`;
|
|
29
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
30
|
+
this.takeLock();
|
|
31
|
+
try {
|
|
32
|
+
if (existsSync(path)) {
|
|
33
|
+
for (const line of readFileSync(path, "utf8").split("\n")) {
|
|
34
|
+
if (KEY.test(line))
|
|
35
|
+
this.seen.add(line);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
this.fd = openSync(path, "a", 0o600);
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
this.releaseLock();
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
takeLock() {
|
|
46
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
47
|
+
try {
|
|
48
|
+
writeFileSync(this.lockPath, String(process.pid), { flag: "wx", mode: 0o600 });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error.code !== "EEXIST")
|
|
53
|
+
throw error;
|
|
54
|
+
const owner = Number.parseInt(readFileSync(this.lockPath, "utf8"), 10);
|
|
55
|
+
if (Number.isSafeInteger(owner) && owner > 0 && owner !== process.pid && processAlive(owner)) {
|
|
56
|
+
throw new Error(`another provider process (pid ${owner}) is using ${this.path}`);
|
|
57
|
+
}
|
|
58
|
+
// The process that held the lock is gone.
|
|
59
|
+
unlinkSync(this.lockPath);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
throw new Error(`could not lock ${this.path}`);
|
|
63
|
+
}
|
|
64
|
+
releaseLock() {
|
|
65
|
+
try {
|
|
66
|
+
unlinkSync(this.lockPath);
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
// Already gone.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** True the first time a key is seen. The key is on disk before this returns true. */
|
|
73
|
+
checkAndStore(key) {
|
|
74
|
+
if (this.fd === undefined)
|
|
75
|
+
throw new Error("replay store is closed");
|
|
76
|
+
if (!KEY.test(key))
|
|
77
|
+
throw new Error("replay key must be printable text without spaces");
|
|
78
|
+
if (this.seen.has(key))
|
|
79
|
+
return false;
|
|
80
|
+
appendFileSync(this.fd, `${key}\n`);
|
|
81
|
+
fsyncSync(this.fd);
|
|
82
|
+
this.seen.add(key);
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Records every key or none, in one write: true when all were new and are now
|
|
87
|
+
* on disk, false when any was already present (nothing is written then).
|
|
88
|
+
*/
|
|
89
|
+
checkAndStoreAll(keys) {
|
|
90
|
+
if (this.fd === undefined)
|
|
91
|
+
throw new Error("replay store is closed");
|
|
92
|
+
if (!Array.isArray(keys) || keys.length === 0)
|
|
93
|
+
throw new Error("at least one replay key is required");
|
|
94
|
+
if (keys.some((key) => !KEY.test(key)))
|
|
95
|
+
throw new Error("replay key must be printable text without spaces");
|
|
96
|
+
if (new Set(keys).size !== keys.length)
|
|
97
|
+
throw new Error("replay keys must be distinct");
|
|
98
|
+
if (keys.some((key) => this.seen.has(key)))
|
|
99
|
+
return false;
|
|
100
|
+
appendFileSync(this.fd, keys.map((key) => `${key}\n`).join(""));
|
|
101
|
+
fsyncSync(this.fd);
|
|
102
|
+
for (const key of keys)
|
|
103
|
+
this.seen.add(key);
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
get size() {
|
|
107
|
+
return this.seen.size;
|
|
108
|
+
}
|
|
109
|
+
close() {
|
|
110
|
+
if (this.fd === undefined)
|
|
111
|
+
return;
|
|
112
|
+
closeSync(this.fd);
|
|
113
|
+
this.fd = undefined;
|
|
114
|
+
this.releaseLock();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Starts the provider: loads the key, opens the payment memory, and serves the handler over HTTP. */
|
|
2
|
+
import { type Server } from "node:http";
|
|
3
|
+
import { type ProviderChain } from "./chain.js";
|
|
4
|
+
import type { ProviderConfig } from "./config.js";
|
|
5
|
+
import { type Upstream } from "./upstream.js";
|
|
6
|
+
/** How often sessions are checked for an idle timeout or a refund window that is about to open. */
|
|
7
|
+
export declare const SESSION_SWEEP_MS = 30000;
|
|
8
|
+
export type StartResult = {
|
|
9
|
+
ok: true;
|
|
10
|
+
server: Server;
|
|
11
|
+
close: () => Promise<void>;
|
|
12
|
+
} | {
|
|
13
|
+
ok: false;
|
|
14
|
+
message: string;
|
|
15
|
+
};
|
|
16
|
+
/** Serves a fetch-style handler on a Node HTTP server. */
|
|
17
|
+
export declare function serve(handler: (request: Request) => Promise<Response>, origin: string): Server;
|
|
18
|
+
export declare function upstreamFor(config: ProviderConfig): Upstream;
|
|
19
|
+
/**
|
|
20
|
+
* Refuses to start, rather than start half-working, when the key is missing or
|
|
21
|
+
* wrong, when mock answers would be sold on mainnet, or when the payment
|
|
22
|
+
* memory is in use by another process.
|
|
23
|
+
*/
|
|
24
|
+
export declare function startProvider(config: ProviderConfig, options?: {
|
|
25
|
+
log?: (event: Record<string, unknown>) => void;
|
|
26
|
+
chain?: ProviderChain;
|
|
27
|
+
host?: string;
|
|
28
|
+
}): Promise<StartResult>;
|