@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
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/** Starts the provider: loads the key, opens the payment memory, and serves the handler over HTTP. */
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { Readable } from "node:stream";
|
|
4
|
+
import { createProviderChain } from "./chain.js";
|
|
5
|
+
import { createProviderHandler } from "./handler.js";
|
|
6
|
+
import { loadProviderKey } from "./keys.js";
|
|
7
|
+
import { FileReplayStore } from "./replay.js";
|
|
8
|
+
import { FileSessionStore } from "./sessions.js";
|
|
9
|
+
import { FilePendingSettleStore } from "./pending.js";
|
|
10
|
+
import { dirname, join } from "node:path";
|
|
11
|
+
import { MeteredSessionLedger } from "@redditech/x402-solana";
|
|
12
|
+
import { createMockUpstream, createOpenAiCompatibleUpstream } from "./upstream.js";
|
|
13
|
+
/** How often sessions are checked for an idle timeout or a refund window that is about to open. */
|
|
14
|
+
export const SESSION_SWEEP_MS = 30_000;
|
|
15
|
+
/** Serves a fetch-style handler on a Node HTTP server. */
|
|
16
|
+
export function serve(handler, origin) {
|
|
17
|
+
return createServer(async (req, res) => {
|
|
18
|
+
try {
|
|
19
|
+
const request = new Request(new URL(req.url ?? "/", origin), {
|
|
20
|
+
method: req.method,
|
|
21
|
+
headers: req.headers,
|
|
22
|
+
body: req.method === "GET" || req.method === "HEAD" ? undefined : Readable.toWeb(req),
|
|
23
|
+
duplex: "half",
|
|
24
|
+
});
|
|
25
|
+
const response = await handler(request);
|
|
26
|
+
res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
|
|
27
|
+
res.end(await response.text());
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
31
|
+
res.end(JSON.stringify({ error: { code: "internal_error", message: "The provider hit an unexpected error." } }));
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
export function upstreamFor(config) {
|
|
36
|
+
return config.upstream.mock || !config.upstream.baseUrl
|
|
37
|
+
? createMockUpstream()
|
|
38
|
+
: createOpenAiCompatibleUpstream({ baseUrl: config.upstream.baseUrl, apiKey: config.upstream.apiKey, timeoutMs: config.upstream.timeoutMs });
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Refuses to start, rather than start half-working, when the key is missing or
|
|
42
|
+
* wrong, when mock answers would be sold on mainnet, or when the payment
|
|
43
|
+
* memory is in use by another process.
|
|
44
|
+
*/
|
|
45
|
+
export async function startProvider(config, options = {}) {
|
|
46
|
+
const key = loadProviderKey({ keypairPath: config.keypairPath, wallet: config.wallet });
|
|
47
|
+
if (!key.ok)
|
|
48
|
+
return { ok: false, message: key.message };
|
|
49
|
+
if (config.upstream.mock && config.network === "solana-mainnet-beta")
|
|
50
|
+
return { ok: false, message: "mock answers cannot be sold on mainnet: set upstream.mock to false" };
|
|
51
|
+
let replayStore;
|
|
52
|
+
try {
|
|
53
|
+
replayStore = new FileReplayStore(config.replayFile);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
return { ok: false, message: error instanceof Error ? error.message : "the payment memory file could not be opened" };
|
|
57
|
+
}
|
|
58
|
+
// Settles sent but not yet known to land are kept beside the payment memory, under the same lock.
|
|
59
|
+
let pendingSettles;
|
|
60
|
+
try {
|
|
61
|
+
pendingSettles = new FilePendingSettleStore(join(dirname(config.replayFile), "pending-settles.jsonl"));
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
replayStore.close();
|
|
65
|
+
return { ok: false, message: error instanceof Error ? `pending settles: ${error.message}` : "the pending settle file could not be opened" };
|
|
66
|
+
}
|
|
67
|
+
// Sessions are kept beside the payment memory, whose lock already keeps a second process out.
|
|
68
|
+
let sessionStore;
|
|
69
|
+
let sessions;
|
|
70
|
+
if (config.sessions.enabled) {
|
|
71
|
+
try {
|
|
72
|
+
sessionStore = new FileSessionStore(config.sessions.file);
|
|
73
|
+
sessions = new MeteredSessionLedger(config.terms, sessionStore);
|
|
74
|
+
const restored = await sessions.restore();
|
|
75
|
+
if (restored > 0)
|
|
76
|
+
options.log?.({ event: "sessions_restored", count: restored });
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
sessionStore?.close();
|
|
80
|
+
pendingSettles.close();
|
|
81
|
+
replayStore.close();
|
|
82
|
+
return { ok: false, message: error instanceof Error ? `sessions: ${error.message}` : "the session file could not be opened" };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const chain = options.chain ?? createProviderChain(config.rpcUrl, key.key.keypair);
|
|
86
|
+
const handler = createProviderHandler(config, { chain, upstream: upstreamFor(config), replayStore, pendingSettles, ...(sessions ? { sessions } : {}), signMessage: key.key.signMessage, log: options.log });
|
|
87
|
+
const server = serve(handler, config.publicUrl);
|
|
88
|
+
// Settles idle sessions, closing ones, and any near its refund window, including those restored above,
|
|
89
|
+
// and looks again at single-call settles whose outcome was not known.
|
|
90
|
+
let sweeping = false;
|
|
91
|
+
const sweep = setInterval(() => {
|
|
92
|
+
if (sweeping)
|
|
93
|
+
return;
|
|
94
|
+
sweeping = true;
|
|
95
|
+
handler.settleDueSessions().catch(() => undefined).finally(() => {
|
|
96
|
+
sweeping = false;
|
|
97
|
+
});
|
|
98
|
+
}, SESSION_SWEEP_MS);
|
|
99
|
+
sweep.unref();
|
|
100
|
+
await new Promise((resolve, reject) => {
|
|
101
|
+
server.once("error", reject);
|
|
102
|
+
server.listen(config.port, options.host ?? "0.0.0.0", () => resolve());
|
|
103
|
+
}).catch((error) => {
|
|
104
|
+
clearInterval(sweep);
|
|
105
|
+
sessionStore?.close();
|
|
106
|
+
pendingSettles.close();
|
|
107
|
+
replayStore.close();
|
|
108
|
+
throw error;
|
|
109
|
+
});
|
|
110
|
+
return {
|
|
111
|
+
ok: true,
|
|
112
|
+
server,
|
|
113
|
+
close: () => new Promise((resolve) => {
|
|
114
|
+
clearInterval(sweep);
|
|
115
|
+
server.close(() => {
|
|
116
|
+
sessionStore?.close();
|
|
117
|
+
pendingSettles.close();
|
|
118
|
+
replayStore.close();
|
|
119
|
+
resolve();
|
|
120
|
+
});
|
|
121
|
+
}),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { SessionState, SessionStore } from "@redditech/x402-solana";
|
|
2
|
+
export declare class FileSessionStore implements SessionStore {
|
|
3
|
+
private readonly path;
|
|
4
|
+
private fd;
|
|
5
|
+
constructor(path: string);
|
|
6
|
+
load(): SessionState[];
|
|
7
|
+
/** On disk before it returns. */
|
|
8
|
+
save(state: SessionState): void;
|
|
9
|
+
close(): void;
|
|
10
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keeps sessions in a file, one JSON line per change, so a restart can go on
|
|
3
|
+
* with a session or settle it. The last line for an escrow wins. Opened only
|
|
4
|
+
* by the process that holds the payment memory's lock (see replay.ts), so two
|
|
5
|
+
* processes never share it.
|
|
6
|
+
*/
|
|
7
|
+
import { appendFileSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync } from "node:fs";
|
|
8
|
+
import { dirname } from "node:path";
|
|
9
|
+
const isState = (value) => {
|
|
10
|
+
const s = value;
|
|
11
|
+
return Boolean(s) && typeof s.escrow === "string" && typeof s.payer === "string" && typeof s.nonce === "string" && typeof s.maxBaseUnits === "string" && typeof s.sequence === "number" && typeof s.status === "string";
|
|
12
|
+
};
|
|
13
|
+
export class FileSessionStore {
|
|
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 (isState(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
|
+
/** On disk before it returns. */
|
|
40
|
+
save(state) {
|
|
41
|
+
if (this.fd === undefined)
|
|
42
|
+
throw new Error("session store is closed");
|
|
43
|
+
appendFileSync(this.fd, `${JSON.stringify(state)}\n`);
|
|
44
|
+
fsyncSync(this.fd);
|
|
45
|
+
}
|
|
46
|
+
close() {
|
|
47
|
+
if (this.fd === undefined)
|
|
48
|
+
return;
|
|
49
|
+
closeSync(this.fd);
|
|
50
|
+
this.fd = undefined;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The model behind the provider: any server that speaks the OpenAI chat
|
|
3
|
+
* completions API (OpenRouter, a hosted API, a local Ollama or vLLM).
|
|
4
|
+
*/
|
|
5
|
+
export interface UpstreamMessage {
|
|
6
|
+
role: string;
|
|
7
|
+
content: string;
|
|
8
|
+
}
|
|
9
|
+
export interface UpstreamRequest {
|
|
10
|
+
model: string;
|
|
11
|
+
messages: UpstreamMessage[];
|
|
12
|
+
temperature?: number;
|
|
13
|
+
max_tokens: number;
|
|
14
|
+
}
|
|
15
|
+
export interface Upstream {
|
|
16
|
+
/** Resolves with the upstream's JSON answer. Rejects when there is no usable answer. */
|
|
17
|
+
createChatCompletion(request: UpstreamRequest): Promise<Record<string, unknown>>;
|
|
18
|
+
}
|
|
19
|
+
type FetchLike = (url: string, init: {
|
|
20
|
+
method: string;
|
|
21
|
+
headers: Record<string, string>;
|
|
22
|
+
body: string;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
}) => Promise<{
|
|
25
|
+
ok: boolean;
|
|
26
|
+
status: number;
|
|
27
|
+
json(): Promise<unknown>;
|
|
28
|
+
}>;
|
|
29
|
+
export declare class UpstreamError extends Error {
|
|
30
|
+
constructor(message: string);
|
|
31
|
+
}
|
|
32
|
+
export declare function createOpenAiCompatibleUpstream(options: {
|
|
33
|
+
baseUrl: string;
|
|
34
|
+
apiKey?: string;
|
|
35
|
+
timeoutMs?: number;
|
|
36
|
+
fetchImpl?: FetchLike;
|
|
37
|
+
}): Upstream;
|
|
38
|
+
/** A canned answer with a usage report, for trying the payment flow without a model. */
|
|
39
|
+
export declare function createMockUpstream(): Upstream;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
export class UpstreamError extends Error {
|
|
2
|
+
constructor(message) {
|
|
3
|
+
super(message);
|
|
4
|
+
this.name = "UpstreamError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export function createOpenAiCompatibleUpstream(options) {
|
|
8
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
9
|
+
return {
|
|
10
|
+
async createChatCompletion(request) {
|
|
11
|
+
let response;
|
|
12
|
+
try {
|
|
13
|
+
response = await fetchImpl(`${options.baseUrl}/chat/completions`, {
|
|
14
|
+
method: "POST",
|
|
15
|
+
headers: { "content-type": "application/json", ...(options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {}) },
|
|
16
|
+
body: JSON.stringify({ ...request, stream: false }),
|
|
17
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 120_000),
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// The cause is not passed on: it can carry the request, key included.
|
|
22
|
+
throw new UpstreamError("the model could not be reached");
|
|
23
|
+
}
|
|
24
|
+
if (!response.ok)
|
|
25
|
+
throw new UpstreamError(`the model answered with status ${response.status}`);
|
|
26
|
+
let body;
|
|
27
|
+
try {
|
|
28
|
+
body = await response.json();
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new UpstreamError("the model's answer was not JSON");
|
|
32
|
+
}
|
|
33
|
+
const choices = body?.choices;
|
|
34
|
+
if (!body || typeof body !== "object" || !Array.isArray(choices) || choices.length === 0)
|
|
35
|
+
throw new UpstreamError("the model returned no answer");
|
|
36
|
+
return body;
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** A canned answer with a usage report, for trying the payment flow without a model. */
|
|
41
|
+
export function createMockUpstream() {
|
|
42
|
+
return {
|
|
43
|
+
async createChatCompletion(request) {
|
|
44
|
+
const last = [...request.messages].reverse().find((m) => m.role === "user")?.content ?? "";
|
|
45
|
+
const content = `Mock answer from ${request.model}. You said: ${last.slice(0, 200)}`;
|
|
46
|
+
const promptTokens = request.messages.reduce((total, m) => total + Math.ceil(m.content.length / 4), 0);
|
|
47
|
+
return {
|
|
48
|
+
id: "chatcmpl-mock",
|
|
49
|
+
object: "chat.completion",
|
|
50
|
+
model: request.model,
|
|
51
|
+
choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }],
|
|
52
|
+
usage: { prompt_tokens: promptTokens, completion_tokens: Math.min(request.max_tokens, Math.ceil(content.length / 4)), total_tokens: 0 },
|
|
53
|
+
};
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# RAP's own providers: a worked example
|
|
2
|
+
|
|
3
|
+
Two first-party providers run on this kit: the video scene and script writer (#846) and the humaniser. Their configs are here as an example of a real listing; their instructions are not. Each config points at a `*.prompt.private.txt` file kept on the host. Those files are ignored by git and left out of the npm package, so the house style rules are never published.
|
|
4
|
+
|
|
5
|
+
| Provider | Price (USDC per million tokens) | Most output per call |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| Script writer | $3 input, $15 output | 4,000 tokens |
|
|
8
|
+
| Humaniser | $3 input, $15 output | 2,000 tokens |
|
|
9
|
+
|
|
10
|
+
Both are on the mid tier the specialist profiles use. The buyer locks the most a call can cost (the estimate for its input plus the output cap) and pays only for the tokens used; the protocol fee is 5% of that (2.5% at the launch rate, up to the end of 31 March 2027), taken from the provider's share.
|
|
11
|
+
|
|
12
|
+
## What the instructions do (outline only)
|
|
13
|
+
|
|
14
|
+
Script writer. The request is a brief: topic, audience, length and platform. The instructions ask for:
|
|
15
|
+
|
|
16
|
+
1. A short background section that a ten-year-old could follow, so viewers are not lost.
|
|
17
|
+
2. A scene-by-scene script: for each scene, what is on screen and the narration, timed to the requested length.
|
|
18
|
+
3. Writing that follows the house pattern list: no em dashes, none of the listed overused words, no forced groups of three, sentence-case headings, plain verbs.
|
|
19
|
+
|
|
20
|
+
Humaniser. The request is a draft. The instructions ask for the same text with the house patterns removed, the meaning, facts, names and numbers unchanged, and about the same length.
|
|
21
|
+
|
|
22
|
+
The full pattern list and style rules are the private part.
|
|
23
|
+
|
|
24
|
+
## Running one
|
|
25
|
+
|
|
26
|
+
1. Put the private prompt next to the config, for example `script-writer.prompt.private.txt`.
|
|
27
|
+
2. Replace the `REPLACE_WITH_...` values: the provider wallet (one wallet per provider), its public https address and the upstream model.
|
|
28
|
+
3. Set `"mock": false` and `UPSTREAM_API_KEY`, then `rap-provider doctor --config script-writer.provider.json` and `rap-provider start --config script-writer.provider.json`.
|
|
29
|
+
|
|
30
|
+
The host, model, wallets and listing wording are the owner's choices, and every mainnet transaction needs the owner's approval.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "Reddi humaniser",
|
|
3
|
+
"description": "Rewrites a draft so it reads as a person wrote it: removes the patterns that mark machine-written text and keeps the meaning, facts and length.",
|
|
4
|
+
"network": "solana-devnet",
|
|
5
|
+
"wallet": "REPLACE_WITH_THE_PROVIDER_WALLET",
|
|
6
|
+
"publicUrl": "https://REPLACE_WITH_THE_PUBLIC_ADDRESS",
|
|
7
|
+
"model": "REPLACE_WITH_THE_MID_TIER_MODEL",
|
|
8
|
+
"upstream": { "baseUrl": "https://openrouter.ai/api/v1", "apiKeyEnv": "UPSTREAM_API_KEY", "mock": true },
|
|
9
|
+
"price": { "currency": "USDC", "inputPerMillion": "3", "outputPerMillion": "15", "maxOutputTokens": 2000 },
|
|
10
|
+
"systemPromptFile": "humaniser.prompt.private.txt",
|
|
11
|
+
"keypairPath": "~/.config/solana/rap/humaniser.json",
|
|
12
|
+
"replayFile": ".rap-provider/humaniser/accepted.log",
|
|
13
|
+
"sessions": { "file": ".rap-provider/humaniser/sessions.jsonl" },
|
|
14
|
+
"listing": { "capabilities": { "taskTypes": ["writing", "editing"] } }
|
|
15
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "Reddi video scene and script writer",
|
|
3
|
+
"description": "Turns a brief (topic, audience, length, platform) into a scene-by-scene video script with narration, in plain, human-sounding English, with a short background section a ten-year-old could follow.",
|
|
4
|
+
"network": "solana-devnet",
|
|
5
|
+
"wallet": "REPLACE_WITH_THE_PROVIDER_WALLET",
|
|
6
|
+
"publicUrl": "https://REPLACE_WITH_THE_PUBLIC_ADDRESS",
|
|
7
|
+
"model": "REPLACE_WITH_THE_MID_TIER_MODEL",
|
|
8
|
+
"upstream": { "baseUrl": "https://openrouter.ai/api/v1", "apiKeyEnv": "UPSTREAM_API_KEY", "mock": true },
|
|
9
|
+
"price": { "currency": "USDC", "inputPerMillion": "3", "outputPerMillion": "15", "maxOutputTokens": 4000 },
|
|
10
|
+
"systemPromptFile": "script-writer.prompt.private.txt",
|
|
11
|
+
"keypairPath": "~/.config/solana/rap/script-writer.json",
|
|
12
|
+
"replayFile": ".rap-provider/script-writer/accepted.log",
|
|
13
|
+
"sessions": { "file": ".rap-provider/script-writer/sessions.jsonl" },
|
|
14
|
+
"listing": { "capabilities": { "taskTypes": ["writing", "video-script"] } }
|
|
15
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* A buyer's side of one paid call, for trying your provider on devnet.
|
|
4
|
+
*
|
|
5
|
+
* BUYER_KEYPAIR_PATH=~/.config/solana/buyer.json \
|
|
6
|
+
* node examples/paid-call.mjs http://localhost:8787 "Write a haiku about escrow"
|
|
7
|
+
*
|
|
8
|
+
* It asks for the price, shows the quote, locks the maximum in a metered
|
|
9
|
+
* escrow, repeats the call with the lock, then checks the receipt.
|
|
10
|
+
*
|
|
11
|
+
* Devnet only. It refuses a provider on any other network. The buyer wallet
|
|
12
|
+
* needs a little devnet SOL and devnet USDC (https://faucet.circle.com).
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, createPrivateKey, randomBytes, sign as edSign } from "node:crypto";
|
|
15
|
+
import { readFileSync } from "node:fs";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { Connection, Keypair, PublicKey, Transaction } from "@solana/web3.js";
|
|
18
|
+
import { verifyReddiReceiptV2 } from "@redditech/agent-protocol/receipt-v2";
|
|
19
|
+
import x402 from "@redditech/x402-solana";
|
|
20
|
+
|
|
21
|
+
const { buildLockTokenEscrowInstruction, directPaymentCurrency, meteredPaymentHeaderValue, paidCallAuthHeaders, SOLANA_GENESIS_HASHES, tokenEscrowAddresses, treasuryTokenAccount } = x402;
|
|
22
|
+
|
|
23
|
+
const [providerUrl, prompt = "Say hello in one sentence."] = process.argv.slice(2);
|
|
24
|
+
if (!providerUrl) {
|
|
25
|
+
console.error('Usage: node examples/paid-call.mjs <provider url> "<prompt>"');
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
const keyPath = (process.env.BUYER_KEYPAIR_PATH ?? "").replace(/^~(?=\/)/, homedir());
|
|
29
|
+
if (!keyPath) {
|
|
30
|
+
console.error("Set BUYER_KEYPAIR_PATH to the buyer wallet's keypair file. Use a devnet-only wallet.");
|
|
31
|
+
process.exit(1);
|
|
32
|
+
}
|
|
33
|
+
const buyer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(keyPath, "utf8"))));
|
|
34
|
+
const endpoint = `${providerUrl.replace(/\/+$/, "")}/v1/chat/completions`;
|
|
35
|
+
const body = JSON.stringify({ messages: [{ role: "user", content: prompt }], max_tokens: 200 });
|
|
36
|
+
const post = (headers = {}) => fetch(endpoint, { method: "POST", headers: { "content-type": "application/json", ...headers }, body });
|
|
37
|
+
|
|
38
|
+
const first = await post();
|
|
39
|
+
if (first.status !== 402) throw new Error(`expected a 402 with the price, got ${first.status}`);
|
|
40
|
+
const offer = (await first.json()).metered;
|
|
41
|
+
if (offer?.settlement !== "metered-escrow") throw new Error("the provider made no per-token offer");
|
|
42
|
+
if (offer.network !== "solana-devnet") throw new Error(`this example pays on devnet only; the provider is on ${offer.network}`);
|
|
43
|
+
const currency = directPaymentCurrency(offer.currency);
|
|
44
|
+
if (!currency?.tokenProgram) throw new Error(`unsupported currency ${offer.currency}`);
|
|
45
|
+
|
|
46
|
+
console.log(`Price: ${offer.inputPerMillion} in / ${offer.outputPerMillion} out ${offer.currency} per million tokens`);
|
|
47
|
+
console.log(`Estimate: ${offer.estimatedCost} ${offer.currency}. Locking the maximum: ${offer.suggestedMaxCharge} ${offer.currency} (twice the estimate).`);
|
|
48
|
+
|
|
49
|
+
const connection = new Connection(process.env.SOLANA_RPC_URL ?? "https://api.devnet.solana.com", "confirmed");
|
|
50
|
+
if ((await connection.getGenesisHash()) !== SOLANA_GENESIS_HASHES["solana-devnet"]) throw new Error("SOLANA_RPC_URL is not a devnet endpoint");
|
|
51
|
+
|
|
52
|
+
const programId = new PublicKey(offer.escrowProgramId);
|
|
53
|
+
const mint = new PublicKey(offer.mint);
|
|
54
|
+
const tokenProgram = new PublicKey(currency.tokenProgram);
|
|
55
|
+
const payee = new PublicKey(offer.payTo);
|
|
56
|
+
const nonce = randomBytes(16);
|
|
57
|
+
const lock = buildLockTokenEscrowInstruction({
|
|
58
|
+
programId,
|
|
59
|
+
tokenProgram,
|
|
60
|
+
payer: buyer.publicKey,
|
|
61
|
+
payee,
|
|
62
|
+
mint,
|
|
63
|
+
source: treasuryTokenAccount({ mint, tokenProgram }, buyer.publicKey),
|
|
64
|
+
recipient: treasuryTokenAccount({ mint, tokenProgram }, payee),
|
|
65
|
+
amount: BigInt(offer.suggestedMaxChargeBaseUnits),
|
|
66
|
+
nonce,
|
|
67
|
+
metered: true,
|
|
68
|
+
});
|
|
69
|
+
const latest = await connection.getLatestBlockhash("confirmed");
|
|
70
|
+
const transaction = new Transaction({ feePayer: buyer.publicKey, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }).add(lock);
|
|
71
|
+
transaction.sign(buyer);
|
|
72
|
+
const lockSignature = await connection.sendRawTransaction(transaction.serialize());
|
|
73
|
+
await connection.confirmTransaction({ signature: lockSignature, ...latest }, "confirmed");
|
|
74
|
+
console.log(`Locked: ${lockSignature}`);
|
|
75
|
+
|
|
76
|
+
// The lock is public on chain, so the buyer also signs this exact request: only the payer's call is served.
|
|
77
|
+
const buyerKey = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(buyer.secretKey.subarray(0, 32))]), format: "der", type: "pkcs8" });
|
|
78
|
+
const authHeaders = await paidCallAuthHeaders({
|
|
79
|
+
genesisHash: SOLANA_GENESIS_HASHES["solana-devnet"],
|
|
80
|
+
escrow: tokenEscrowAddresses({ programId, payer: buyer.publicKey, nonce }).escrow.toBase58(),
|
|
81
|
+
provider: payee.toBase58(),
|
|
82
|
+
body,
|
|
83
|
+
payer: buyer.publicKey.toBase58(),
|
|
84
|
+
signWithPayer: (message) => new Uint8Array(edSign(null, Buffer.from(message), buyerKey)),
|
|
85
|
+
});
|
|
86
|
+
const paid = await post({ "x402-payment": meteredPaymentHeaderValue({ payer: buyer.publicKey, nonce, programId }), ...authHeaders });
|
|
87
|
+
const responseText = await paid.text();
|
|
88
|
+
if (paid.status !== 200) throw new Error(`the paid call failed (${paid.status}): ${responseText}`);
|
|
89
|
+
const answer = JSON.parse(responseText);
|
|
90
|
+
console.log(`\n${answer.choices?.[0]?.message?.content}\n`);
|
|
91
|
+
const m = answer.reddi.metered;
|
|
92
|
+
console.log(`Used ${m.inputTokens} in / ${m.outputTokens} out tokens. Charged ${m.charged} ${m.currency} (fee ${m.fee}, provider ${m.provider}). Refunded ${m.refund}.`);
|
|
93
|
+
console.log(`Settled: ${m.settleSignature}`);
|
|
94
|
+
|
|
95
|
+
const signed = JSON.parse(Buffer.from(paid.headers.get("x-reddi-provider-receipt") ?? "", "base64url").toString("utf8") || "null");
|
|
96
|
+
const sha = (text) => createHash("sha256").update(text).digest("hex");
|
|
97
|
+
const check = verifyReddiReceiptV2(signed, {
|
|
98
|
+
providerId: offer.payTo,
|
|
99
|
+
requestHash: sha(body),
|
|
100
|
+
responseHash: sha(responseText),
|
|
101
|
+
payment: { network: "solana-devnet", txSignature: m.settleSignature, payer: buyer.publicKey.toBase58(), settlement: "metered-escrow" },
|
|
102
|
+
});
|
|
103
|
+
console.log(check.ok ? "Receipt: signed by the provider and matches this call." : `Receipt did NOT verify: ${JSON.stringify(check.errors)}`);
|
|
104
|
+
process.exit(check.ok ? 0 : 1);
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* A buyer's side of a session: one metered escrow lock pays for several
|
|
4
|
+
* calls, and the provider settles once, for the total.
|
|
5
|
+
*
|
|
6
|
+
* BUYER_KEYPAIR_PATH=~/.config/solana/buyer.json \
|
|
7
|
+
* node examples/session-call.mjs http://localhost:8787 3
|
|
8
|
+
*
|
|
9
|
+
* It locks enough for the calls, makes a session key and has the buyer
|
|
10
|
+
* wallet sign a delegation to it, sends the calls numbered 1..n (the last
|
|
11
|
+
* one closes the session), then checks the whole receipt chain.
|
|
12
|
+
*
|
|
13
|
+
* Devnet only. The buyer wallet needs a little devnet SOL and devnet USDC.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, createPrivateKey, randomBytes, sign as edSign } from "node:crypto";
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import { Connection, Keypair, PublicKey, Transaction } from "@solana/web3.js";
|
|
19
|
+
import { verifyReddiReceiptV2Session } from "@redditech/agent-protocol/receipt-v2";
|
|
20
|
+
import x402 from "@redditech/x402-solana";
|
|
21
|
+
|
|
22
|
+
const { buildLockTokenEscrowInstruction, directPaymentCurrency, meteredPaymentHeaderValue, SOLANA_GENESIS_HASHES, sessionCallAction, sessionDelegationHeaderValue, sessionSignatureHeaderValue, tokenEscrowAddresses, treasuryTokenAccount } = x402;
|
|
23
|
+
|
|
24
|
+
const [providerUrl, callsText = "3"] = process.argv.slice(2);
|
|
25
|
+
const calls = Number(callsText);
|
|
26
|
+
if (!providerUrl || !Number.isSafeInteger(calls) || calls < 1 || calls > 20) {
|
|
27
|
+
console.error("Usage: node examples/session-call.mjs <provider url> [calls, 1-20]");
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
const keyPath = (process.env.BUYER_KEYPAIR_PATH ?? "").replace(/^~(?=\/)/, homedir());
|
|
31
|
+
if (!keyPath) {
|
|
32
|
+
console.error("Set BUYER_KEYPAIR_PATH to the buyer wallet's keypair file. Use a devnet-only wallet.");
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
const buyer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(readFileSync(keyPath, "utf8"))));
|
|
36
|
+
const signer = (keypair) => {
|
|
37
|
+
const key = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), Buffer.from(keypair.secretKey.subarray(0, 32))]), format: "der", type: "pkcs8" });
|
|
38
|
+
return (message) => new Uint8Array(edSign(null, Buffer.from(message), key));
|
|
39
|
+
};
|
|
40
|
+
const base = providerUrl.replace(/\/+$/, "");
|
|
41
|
+
const endpoint = `${base}/v1/chat/completions`;
|
|
42
|
+
const bodyOf = (n) => JSON.stringify({ messages: [{ role: "user", content: `Call ${n}: say hello in one sentence.` }], max_tokens: 200 });
|
|
43
|
+
|
|
44
|
+
const first = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: bodyOf(1) });
|
|
45
|
+
if (first.status !== 402) throw new Error(`expected a 402 with the price, got ${first.status}`);
|
|
46
|
+
const offer = (await first.json()).metered;
|
|
47
|
+
if (offer?.network !== "solana-devnet") throw new Error("this example pays on devnet only");
|
|
48
|
+
const currency = directPaymentCurrency(offer.currency);
|
|
49
|
+
// Enough for every call's worst case, twice over.
|
|
50
|
+
const amount = BigInt(offer.suggestedMaxChargeBaseUnits) * BigInt(calls);
|
|
51
|
+
console.log(`Price: ${offer.inputPerMillion} in / ${offer.outputPerMillion} out ${offer.currency} per million tokens. Locking ${amount} base units for ${calls} calls.`);
|
|
52
|
+
|
|
53
|
+
const connection = new Connection(process.env.SOLANA_RPC_URL ?? "https://api.devnet.solana.com", "confirmed");
|
|
54
|
+
if ((await connection.getGenesisHash()) !== SOLANA_GENESIS_HASHES["solana-devnet"]) throw new Error("SOLANA_RPC_URL is not a devnet endpoint");
|
|
55
|
+
const programId = new PublicKey(offer.escrowProgramId);
|
|
56
|
+
const mint = new PublicKey(offer.mint);
|
|
57
|
+
const tokenProgram = new PublicKey(currency.tokenProgram);
|
|
58
|
+
const payee = new PublicKey(offer.payTo);
|
|
59
|
+
const nonce = randomBytes(16);
|
|
60
|
+
const lock = buildLockTokenEscrowInstruction({
|
|
61
|
+
programId, tokenProgram, payer: buyer.publicKey, payee, mint,
|
|
62
|
+
source: treasuryTokenAccount({ mint, tokenProgram }, buyer.publicKey),
|
|
63
|
+
recipient: treasuryTokenAccount({ mint, tokenProgram }, payee),
|
|
64
|
+
amount, nonce, metered: true,
|
|
65
|
+
});
|
|
66
|
+
const latest = await connection.getLatestBlockhash("confirmed");
|
|
67
|
+
const transaction = new Transaction({ feePayer: buyer.publicKey, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }).add(lock);
|
|
68
|
+
transaction.sign(buyer);
|
|
69
|
+
const lockSignature = await connection.sendRawTransaction(transaction.serialize());
|
|
70
|
+
await connection.confirmTransaction({ signature: lockSignature, ...latest }, "confirmed");
|
|
71
|
+
console.log(`Locked: ${lockSignature}`);
|
|
72
|
+
|
|
73
|
+
const escrow = tokenEscrowAddresses({ programId, payer: buyer.publicKey, nonce }).escrow.toBase58();
|
|
74
|
+
const sessionKey = Keypair.generate();
|
|
75
|
+
const delegation = await sessionDelegationHeaderValue({ genesisHash: SOLANA_GENESIS_HASHES["solana-devnet"], escrow, provider: payee.toBase58(), sessionKey: sessionKey.publicKey.toBase58(), expiresAt: Math.floor(Date.now() / 1000) + 3600 }, signer(buyer));
|
|
76
|
+
const payment = meteredPaymentHeaderValue({ payer: buyer.publicKey, nonce, programId });
|
|
77
|
+
|
|
78
|
+
const receipts = [];
|
|
79
|
+
let closing;
|
|
80
|
+
for (let n = 1; n <= calls; n += 1) {
|
|
81
|
+
const body = bodyOf(n);
|
|
82
|
+
const response = await fetch(endpoint, {
|
|
83
|
+
method: "POST",
|
|
84
|
+
headers: {
|
|
85
|
+
"content-type": "application/json",
|
|
86
|
+
"x402-payment": payment,
|
|
87
|
+
"x402-session-sequence": String(n),
|
|
88
|
+
...(n === calls ? { "x402-session": "close" } : {}),
|
|
89
|
+
"x402-session-delegation": delegation,
|
|
90
|
+
"x402-session-signature": await sessionSignatureHeaderValue({ genesisHash: SOLANA_GENESIS_HASHES["solana-devnet"], action: sessionCallAction(n === calls), escrow, sequence: n, body }, signer(sessionKey)),
|
|
91
|
+
},
|
|
92
|
+
body,
|
|
93
|
+
});
|
|
94
|
+
const text = await response.text();
|
|
95
|
+
if (response.status !== 200) throw new Error(`call ${n} failed (${response.status}): ${text}`);
|
|
96
|
+
const m = JSON.parse(text).reddi.metered;
|
|
97
|
+
console.log(`Call ${n}: ${m.inputTokens} in / ${m.outputTokens} out; session so far ${m.session.cumulativeCost} ${offer.currency}.`);
|
|
98
|
+
receipts.push(JSON.parse(Buffer.from(response.headers.get("x-reddi-provider-receipt"), "base64url").toString("utf8")));
|
|
99
|
+
if (n === calls) {
|
|
100
|
+
console.log(`Session ${response.headers.get("x-reddi-session-state")}.`);
|
|
101
|
+
const value = response.headers.get("x-reddi-session-receipt");
|
|
102
|
+
if (value) closing = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (!closing) throw new Error("the session closed without a closing receipt");
|
|
106
|
+
receipts.push(closing);
|
|
107
|
+
const p = closing.receipt.payment;
|
|
108
|
+
console.log(`Settled once: ${p.txSignature}. Charged ${p.amount} base units (fee ${p.fee.amount}); refunded ${p.metered.refunded}.`);
|
|
109
|
+
const check = verifyReddiReceiptV2Session(receipts, { providerId: offer.payTo, session: { escrow } });
|
|
110
|
+
console.log(check.ok ? `Receipt chain: ${receipts.length} receipts, signed, linked and closed.` : `Receipt chain did NOT verify: ${JSON.stringify(check)}`);
|
|
111
|
+
process.exit(check.ok ? 0 : 1);
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@redditech/provider-kit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Run your own paid, per-token priced provider on Reddi Agent Protocol: one config file, one command, any OpenAI-compatible model.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nissan/reddi-agent-protocol.git",
|
|
9
|
+
"directory": "packages/provider-kit"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "dist/src/index.js",
|
|
13
|
+
"types": "dist/src/index.d.ts",
|
|
14
|
+
"bin": {
|
|
15
|
+
"rap-provider": "dist/src/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/src/index.d.ts",
|
|
20
|
+
"import": "./dist/src/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"!dist/tests",
|
|
27
|
+
"examples",
|
|
28
|
+
"!examples/**/*.private.txt",
|
|
29
|
+
"Dockerfile",
|
|
30
|
+
"README.md",
|
|
31
|
+
"LICENSE"
|
|
32
|
+
],
|
|
33
|
+
"scripts": {
|
|
34
|
+
"clean": "rm -rf dist",
|
|
35
|
+
"build": "tsc -p tsconfig.json",
|
|
36
|
+
"test": "npm run build && node --test dist/tests/*.test.js",
|
|
37
|
+
"check:artifacts": "node ../../scripts/check-package-artifact-contents.mjs --dir packages/provider-kit",
|
|
38
|
+
"release:dry-run": "npm run clean && npm test && npm run check:artifacts && npm pack --dry-run"
|
|
39
|
+
},
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": ">=20"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@redditech/agent-protocol": "^0.2.0",
|
|
45
|
+
"@redditech/x402-solana": "^0.1.0",
|
|
46
|
+
"@solana/web3.js": "^1.98.4"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^20",
|
|
50
|
+
"typescript": "^5"
|
|
51
|
+
}
|
|
52
|
+
}
|