@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,1051 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The provider's HTTP surface.
|
|
3
|
+
*
|
|
4
|
+
* GET /healthz liveness
|
|
5
|
+
* GET /v1/models the declared model
|
|
6
|
+
* GET /.well-known/reddi-agent.json name, wallet, network and per-token price
|
|
7
|
+
* POST /v1/chat/completions OpenAI-compatible, paid per token
|
|
8
|
+
* POST /v1/session/close settle a session now (payment header only)
|
|
9
|
+
* GET /v1/session/<escrow> a session's totals, and its closing receipt once settled
|
|
10
|
+
*
|
|
11
|
+
* A paid call goes: no payment, so 402 with the price, the estimate and the
|
|
12
|
+
* maximum to lock; then the same request with the lock named in `x402-payment`;
|
|
13
|
+
* the lock is checked on chain; the model answers; the provider settles the
|
|
14
|
+
* actual cost; the answer returns with a signed receipt.
|
|
15
|
+
*
|
|
16
|
+
* Order matters for money. A lock is accepted only when every account its
|
|
17
|
+
* payout needs can receive. The buyer is charged only after the model has
|
|
18
|
+
* answered, and the answer is sent only after the settle has confirmed. If the
|
|
19
|
+
* model fails the lock is declined, which refunds the buyer in full. The
|
|
20
|
+
* receipt states what the confirmed settle moved, read back from the chain;
|
|
21
|
+
* when that cannot be read, no receipt is issued. A buyer is told nothing was
|
|
22
|
+
* charged only when its escrow is read back as still locked.
|
|
23
|
+
*
|
|
24
|
+
* Sessions (`x402-session-sequence: n` with the same lock on every call): one
|
|
25
|
+
* lock pays for many calls. Each call is checked against the session's
|
|
26
|
+
* ledger, answered with a receipt that carries the running totals and the
|
|
27
|
+
* previous receipt's hash, and recorded before the answer is sent. Nothing is
|
|
28
|
+
* charged per call. The session settles once, for the ledger's total, when the
|
|
29
|
+
* buyer closes it, after it has been idle, or before its refund window opens,
|
|
30
|
+
* and that settle has a closing receipt of its own.
|
|
31
|
+
*/
|
|
32
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
33
|
+
import { hashReddiReceiptV2, signReddiReceiptV2 } from "@redditech/agent-protocol/receipt-v2";
|
|
34
|
+
import { PublicKey } from "@solana/web3.js";
|
|
35
|
+
import { baseUnitsToDecimal, checkMeteredPayout, checkProviderCluster, confirmMeteredSettlement, decodeTokenEscrowAccount, directPaymentCurrency, ESCROW_PROTOCOL_TREASURY, estimateInputTokens, meteredDecline, meteredOffer, meteredSettlement, outputLimit, readMeteredPaymentHeader, lockMatchesSession, readSessionHeaders, recordedInstruction, sessionCallAction, sessionPaymentHeader, sessionSettlement, SOLANA_GENESIS_HASHES, tokenCostBaseUnits, tokenEscrowAddresses, usageFrom, verifyMeteredLock, verifySessionRequestWithTransactions, } from "@redditech/x402-solana";
|
|
36
|
+
import { MemoryPendingSettleStore } from "./pending.js";
|
|
37
|
+
import { MAX_BODY_BYTES } from "./config.js";
|
|
38
|
+
import { ADL_PATH, providerAdlText } from "./adl.js";
|
|
39
|
+
export const PROVIDER_RECEIPT_HEADER = "x-reddi-provider-receipt";
|
|
40
|
+
/** The closing receipt of a session, on the answer that settled it. */
|
|
41
|
+
export const SESSION_RECEIPT_HEADER = "x-reddi-session-receipt";
|
|
42
|
+
/** On an answer that asked to close the session: settled, declined, or pending (tried again shortly). */
|
|
43
|
+
export const SESSION_STATE_HEADER = "x-reddi-session-state";
|
|
44
|
+
const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
|
|
45
|
+
const MAX_RECEIPT_HEADER_CHARS = 4096;
|
|
46
|
+
/** How long the answer of a call whose settle outcome is not known is held for the buyer to collect. */
|
|
47
|
+
const HELD_ANSWER_MS = 10 * 60_000;
|
|
48
|
+
const sha256Hex = (text) => createHash("sha256").update(Buffer.from(text, "utf8")).digest("hex");
|
|
49
|
+
function json(status, body, headers = {}) {
|
|
50
|
+
return new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } });
|
|
51
|
+
}
|
|
52
|
+
function refuse(status, code, message, extra = {}, headers = {}) {
|
|
53
|
+
return json(status, { error: { code, message }, ...extra }, headers);
|
|
54
|
+
}
|
|
55
|
+
function readMessages(value) {
|
|
56
|
+
if (!Array.isArray(value) || value.length === 0)
|
|
57
|
+
return undefined;
|
|
58
|
+
const messages = [];
|
|
59
|
+
for (const item of value) {
|
|
60
|
+
const role = item?.role;
|
|
61
|
+
const content = item?.content;
|
|
62
|
+
if (typeof role !== "string" || typeof content !== "string")
|
|
63
|
+
return undefined;
|
|
64
|
+
messages.push({ role, content });
|
|
65
|
+
}
|
|
66
|
+
return messages;
|
|
67
|
+
}
|
|
68
|
+
/** What the listing and buyers read about this provider. No secrets. */
|
|
69
|
+
export function providerMetadata(config) {
|
|
70
|
+
const { terms } = config;
|
|
71
|
+
return {
|
|
72
|
+
protocol: "reddi-agent-protocol",
|
|
73
|
+
adl: `${config.publicUrl}${ADL_PATH}`,
|
|
74
|
+
name: config.name,
|
|
75
|
+
description: config.description,
|
|
76
|
+
walletAddress: config.wallet,
|
|
77
|
+
network: config.network,
|
|
78
|
+
endpoint: `${config.publicUrl}/v1/chat/completions`,
|
|
79
|
+
model: config.model,
|
|
80
|
+
acceptingPayments: !config.paused,
|
|
81
|
+
pricing: {
|
|
82
|
+
settlement: "metered-escrow",
|
|
83
|
+
currency: terms.price.currency,
|
|
84
|
+
mint: terms.mint.toBase58(),
|
|
85
|
+
inputPerMillion: terms.price.inputPerMillion,
|
|
86
|
+
outputPerMillion: terms.price.outputPerMillion,
|
|
87
|
+
maxOutputTokens: terms.maxOutputTokens,
|
|
88
|
+
escrowProgramId: terms.programId.toBase58(),
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export function createProviderHandler(config, deps) {
|
|
93
|
+
const { terms } = config;
|
|
94
|
+
// The provider's ADL, made once from the config it runs on.
|
|
95
|
+
const adlText = providerAdlText(config).text;
|
|
96
|
+
const log = deps.log ?? (() => undefined);
|
|
97
|
+
// Payers sign for one network, named by its genesis hash: the one this provider checks its RPC is on.
|
|
98
|
+
const signingGenesisHash = config.genesisHash ?? SOLANA_GENESIS_HASHES[config.network];
|
|
99
|
+
// The cluster is checked before the first lock is trusted, and again after any failure.
|
|
100
|
+
let clusterConfirmed = false;
|
|
101
|
+
// Buyer token accounts this provider paid to create today (UTC), against the operator's daily bound.
|
|
102
|
+
const subsidy = { day: "", used: 0 };
|
|
103
|
+
const today = () => (deps.now?.() ?? new Date()).toISOString().slice(0, 10);
|
|
104
|
+
const pendingSettles = deps.pendingSettles ?? new MemoryPendingSettleStore();
|
|
105
|
+
// Answers of single calls whose settle was sent but not yet known to land, by escrow.
|
|
106
|
+
const waitingCalls = new Map();
|
|
107
|
+
/** Single-call locks whose settle is being sent or looked at right now. */
|
|
108
|
+
const answering = new Set();
|
|
109
|
+
const subsidyLeft = () => {
|
|
110
|
+
if (subsidy.day !== today())
|
|
111
|
+
Object.assign(subsidy, { day: today(), used: 0 });
|
|
112
|
+
return config.refundAccountsPerDay - subsidy.used > 0;
|
|
113
|
+
};
|
|
114
|
+
// "locked": the buyer's maximum is still in escrow. "closed": a settle landed. "unknown": the chain could not say.
|
|
115
|
+
const escrowState = async (address) => {
|
|
116
|
+
try {
|
|
117
|
+
const account = await deps.chain.readAccount(address);
|
|
118
|
+
if (!account)
|
|
119
|
+
return "closed";
|
|
120
|
+
if (!account.owner.equals(terms.programId))
|
|
121
|
+
return "unknown";
|
|
122
|
+
return decodeTokenEscrowAccount(Buffer.from(account.data)).status === 0 ? "locked" : "closed";
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return "unknown";
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Sends the settle `build` makes and reads back what it moved. The settle is signed first and recorded through
|
|
130
|
+
* `record` before it is sent, so after a failure, a timeout or a restart the
|
|
131
|
+
* only transaction that can count as this settle is that signature. The
|
|
132
|
+
* outcome is:
|
|
133
|
+
*
|
|
134
|
+
* - `ok: true`: this settle landed (confirmed on chain under its own
|
|
135
|
+
* signature). `confirmed` says whether what it moved could be read back and
|
|
136
|
+
* adds up, with the settle instruction matched exactly.
|
|
137
|
+
* - `ok: false`: nothing was charged by this provider: no settle could be
|
|
138
|
+
* built or recorded, or every one sent is known not to have landed while
|
|
139
|
+
* the escrow stays locked.
|
|
140
|
+
* - `closed`: the escrow was closed by something else (the buyer's refund)
|
|
141
|
+
* and no settle of this provider landed.
|
|
142
|
+
* - `pending`: a settle was sent and its outcome is not known. It stays
|
|
143
|
+
* recorded and is looked up again later; nothing else counts as settled.
|
|
144
|
+
*
|
|
145
|
+
* `resume` picks up a settle recorded earlier instead of building a new one.
|
|
146
|
+
*/
|
|
147
|
+
async function settleLock(lock, escrowAddress, requestId, build, record, resume) {
|
|
148
|
+
const escrow = escrowAddress.toBase58();
|
|
149
|
+
// Signs one settle and records it before it is sent. Undefined when it could not be built, signed or recorded: then nothing was sent.
|
|
150
|
+
const prepare = async (payout) => {
|
|
151
|
+
try {
|
|
152
|
+
const settled = build(payout);
|
|
153
|
+
const signed = await deps.chain.signInstructions(settled.instructions);
|
|
154
|
+
const pending = {
|
|
155
|
+
signature: signed.signature,
|
|
156
|
+
transaction: signed.transaction,
|
|
157
|
+
lastValidBlockHeight: signed.lastValidBlockHeight,
|
|
158
|
+
instruction: recordedInstruction(settled.instruction),
|
|
159
|
+
destination: (payout.payTo ?? lock.terms.recipient).toBase58(),
|
|
160
|
+
treasuryToken: payout.treasuryToken.toBase58(),
|
|
161
|
+
refundTo: payout.refundTo.toBase58(),
|
|
162
|
+
requestId,
|
|
163
|
+
};
|
|
164
|
+
await record(pending);
|
|
165
|
+
return { settled, payout, pending };
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return undefined;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
// Sends (or sends again) a recorded settle and says where it stands.
|
|
172
|
+
const sendAndResolve = async (pending) => {
|
|
173
|
+
try {
|
|
174
|
+
const signature = await deps.chain.sendSigned({ signature: pending.signature, transaction: pending.transaction, lastValidBlockHeight: pending.lastValidBlockHeight });
|
|
175
|
+
if (signature === pending.signature)
|
|
176
|
+
return "landed";
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
// Sending can fail and the transaction still land: look it up by its own signature.
|
|
180
|
+
}
|
|
181
|
+
return deps.chain.signatureState(pending.signature, pending.lastValidBlockHeight);
|
|
182
|
+
};
|
|
183
|
+
const confirm = async (pending, settled, payout) => {
|
|
184
|
+
let confirmed = { ok: false, reason: "not_found" };
|
|
185
|
+
try {
|
|
186
|
+
confirmed = confirmMeteredSettlement(await deps.chain.readSettlement(pending.signature), {
|
|
187
|
+
programId: terms.programId,
|
|
188
|
+
escrow: escrowAddress,
|
|
189
|
+
mint: terms.mint,
|
|
190
|
+
destination: new PublicKey(pending.destination),
|
|
191
|
+
treasuryToken: new PublicKey(pending.treasuryToken),
|
|
192
|
+
refundTo: new PublicKey(pending.refundTo),
|
|
193
|
+
maxBaseUnits: lock.maxBaseUnits,
|
|
194
|
+
instruction: pending.instruction,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
confirmed = { ok: false, reason: "not_found" };
|
|
199
|
+
}
|
|
200
|
+
return { ok: true, settleSignature: pending.signature, confirmed, ...(settled ? { settled } : {}), ...(payout ? { payout } : {}) };
|
|
201
|
+
};
|
|
202
|
+
let current;
|
|
203
|
+
if (resume)
|
|
204
|
+
current = { pending: resume };
|
|
205
|
+
else
|
|
206
|
+
current = await prepare(lock.payout);
|
|
207
|
+
if (!current) {
|
|
208
|
+
log({ event: "settle_failed", requestId, escrow, reason: "not_sent" });
|
|
209
|
+
return { ok: false };
|
|
210
|
+
}
|
|
211
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
212
|
+
const state = await sendAndResolve(current.pending);
|
|
213
|
+
if (state === "landed")
|
|
214
|
+
return confirm(current.pending, current.settled, current.payout);
|
|
215
|
+
if (state === "unknown") {
|
|
216
|
+
log({ event: "settle_pending", requestId, escrow, signature: current.pending.signature, alert: true });
|
|
217
|
+
return { ok: "pending", signature: current.pending.signature };
|
|
218
|
+
}
|
|
219
|
+
// It moved nothing and never will. Forget it, then look at the escrow.
|
|
220
|
+
await record(undefined).catch(() => undefined);
|
|
221
|
+
const escrowNow = await escrowState(escrowAddress);
|
|
222
|
+
if (escrowNow === "closed") {
|
|
223
|
+
log({ event: "settle_lost_to_close", requestId, escrow, signature: current.pending.signature });
|
|
224
|
+
return { ok: "closed" };
|
|
225
|
+
}
|
|
226
|
+
if (escrowNow !== "locked" || attempt === 1)
|
|
227
|
+
break;
|
|
228
|
+
// Still locked: an account may have gone since the lock was checked. The
|
|
229
|
+
// buyer's associated token account will do for the unused part; the
|
|
230
|
+
// provider pays to create it within the operator's daily bound.
|
|
231
|
+
const reserved = subsidyLeft();
|
|
232
|
+
if (reserved)
|
|
233
|
+
subsidy.used += 1;
|
|
234
|
+
let next;
|
|
235
|
+
try {
|
|
236
|
+
const again = await checkMeteredPayout({ terms, escrow: lock.terms, readAccount: (address) => deps.chain.readAccount(address), allowPayerAssociatedAccount: true, createRefundAccount: reserved || lock.payout.createRefundAccount === true });
|
|
237
|
+
if (again.ok)
|
|
238
|
+
next = await prepare(again.payout);
|
|
239
|
+
if (next?.payout?.createRefundAccount)
|
|
240
|
+
log({ event: "refund_account_created", requestId, escrow, account: next.payout.refundTo.toBase58() });
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
next = undefined;
|
|
244
|
+
}
|
|
245
|
+
if (reserved && !next?.payout?.createRefundAccount)
|
|
246
|
+
subsidy.used = Math.max(0, subsidy.used - 1);
|
|
247
|
+
if (!next)
|
|
248
|
+
break;
|
|
249
|
+
current = next;
|
|
250
|
+
}
|
|
251
|
+
log({ event: "settle_failed", requestId, escrow });
|
|
252
|
+
return { ok: false };
|
|
253
|
+
}
|
|
254
|
+
const nowMs = () => (deps.now?.() ?? new Date()).getTime();
|
|
255
|
+
const issuedAt = () => (deps.now?.() ?? new Date()).toISOString();
|
|
256
|
+
const decimals = directPaymentCurrency(terms.price.currency).decimals;
|
|
257
|
+
const readAccount = (address) => deps.chain.readAccount(address);
|
|
258
|
+
const readSlot = () => deps.chain.readSlot();
|
|
259
|
+
const encodeReceipt = (signed) => {
|
|
260
|
+
const encoded = Buffer.from(JSON.stringify(signed), "utf8").toString("base64url");
|
|
261
|
+
return encoded.length <= MAX_RECEIPT_HEADER_CHARS ? encoded : undefined;
|
|
262
|
+
};
|
|
263
|
+
/** The receipt's session block for `state`, the totals after this call. */
|
|
264
|
+
function receiptSession(state, call, previousReceiptHash, closed) {
|
|
265
|
+
return {
|
|
266
|
+
escrow: state.escrow,
|
|
267
|
+
payer: state.payer,
|
|
268
|
+
network: config.network,
|
|
269
|
+
currency: terms.price.currency,
|
|
270
|
+
mint: terms.mint.toBase58(),
|
|
271
|
+
maxAmount: state.maxBaseUnits,
|
|
272
|
+
sequence: String(state.sequence),
|
|
273
|
+
inputTokens: String(call.inputTokens),
|
|
274
|
+
outputTokens: String(call.outputTokens),
|
|
275
|
+
cumulativeInputTokens: String(state.inputTokens),
|
|
276
|
+
cumulativeOutputTokens: String(state.outputTokens),
|
|
277
|
+
cumulativeCost: state.costBaseUnits,
|
|
278
|
+
...(previousReceiptHash ? { previousReceiptHash } : {}),
|
|
279
|
+
closed,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** What a buyer is told about a session. */
|
|
283
|
+
function sessionSummary(state) {
|
|
284
|
+
return {
|
|
285
|
+
escrow: state.escrow,
|
|
286
|
+
sequence: state.sequence,
|
|
287
|
+
cumulativeInputTokens: state.inputTokens,
|
|
288
|
+
cumulativeOutputTokens: state.outputTokens,
|
|
289
|
+
cumulativeCost: baseUnitsToDecimal(BigInt(state.costBaseUnits), decimals),
|
|
290
|
+
cumulativeCostBaseUnits: state.costBaseUnits,
|
|
291
|
+
maxCharge: baseUnitsToDecimal(BigInt(state.maxBaseUnits), decimals),
|
|
292
|
+
maxChargeBaseUnits: state.maxBaseUnits,
|
|
293
|
+
currency: terms.price.currency,
|
|
294
|
+
status: state.status,
|
|
295
|
+
settled: state.status === "settled",
|
|
296
|
+
...(state.settleSignature ? { settleSignature: state.settleSignature } : {}),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
// Delegations proved by a memo in the lock transaction are read from the chain only when the operator opted in.
|
|
300
|
+
// A confirmed transaction never changes, so its facts are kept (bounded); a transaction not found yet is remembered briefly,
|
|
301
|
+
// so repeated requests naming the same signature cost one read.
|
|
302
|
+
const factsCache = new Map();
|
|
303
|
+
const FACTS_CACHE_SIZE = 1_000;
|
|
304
|
+
const NOT_FOUND_MS = 5_000;
|
|
305
|
+
const readTransaction = config.lockBoundDelegations && deps.chain.readTransactionFacts
|
|
306
|
+
? async (signature) => {
|
|
307
|
+
const kept = factsCache.get(signature);
|
|
308
|
+
if (kept && kept.until > Date.now()) {
|
|
309
|
+
factsCache.delete(signature);
|
|
310
|
+
factsCache.set(signature, kept);
|
|
311
|
+
return kept.facts;
|
|
312
|
+
}
|
|
313
|
+
const facts = await deps.chain.readTransactionFacts(signature);
|
|
314
|
+
// The lock's slot is what ties the memo to this escrow's lock and no earlier one at the same address: no slot, no answer.
|
|
315
|
+
if (facts && facts.slot === undefined)
|
|
316
|
+
throw new Error("the transaction's slot was not reported");
|
|
317
|
+
factsCache.delete(signature);
|
|
318
|
+
factsCache.set(signature, { facts, until: facts ? Number.POSITIVE_INFINITY : Date.now() + NOT_FOUND_MS });
|
|
319
|
+
while (factsCache.size > FACTS_CACHE_SIZE)
|
|
320
|
+
factsCache.delete(factsCache.keys().next().value);
|
|
321
|
+
return facts;
|
|
322
|
+
}
|
|
323
|
+
: undefined;
|
|
324
|
+
/**
|
|
325
|
+
* Checks that a paid request (a session request or a single call) is signed by a key the escrow's payer delegated to (security review S-1, #866).
|
|
326
|
+
* With `lockBoundDelegations`, the payer's consent may instead be a memo it signed in the lock transaction (#925).
|
|
327
|
+
*/
|
|
328
|
+
/** A delegation proved by a lock transaction counts only for the lock that transaction made: a lock made again at the same address is another lock. */
|
|
329
|
+
function lockSlotMismatch(auth, createdSlot) {
|
|
330
|
+
if (auth.lockSlot === undefined || auth.lockSlot === createdSlot)
|
|
331
|
+
return undefined;
|
|
332
|
+
return refuse(401, "session_auth_invalid", "The delegation was given in the transaction of another lock at this address. Delegate for this lock.", { charged: false });
|
|
333
|
+
}
|
|
334
|
+
async function sessionAuth(request, action, escrow, payer, sequence, body) {
|
|
335
|
+
const auth = await verifySessionRequestWithTransactions({ headers: request.headers, genesisHash: signingGenesisHash, action, escrow, payer, provider: terms.payee, sequence, body, nowMs: nowMs(), ...(readTransaction ? { readTransaction } : {}) });
|
|
336
|
+
if (auth.ok)
|
|
337
|
+
return { ok: true, sessionKey: auth.sessionKey, ...(auth.lockSlot !== undefined ? { lockSlot: auth.lockSlot } : {}) };
|
|
338
|
+
if (auth.reason === "payment_check_unavailable")
|
|
339
|
+
return { ok: false, response: refuse(503, auth.reason, auth.message, { charged: false }) };
|
|
340
|
+
return { ok: false, response: refuse(401, auth.reason, auth.message, { charged: false }) };
|
|
341
|
+
}
|
|
342
|
+
/** A session request signed by another key than the one the session started with. */
|
|
343
|
+
function keyMismatch(escrow, sessionKey) {
|
|
344
|
+
const state = deps.sessions?.get(escrow);
|
|
345
|
+
return state && state.sessionKey !== sessionKey ? refuse(409, "session_key_mismatch", "This session was started with another session key. Sign with the key it was started with.", { charged: false }) : undefined;
|
|
346
|
+
}
|
|
347
|
+
async function sessionCall(c) {
|
|
348
|
+
const ledger = deps.sessions;
|
|
349
|
+
const escrow = c.header.escrow.toBase58();
|
|
350
|
+
// Before the lock is read: the escrow, payer and nonce are public, so only a signature shows the payer is calling.
|
|
351
|
+
// A call that asks to close the session is signed as such, so the close cannot be added or removed in transit.
|
|
352
|
+
const auth = await sessionAuth(c, sessionCallAction(c.close), c.header.escrow, c.header.payer, c.sequence, c.requestText);
|
|
353
|
+
if (!auth.ok)
|
|
354
|
+
return auth.response;
|
|
355
|
+
const mismatch = keyMismatch(escrow, auth.sessionKey);
|
|
356
|
+
if (mismatch)
|
|
357
|
+
return mismatch;
|
|
358
|
+
let lock;
|
|
359
|
+
try {
|
|
360
|
+
lock = await verifyMeteredLock({ header: c.header, terms, minimum: c.minimum, readAccount, readSlot, replayStore: deps.replayStore, purpose: "session-call" });
|
|
361
|
+
}
|
|
362
|
+
catch {
|
|
363
|
+
return refuse(503, "payment_check_unavailable", "The lock could not be checked. Nothing was charged for this call; send it again.", { charged: false });
|
|
364
|
+
}
|
|
365
|
+
if (!lock.ok) {
|
|
366
|
+
if (lock.reason === "payment_check_unavailable")
|
|
367
|
+
clusterConfirmed = false;
|
|
368
|
+
// No more calls fit before the refund window opens: settle what was served while there is time.
|
|
369
|
+
if (lock.reason === "session_window_closing" && ledger.get(escrow))
|
|
370
|
+
void settleSession(escrow).catch(() => undefined);
|
|
371
|
+
const status = lock.reason === "payment_check_unavailable" || lock.reason === "provider_not_ready" ? 503 : lock.reason === "duplicate_nonce" || lock.reason === "session_window_closing" ? 409 : 402;
|
|
372
|
+
return refuse(status, lock.reason, lock.message, { charged: false });
|
|
373
|
+
}
|
|
374
|
+
const otherLock = lockSlotMismatch(auth, lock.createdSlot);
|
|
375
|
+
if (otherLock)
|
|
376
|
+
return otherLock;
|
|
377
|
+
let begun;
|
|
378
|
+
try {
|
|
379
|
+
begun = await ledger.begin({ lock, escrow: c.header.escrow, sequence: c.sequence, sessionKey: auth.sessionKey, worstCase: c.worstCase, replayStore: deps.replayStore, nowMs: nowMs() });
|
|
380
|
+
}
|
|
381
|
+
catch {
|
|
382
|
+
return refuse(503, "payment_check_unavailable", "The session could not be recorded. Nothing was charged for this call; send it again.", { charged: false });
|
|
383
|
+
}
|
|
384
|
+
if (!begun.ok) {
|
|
385
|
+
const current = ledger.get(escrow);
|
|
386
|
+
return refuse(begun.reason === "session_max_reached" ? 402 : 409, begun.reason, begun.message, { charged: false, ...(current ? { session: sessionSummary(current) } : {}) });
|
|
387
|
+
}
|
|
388
|
+
const reservation = begun.reservation;
|
|
389
|
+
const requestId = randomUUID();
|
|
390
|
+
let upstream;
|
|
391
|
+
try {
|
|
392
|
+
upstream = await deps.upstream.createChatCompletion({ model: config.upstream.model, messages: c.upstreamMessages, ...(c.temperature === undefined ? {} : { temperature: c.temperature }), max_tokens: c.worstCase.outputTokens });
|
|
393
|
+
}
|
|
394
|
+
catch (error) {
|
|
395
|
+
ledger.release(reservation);
|
|
396
|
+
log({ event: "upstream_failed", requestId, escrow, sequence: c.sequence, detail: error instanceof Error ? error.message : "unknown" });
|
|
397
|
+
return refuse(502, "model_unavailable", `The model did not answer. Nothing was charged for this call; the session stays open and call ${c.sequence} can be sent again.`, { charged: false, escrow });
|
|
398
|
+
}
|
|
399
|
+
const usage = usageFrom(upstream, c.worstCase.inputTokens);
|
|
400
|
+
const next = ledger.preview(reservation, usage);
|
|
401
|
+
const reddi = {
|
|
402
|
+
requestId,
|
|
403
|
+
provider: config.wallet,
|
|
404
|
+
model: config.model,
|
|
405
|
+
metered: {
|
|
406
|
+
inputTokens: usage.inputTokens,
|
|
407
|
+
outputTokens: usage.outputTokens,
|
|
408
|
+
currency: terms.price.currency,
|
|
409
|
+
session: { ...sessionSummary({ ...next, status: "open" }), ...(reservation.before.lastReceiptHash ? { previousReceiptHash: reservation.before.lastReceiptHash } : {}), closeRequested: c.close },
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
const responseText = JSON.stringify({ ...upstream, reddi });
|
|
413
|
+
let encoded;
|
|
414
|
+
let receiptHash;
|
|
415
|
+
try {
|
|
416
|
+
const signed = await signReddiReceiptV2({
|
|
417
|
+
schemaVersion: "reddi.receipt.v2",
|
|
418
|
+
providerId: config.wallet,
|
|
419
|
+
declaredModel: config.model,
|
|
420
|
+
requestHash: sha256Hex(c.requestText),
|
|
421
|
+
responseHash: sha256Hex(responseText),
|
|
422
|
+
session: receiptSession(next, usage, reservation.before.lastReceiptHash, false),
|
|
423
|
+
issuedAt: issuedAt(),
|
|
424
|
+
}, deps.signMessage);
|
|
425
|
+
encoded = encodeReceipt(signed);
|
|
426
|
+
receiptHash = hashReddiReceiptV2(signed.receipt);
|
|
427
|
+
}
|
|
428
|
+
catch {
|
|
429
|
+
encoded = undefined;
|
|
430
|
+
}
|
|
431
|
+
if (!encoded || !receiptHash) {
|
|
432
|
+
// A session call is billed through its receipt chain, so a call without a receipt is not billed or answered.
|
|
433
|
+
ledger.release(reservation);
|
|
434
|
+
log({ event: "receipt_failed", requestId, escrow, sequence: c.sequence });
|
|
435
|
+
return refuse(500, "receipt_failed", `This call's receipt could not be signed, so its answer is withheld. Nothing was charged for it; call ${c.sequence} can be sent again.`, { charged: false, escrow });
|
|
436
|
+
}
|
|
437
|
+
let recorded;
|
|
438
|
+
try {
|
|
439
|
+
recorded = await ledger.record(reservation, usage, receiptHash, nowMs());
|
|
440
|
+
}
|
|
441
|
+
catch {
|
|
442
|
+
log({ event: "session_record_failed", requestId, escrow, sequence: c.sequence });
|
|
443
|
+
return refuse(503, "session_record_failed", `This call could not be recorded, so its answer is withheld. Nothing was charged for it; call ${c.sequence} can be sent again.`, { charged: false, escrow });
|
|
444
|
+
}
|
|
445
|
+
log({ event: "session_call", requestId, escrow, sequence: c.sequence, inputTokens: usage.inputTokens, outputTokens: usage.outputTokens, cumulativeCost: recorded.state.costBaseUnits, full: recorded.full });
|
|
446
|
+
const headers = { ...JSON_HEADERS, [PROVIDER_RECEIPT_HEADER]: encoded };
|
|
447
|
+
if (c.close || recorded.full) {
|
|
448
|
+
const closing = await settleSession(escrow, requestId);
|
|
449
|
+
headers[SESSION_STATE_HEADER] = closing.status;
|
|
450
|
+
if (closing.receipt)
|
|
451
|
+
headers[SESSION_RECEIPT_HEADER] = closing.receipt;
|
|
452
|
+
}
|
|
453
|
+
return new Response(responseText, { status: 200, headers });
|
|
454
|
+
}
|
|
455
|
+
const settling = new Set();
|
|
456
|
+
/** The signed closing receipt of a settled session and the summary its response hash covers. */
|
|
457
|
+
async function closingReceipt(state, outcome) {
|
|
458
|
+
if (!outcome.confirmed.ok || !outcome.settleSignature)
|
|
459
|
+
return undefined;
|
|
460
|
+
const confirmed = outcome.confirmed;
|
|
461
|
+
const closingState = { ...state, sequence: state.sequence + 1 };
|
|
462
|
+
const summary = JSON.stringify({
|
|
463
|
+
escrow: state.escrow,
|
|
464
|
+
settleSignature: outcome.settleSignature,
|
|
465
|
+
charged: baseUnitsToDecimal(confirmed.paidBaseUnits, decimals),
|
|
466
|
+
fee: baseUnitsToDecimal(confirmed.feeBaseUnits, decimals),
|
|
467
|
+
provider: baseUnitsToDecimal(confirmed.providerBaseUnits, decimals),
|
|
468
|
+
refund: baseUnitsToDecimal(confirmed.refundedBaseUnits, decimals),
|
|
469
|
+
currency: terms.price.currency,
|
|
470
|
+
cumulativeInputTokens: state.inputTokens,
|
|
471
|
+
cumulativeOutputTokens: state.outputTokens,
|
|
472
|
+
calls: state.sequence,
|
|
473
|
+
});
|
|
474
|
+
try {
|
|
475
|
+
const signed = await signReddiReceiptV2({
|
|
476
|
+
schemaVersion: "reddi.receipt.v2",
|
|
477
|
+
providerId: config.wallet,
|
|
478
|
+
declaredModel: config.model,
|
|
479
|
+
requestHash: sha256Hex(`session-close:${state.escrow}:${closingState.sequence}`),
|
|
480
|
+
responseHash: sha256Hex(summary),
|
|
481
|
+
payment: {
|
|
482
|
+
network: config.network,
|
|
483
|
+
txSignature: outcome.settleSignature,
|
|
484
|
+
currency: terms.price.currency,
|
|
485
|
+
mint: terms.mint.toBase58(),
|
|
486
|
+
amount: confirmed.paidBaseUnits.toString(),
|
|
487
|
+
fee: confirmed.feeBaseUnits > 0n ? { amount: confirmed.feeBaseUnits.toString(), treasury: ESCROW_PROTOCOL_TREASURY.toBase58() } : { amount: "0" },
|
|
488
|
+
payer: state.payer,
|
|
489
|
+
settlement: "metered-escrow",
|
|
490
|
+
metered: { inputTokens: String(state.inputTokens), outputTokens: String(state.outputTokens), maxAmount: state.maxBaseUnits, refunded: confirmed.refundedBaseUnits.toString() },
|
|
491
|
+
},
|
|
492
|
+
session: receiptSession(closingState, { inputTokens: 0, outputTokens: 0 }, state.lastReceiptHash, true),
|
|
493
|
+
issuedAt: issuedAt(),
|
|
494
|
+
}, deps.signMessage);
|
|
495
|
+
const receipt = encodeReceipt(signed);
|
|
496
|
+
return receipt ? { receipt, summary } : undefined;
|
|
497
|
+
}
|
|
498
|
+
catch {
|
|
499
|
+
return undefined;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Ends a session: stops new calls, then settles the ledger's total (or, when
|
|
504
|
+
* no call was recorded, declines the lock so the buyer gets it all back).
|
|
505
|
+
* `pending` means it is not finished and will be tried again: a call is
|
|
506
|
+
* running, the chain could not be read, or a settle was sent and its outcome
|
|
507
|
+
* is not known yet. A session counts as settled only when its own recorded
|
|
508
|
+
* settle signature has landed.
|
|
509
|
+
*/
|
|
510
|
+
async function settleSession(escrow, requestId = randomUUID()) {
|
|
511
|
+
const ledger = deps.sessions;
|
|
512
|
+
if (!ledger)
|
|
513
|
+
return { status: "none" };
|
|
514
|
+
if (settling.has(escrow))
|
|
515
|
+
return { status: "pending" };
|
|
516
|
+
settling.add(escrow);
|
|
517
|
+
try {
|
|
518
|
+
const state = await ledger.close(escrow).catch(() => undefined);
|
|
519
|
+
if (!state)
|
|
520
|
+
return { status: ledger.get(escrow) ? "pending" : "none" };
|
|
521
|
+
const kept = state.closingReceipt;
|
|
522
|
+
if (state.status === "settled" || state.status === "declined" || state.status === "refunded_unpaid")
|
|
523
|
+
return { status: state.status, state, ...(kept?.receipt ? { receipt: kept.receipt } : {}) };
|
|
524
|
+
if (!clusterConfirmed) {
|
|
525
|
+
const cluster = await checkProviderCluster(() => deps.chain.readGenesisHash(), config.network, config.genesisHash);
|
|
526
|
+
if (!cluster.ok)
|
|
527
|
+
return { status: "pending", state };
|
|
528
|
+
clusterConfirmed = true;
|
|
529
|
+
}
|
|
530
|
+
const header = sessionPaymentHeader(state);
|
|
531
|
+
const record = (pending) => ledger.markSettling(escrow, pending);
|
|
532
|
+
const waiting = (reason) => {
|
|
533
|
+
// The operator should know: a session that cannot settle is revenue at risk once the refund window opens.
|
|
534
|
+
log({ event: "session_settle_waiting", escrow, reason, cumulativeCost: state.costBaseUnits, alert: true });
|
|
535
|
+
return { status: "pending", state };
|
|
536
|
+
};
|
|
537
|
+
// A settle sent earlier whose outcome was not known: it alone can count as this session's settle.
|
|
538
|
+
if (state.pendingSettle) {
|
|
539
|
+
const pending = state.pendingSettle;
|
|
540
|
+
const where = await deps.chain.signatureState(pending.signature, pending.lastValidBlockHeight);
|
|
541
|
+
if (where === "unknown") {
|
|
542
|
+
// Send the same signed transaction again; it lands at most once.
|
|
543
|
+
await deps.chain.sendSigned({ signature: pending.signature, transaction: pending.transaction, lastValidBlockHeight: pending.lastValidBlockHeight }).catch(() => undefined);
|
|
544
|
+
const again = await deps.chain.signatureState(pending.signature, pending.lastValidBlockHeight);
|
|
545
|
+
if (again === "unknown")
|
|
546
|
+
return waiting("settle_outcome_unknown");
|
|
547
|
+
if (again === "landed")
|
|
548
|
+
return finishSettled(state, await confirmPending(state, pending), requestId);
|
|
549
|
+
await record(undefined).catch(() => undefined);
|
|
550
|
+
}
|
|
551
|
+
else if (where === "landed") {
|
|
552
|
+
return finishSettled(state, await confirmPending(state, pending), requestId);
|
|
553
|
+
}
|
|
554
|
+
else {
|
|
555
|
+
await record(undefined).catch(() => undefined);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
let lock;
|
|
559
|
+
// Creating the buyer's account for the unused part is paid by the provider, within the operator's daily bound.
|
|
560
|
+
const reserved = subsidyLeft();
|
|
561
|
+
if (reserved)
|
|
562
|
+
subsidy.used += 1;
|
|
563
|
+
try {
|
|
564
|
+
lock = await verifyMeteredLock({ header, terms, minimum: 0n, readAccount, readSlot, replayStore: deps.replayStore, purpose: "session-settle", createRefundAccount: reserved });
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
if (reserved)
|
|
568
|
+
subsidy.used = Math.max(0, subsidy.used - 1);
|
|
569
|
+
return waiting("payment_check_unavailable");
|
|
570
|
+
}
|
|
571
|
+
if (reserved && !(lock.ok && lock.payout.createRefundAccount))
|
|
572
|
+
subsidy.used = Math.max(0, subsidy.used - 1);
|
|
573
|
+
if (lock.ok && lock.payout.createRefundAccount)
|
|
574
|
+
log({ event: "refund_account_created", requestId, escrow, account: lock.payout.refundTo.toBase58() });
|
|
575
|
+
if (!lock.ok && lock.reason === "refund_account_unusable" && !reserved)
|
|
576
|
+
log({ event: "refund_account_subsidy_spent", escrow, alert: true });
|
|
577
|
+
if (!lock.ok) {
|
|
578
|
+
// The escrow is no longer locked. No settle of this session landed (that was checked above), so the buyer refunded it.
|
|
579
|
+
if ((await escrowState(header.escrow)) === "closed") {
|
|
580
|
+
const ended = BigInt(state.costBaseUnits) > 0n ? "refunded_unpaid" : "declined";
|
|
581
|
+
log({ event: ended === "refunded_unpaid" ? "session_refunded_unpaid" : "session_lock_gone", escrow, cumulativeCost: state.costBaseUnits, ...(ended === "refunded_unpaid" ? { alert: true } : {}) });
|
|
582
|
+
await ledger.finish(escrow, { status: ended }).catch(() => undefined);
|
|
583
|
+
return { status: ended, state };
|
|
584
|
+
}
|
|
585
|
+
if (lock.reason === "payment_check_unavailable")
|
|
586
|
+
clusterConfirmed = false;
|
|
587
|
+
return waiting(lock.reason);
|
|
588
|
+
}
|
|
589
|
+
// The lock at this address must be the one the session was opened on, not a later one made with the same nonce.
|
|
590
|
+
if (!lockMatchesSession(lock, state)) {
|
|
591
|
+
log({ event: "session_lock_replaced", escrow, alert: true });
|
|
592
|
+
const ended = BigInt(state.costBaseUnits) > 0n ? "refunded_unpaid" : "declined";
|
|
593
|
+
await ledger.finish(escrow, { status: ended }).catch(() => undefined);
|
|
594
|
+
return { status: ended, state };
|
|
595
|
+
}
|
|
596
|
+
if (BigInt(state.costBaseUnits) === 0n) {
|
|
597
|
+
try {
|
|
598
|
+
const signature = await deps.chain.sendInstructions([meteredDecline(terms, lock)]);
|
|
599
|
+
await ledger.finish(escrow, { status: "declined", signature });
|
|
600
|
+
log({ event: "session_declined", escrow, signature });
|
|
601
|
+
return { status: "declined", state };
|
|
602
|
+
}
|
|
603
|
+
catch {
|
|
604
|
+
return { status: "pending", state };
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
const outcome = await settleLock(lock, header.escrow, requestId, (payout) => sessionSettlement(terms, lock, state, payout), record);
|
|
608
|
+
if (outcome.ok === "pending")
|
|
609
|
+
return waiting("settle_outcome_unknown");
|
|
610
|
+
if (outcome.ok === "closed") {
|
|
611
|
+
const ended = BigInt(state.costBaseUnits) > 0n ? "refunded_unpaid" : "declined";
|
|
612
|
+
log({ event: "session_refunded_unpaid", escrow, cumulativeCost: state.costBaseUnits, alert: true });
|
|
613
|
+
await ledger.finish(escrow, { status: ended }).catch(() => undefined);
|
|
614
|
+
return { status: ended, state };
|
|
615
|
+
}
|
|
616
|
+
if (!outcome.ok) {
|
|
617
|
+
log({ event: "session_settle_failed", escrow, alert: true });
|
|
618
|
+
return { status: "pending", state };
|
|
619
|
+
}
|
|
620
|
+
return finishSettled(state, outcome, requestId);
|
|
621
|
+
}
|
|
622
|
+
finally {
|
|
623
|
+
settling.delete(escrow);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
/** Reads back a session's recorded settle once it is known to have landed. */
|
|
627
|
+
async function confirmPending(state, pending) {
|
|
628
|
+
let confirmed = { ok: false, reason: "not_found" };
|
|
629
|
+
try {
|
|
630
|
+
confirmed = confirmMeteredSettlement(await deps.chain.readSettlement(pending.signature), {
|
|
631
|
+
programId: terms.programId,
|
|
632
|
+
escrow: new PublicKey(state.escrow),
|
|
633
|
+
mint: terms.mint,
|
|
634
|
+
destination: new PublicKey(pending.destination),
|
|
635
|
+
treasuryToken: new PublicKey(pending.treasuryToken),
|
|
636
|
+
refundTo: new PublicKey(pending.refundTo),
|
|
637
|
+
maxBaseUnits: BigInt(state.maxBaseUnits),
|
|
638
|
+
instruction: pending.instruction,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
confirmed = { ok: false, reason: "not_found" };
|
|
643
|
+
}
|
|
644
|
+
return { ok: true, settleSignature: pending.signature, confirmed };
|
|
645
|
+
}
|
|
646
|
+
async function finishSettled(state, outcome, requestId) {
|
|
647
|
+
const ledger = deps.sessions;
|
|
648
|
+
const closing = await closingReceipt(state, outcome);
|
|
649
|
+
if (!closing)
|
|
650
|
+
log({ event: "receipt_withheld", requestId, escrow: state.escrow, settleSignature: outcome.settleSignature, reason: outcome.confirmed.ok ? "not_signed" : outcome.confirmed.reason });
|
|
651
|
+
await ledger.finish(state.escrow, { status: "settled", signature: outcome.settleSignature, ...(closing ? { closingReceipt: closing } : {}) }).catch(() => undefined);
|
|
652
|
+
log({ event: "session_settled", requestId, escrow: state.escrow, calls: state.sequence, charged: state.costBaseUnits, settleSignature: outcome.settleSignature, confirmed: outcome.confirmed.ok, receipt: closing !== undefined });
|
|
653
|
+
return { status: "settled", state, ...(closing ? { receipt: closing.receipt } : {}) };
|
|
654
|
+
}
|
|
655
|
+
/** Settles every session that is closing, idle, or near its refund window. The server calls this on a timer. */
|
|
656
|
+
async function settleDueSessions() {
|
|
657
|
+
await reconcilePendingCalls().catch(() => undefined);
|
|
658
|
+
const ledger = deps.sessions;
|
|
659
|
+
if (!ledger)
|
|
660
|
+
return [];
|
|
661
|
+
let slot = 0n;
|
|
662
|
+
try {
|
|
663
|
+
slot = BigInt(await deps.chain.readSlot());
|
|
664
|
+
}
|
|
665
|
+
catch {
|
|
666
|
+
// Without the slot, only closing and idle sessions are found; a near window is caught next time.
|
|
667
|
+
}
|
|
668
|
+
const ended = [];
|
|
669
|
+
for (const state of ledger.due(nowMs(), slot, config.sessions.idleMs))
|
|
670
|
+
ended.push(await settleSession(state.escrow));
|
|
671
|
+
return ended;
|
|
672
|
+
}
|
|
673
|
+
async function closeRequest(request) {
|
|
674
|
+
const header = readMeteredPaymentHeader(request.headers);
|
|
675
|
+
if (!header || "error" in header)
|
|
676
|
+
return refuse(400, "invalid_receipt", "Name the session's lock in x402-payment.");
|
|
677
|
+
if (!deps.sessions)
|
|
678
|
+
return refuse(400, "sessions_not_offered", "This provider settles each call on its own.");
|
|
679
|
+
if (!tokenEscrowAddresses({ programId: terms.programId, payer: header.payer, nonce: header.nonce }).escrow.equals(header.escrow)) {
|
|
680
|
+
return refuse(400, "invalid_receipt", "The escrow address is not the one this payer and nonce give.");
|
|
681
|
+
}
|
|
682
|
+
const escrow = header.escrow.toBase58();
|
|
683
|
+
const auth = await sessionAuth(request, "close", header.escrow, header.payer, 0, await request.text().catch(() => ""));
|
|
684
|
+
if (!auth.ok)
|
|
685
|
+
return auth.response;
|
|
686
|
+
if (!deps.sessions.get(escrow))
|
|
687
|
+
return refuse(404, "session_not_found", "No session is open on this lock.");
|
|
688
|
+
const mismatch = keyMismatch(escrow, auth.sessionKey);
|
|
689
|
+
if (mismatch)
|
|
690
|
+
return mismatch;
|
|
691
|
+
const end = await settleSession(escrow);
|
|
692
|
+
if (end.status === "none")
|
|
693
|
+
return refuse(404, "session_not_found", "No session is open on this lock.");
|
|
694
|
+
const state = deps.sessions.get(escrow);
|
|
695
|
+
return json(end.status === "pending" ? 202 : 200, { ok: end.status !== "pending", status: end.status, session: state ? sessionSummary(state) : undefined }, end.receipt ? { [SESSION_RECEIPT_HEADER]: end.receipt } : {});
|
|
696
|
+
}
|
|
697
|
+
async function sessionRead(request, escrowText) {
|
|
698
|
+
if (!deps.sessions)
|
|
699
|
+
return refuse(404, "session_not_found", "This provider has no sessions.");
|
|
700
|
+
let escrow;
|
|
701
|
+
try {
|
|
702
|
+
escrow = new PublicKey(escrowText).toBase58();
|
|
703
|
+
}
|
|
704
|
+
catch {
|
|
705
|
+
return refuse(400, "invalid_request", "Name the escrow by its address.");
|
|
706
|
+
}
|
|
707
|
+
const state = deps.sessions.get(escrow);
|
|
708
|
+
if (!state)
|
|
709
|
+
return refuse(404, "session_not_found", "No session on that escrow.");
|
|
710
|
+
// Only the payer's session key may read the totals.
|
|
711
|
+
const auth = await sessionAuth(request, "read", new PublicKey(escrow), new PublicKey(state.payer), 0, "");
|
|
712
|
+
if (!auth.ok)
|
|
713
|
+
return auth.response;
|
|
714
|
+
const mismatch = keyMismatch(escrow, auth.sessionKey);
|
|
715
|
+
if (mismatch)
|
|
716
|
+
return mismatch;
|
|
717
|
+
const kept = state.closingReceipt;
|
|
718
|
+
return json(200, { session: sessionSummary(state), ...(kept?.receipt ? { closing: { summary: kept.summary, receipt: kept.receipt } } : {}) });
|
|
719
|
+
}
|
|
720
|
+
async function paidChat(request) {
|
|
721
|
+
if (config.paused) {
|
|
722
|
+
return refuse(503, "currency_paused", `This provider is not taking new payments in ${terms.price.currency} for now. Nothing was accepted; a lock you already made can be refunded once its refund window opens.`, { charged: false });
|
|
723
|
+
}
|
|
724
|
+
const lengthHeader = Number(request.headers.get("content-length") ?? "0");
|
|
725
|
+
if (lengthHeader > MAX_BODY_BYTES)
|
|
726
|
+
return refuse(413, "request_too_large", "The request body is too large.");
|
|
727
|
+
const requestText = await request.text().catch(() => "");
|
|
728
|
+
if (Buffer.byteLength(requestText, "utf8") > MAX_BODY_BYTES)
|
|
729
|
+
return refuse(413, "request_too_large", "The request body is too large.");
|
|
730
|
+
let body;
|
|
731
|
+
try {
|
|
732
|
+
const parsed = JSON.parse(requestText);
|
|
733
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
734
|
+
throw new Error("shape");
|
|
735
|
+
body = parsed;
|
|
736
|
+
}
|
|
737
|
+
catch {
|
|
738
|
+
return refuse(400, "invalid_request", "Send the request as a JSON object.");
|
|
739
|
+
}
|
|
740
|
+
const messages = readMessages(body.messages);
|
|
741
|
+
if (!messages)
|
|
742
|
+
return refuse(400, "invalid_request", "messages must be a list of { role, content } with text content.");
|
|
743
|
+
if (body.stream === true)
|
|
744
|
+
return refuse(400, "streaming_not_supported", "This provider does not stream. Send the request without stream.");
|
|
745
|
+
const requestedMax = typeof body.max_tokens === "number" ? body.max_tokens : typeof body.max_completion_tokens === "number" ? body.max_completion_tokens : undefined;
|
|
746
|
+
const temperature = typeof body.temperature === "number" && Number.isFinite(body.temperature) ? body.temperature : undefined;
|
|
747
|
+
// What the model will actually be sent. The quote and the minimum lock are
|
|
748
|
+
// worked out on this, so a system prompt's tokens are priced in up front.
|
|
749
|
+
const upstreamMessages = config.systemPrompt ? [{ role: "system", content: config.systemPrompt }, ...messages.filter((m) => m.role !== "system")] : messages;
|
|
750
|
+
const offer = meteredOffer(terms, upstreamMessages, requestedMax, config.network);
|
|
751
|
+
const header = readMeteredPaymentHeader(request.headers);
|
|
752
|
+
if (header === undefined) {
|
|
753
|
+
return refuse(402, "payment_required", "Lock at least the minimum in a metered escrow payable to this provider, then repeat the request with the lock in x402-payment.", { metered: offer }, { "x402-request": JSON.stringify(offer) });
|
|
754
|
+
}
|
|
755
|
+
if ("error" in header)
|
|
756
|
+
return refuse(402, "invalid_receipt", header.error, { metered: offer });
|
|
757
|
+
if (!clusterConfirmed) {
|
|
758
|
+
const cluster = await checkProviderCluster(() => deps.chain.readGenesisHash(), config.network, config.genesisHash);
|
|
759
|
+
if (!cluster.ok) {
|
|
760
|
+
log({ event: "cluster_check_failed", reason: cluster.reason });
|
|
761
|
+
return refuse(503, cluster.reason, cluster.reason === "wrong_cluster" ? "This provider's chain connection is misconfigured. Nothing was accepted." : cluster.message, { charged: false });
|
|
762
|
+
}
|
|
763
|
+
clusterConfirmed = true;
|
|
764
|
+
}
|
|
765
|
+
const outputTokens = outputLimit(terms, requestedMax);
|
|
766
|
+
const inputEstimate = estimateInputTokens(upstreamMessages);
|
|
767
|
+
const minimum = tokenCostBaseUnits(terms.price, { inputTokens: inputEstimate, outputTokens });
|
|
768
|
+
const sessionHeaders = readSessionHeaders(request.headers);
|
|
769
|
+
if (sessionHeaders !== undefined) {
|
|
770
|
+
if ("error" in sessionHeaders)
|
|
771
|
+
return refuse(400, "session_invalid", sessionHeaders.error, { charged: false });
|
|
772
|
+
if (!deps.sessions)
|
|
773
|
+
return refuse(400, "sessions_not_offered", "This provider settles each call on its own. Send the call without x402-session-sequence.", { charged: false });
|
|
774
|
+
return sessionCall({ header, sequence: sessionHeaders.sequence, close: sessionHeaders.close, requestText, headers: request.headers, upstreamMessages, temperature, worstCase: { inputTokens: inputEstimate, outputTokens }, minimum });
|
|
775
|
+
}
|
|
776
|
+
// The lock's escrow, payer and nonce are public: only the payer's signature shows who is calling (#866).
|
|
777
|
+
const auth = await sessionAuth(request, "single", header.escrow, header.payer, 0, requestText);
|
|
778
|
+
if (!auth.ok)
|
|
779
|
+
return auth.response;
|
|
780
|
+
// A call whose settle was sent but not yet known to land: the same request collects its answer.
|
|
781
|
+
// One look at a held settle per lock at a time; a second retry waits for it.
|
|
782
|
+
if (answering.has(header.escrow.toBase58()))
|
|
783
|
+
return refuse(503, "settle_pending", "This lock's settle is already being checked. Try again shortly.", { charged: "unknown" }, { "retry-after": "10" });
|
|
784
|
+
answering.add(header.escrow.toBase58());
|
|
785
|
+
try {
|
|
786
|
+
const held = await collectHeld(header.escrow.toBase58(), requestText);
|
|
787
|
+
if (held)
|
|
788
|
+
return held;
|
|
789
|
+
}
|
|
790
|
+
finally {
|
|
791
|
+
answering.delete(header.escrow.toBase58());
|
|
792
|
+
}
|
|
793
|
+
let lock;
|
|
794
|
+
try {
|
|
795
|
+
lock = await verifyMeteredLock({ header, terms, minimum, readAccount: (address) => deps.chain.readAccount(address), readSlot: () => deps.chain.readSlot(), replayStore: deps.replayStore });
|
|
796
|
+
}
|
|
797
|
+
catch {
|
|
798
|
+
// The replay store could not record the escrow, so it cannot be accepted.
|
|
799
|
+
return refuse(503, "payment_check_unavailable", "The payment could not be recorded. Nothing was accepted; present the same lock again.", { charged: false });
|
|
800
|
+
}
|
|
801
|
+
if (!lock.ok) {
|
|
802
|
+
if (lock.reason === "payment_check_unavailable")
|
|
803
|
+
clusterConfirmed = false;
|
|
804
|
+
const status = lock.reason === "payment_check_unavailable" || lock.reason === "provider_not_ready" ? 503 : lock.reason === "duplicate_nonce" ? 409 : 402;
|
|
805
|
+
if (lock.reason === "provider_not_ready")
|
|
806
|
+
log({ event: "payout_not_ready", escrow: header.escrow.toBase58() });
|
|
807
|
+
return refuse(status, lock.reason, lock.message, { metered: offer, charged: false });
|
|
808
|
+
}
|
|
809
|
+
const otherLock = lockSlotMismatch(auth, lock.createdSlot);
|
|
810
|
+
if (otherLock)
|
|
811
|
+
return otherLock;
|
|
812
|
+
const escrow = header.escrow.toBase58();
|
|
813
|
+
const requestId = randomUUID();
|
|
814
|
+
let upstream;
|
|
815
|
+
try {
|
|
816
|
+
upstream = await deps.upstream.createChatCompletion({ model: config.upstream.model, messages: upstreamMessages, ...(temperature === undefined ? {} : { temperature }), max_tokens: outputTokens });
|
|
817
|
+
}
|
|
818
|
+
catch (error) {
|
|
819
|
+
// No work was delivered, so the provider gives the whole lock back.
|
|
820
|
+
let declineSignature;
|
|
821
|
+
try {
|
|
822
|
+
declineSignature = await deps.chain.sendInstructions([meteredDecline(terms, lock)]);
|
|
823
|
+
}
|
|
824
|
+
catch {
|
|
825
|
+
declineSignature = undefined;
|
|
826
|
+
}
|
|
827
|
+
log({ event: "upstream_failed", requestId, escrow, declined: declineSignature !== undefined, detail: error instanceof Error ? error.message : "unknown" });
|
|
828
|
+
return refuse(502, "model_unavailable", declineSignature
|
|
829
|
+
? "The model did not answer. Nothing was charged and your lock was refunded in full."
|
|
830
|
+
: `The model did not answer. Nothing was charged; your maximum stays locked in escrow ${escrow} and you can refund it once its refund window opens.`, { charged: false, escrow, ...(declineSignature ? { refundSignature: declineSignature } : {}) });
|
|
831
|
+
}
|
|
832
|
+
const usage = usageFrom(upstream, inputEstimate);
|
|
833
|
+
answering.add(escrow);
|
|
834
|
+
try {
|
|
835
|
+
return await settleAndAnswer({ escrow, escrowAddress: header.escrow, lock, requestId, requestText, upstream, usage, createdMs: nowMs() });
|
|
836
|
+
}
|
|
837
|
+
finally {
|
|
838
|
+
answering.delete(escrow);
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* A lock whose settle was sent earlier and not known to have landed: the
|
|
843
|
+
* same request collects its held answer, and a settle whose answer was lost
|
|
844
|
+
* is looked up. Undefined when the lock has neither.
|
|
845
|
+
*/
|
|
846
|
+
async function collectHeld(escrow, requestText) {
|
|
847
|
+
const waiting = waitingCalls.get(escrow);
|
|
848
|
+
if (waiting) {
|
|
849
|
+
if (sha256Hex(waiting.requestText) !== sha256Hex(requestText))
|
|
850
|
+
return refuse(409, "settle_pending", "This lock's settle for an earlier request is still being confirmed. Send that same request again to collect its answer.", { charged: "unknown" });
|
|
851
|
+
const recorded = (await Promise.resolve(pendingSettles.load())).find((r) => r.escrow === waiting.escrow && r.status === "pending");
|
|
852
|
+
return settleAndAnswer(waiting, recorded);
|
|
853
|
+
}
|
|
854
|
+
const orphan = (await Promise.resolve(pendingSettles.load())).find((r) => r.escrow === escrow && r.status === "pending");
|
|
855
|
+
if (orphan) {
|
|
856
|
+
const where = await reconcileOrphan(orphan);
|
|
857
|
+
if (where === "landed")
|
|
858
|
+
return refuse(410, "answer_unavailable", "This lock was settled, but the answer it paid for was lost when the provider restarted. The provider's operator has been alerted.", { charged: true, settleSignature: orphan.signature });
|
|
859
|
+
if (where === "pending")
|
|
860
|
+
return refuse(503, "settle_pending", "This lock's settle is still being confirmed. Try again shortly.", { charged: "unknown" }, { "retry-after": "10" });
|
|
861
|
+
return refuse(409, "duplicate_nonce", "This lock's earlier settle did not land; nothing was charged, and the lock was given back if it was still there.", { charged: false });
|
|
862
|
+
}
|
|
863
|
+
return undefined;
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Settles a served single call and returns its answer, or withholds the
|
|
867
|
+
* answer when the settle did not land. A settle whose outcome is not known
|
|
868
|
+
* leaves the answer waiting here: the buyer sends the same signed request
|
|
869
|
+
* again, and gets it once that settle is known to have landed. It is never
|
|
870
|
+
* counted as paid by another transaction on the escrow.
|
|
871
|
+
*/
|
|
872
|
+
async function settleAndAnswer(call, resume) {
|
|
873
|
+
const { escrow, lock, requestId, usage, upstream } = call;
|
|
874
|
+
const requestHash = sha256Hex(call.requestText);
|
|
875
|
+
let last = resume;
|
|
876
|
+
const record = async (pending) => {
|
|
877
|
+
if (pending) {
|
|
878
|
+
last = { ...pending, escrow, requestHash, status: "pending" };
|
|
879
|
+
await pendingSettles.save(last);
|
|
880
|
+
}
|
|
881
|
+
else if (last) {
|
|
882
|
+
last = { ...last, status: "dropped" };
|
|
883
|
+
await pendingSettles.save(last);
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
const outcome = await settleLock(lock, call.escrowAddress, requestId, (payout) => meteredSettlement(terms, lock, usage, payout), record, resume);
|
|
887
|
+
if (outcome.ok === "pending") {
|
|
888
|
+
waitingCalls.set(escrow, call);
|
|
889
|
+
return refuse(503, "settle_pending", "The payment's settle was sent but whether it landed is not known yet, so the answer is held. Send the same request again shortly to get it; you are not charged twice.", { charged: "unknown", escrow, settleSignature: outcome.signature }, { "retry-after": "10" });
|
|
890
|
+
}
|
|
891
|
+
waitingCalls.delete(escrow);
|
|
892
|
+
if (outcome.ok === "closed") {
|
|
893
|
+
return refuse(402, "escrow_closed", `The escrow ${escrow} was closed before the settle landed, so nothing was charged and the answer is withheld.`, { charged: false, escrow });
|
|
894
|
+
}
|
|
895
|
+
if (!outcome.ok)
|
|
896
|
+
return refuse(502, "settle_failed", `The payment could not be settled, so the answer is withheld. Nothing was charged; your maximum stays locked in escrow ${escrow} and you can refund it once its refund window opens.`, { charged: false, escrow });
|
|
897
|
+
if (last)
|
|
898
|
+
await Promise.resolve(pendingSettles.save({ ...last, status: "landed" })).catch(() => undefined);
|
|
899
|
+
const { settleSignature, confirmed } = outcome;
|
|
900
|
+
// The amounts the settle asked for; it was built from these.
|
|
901
|
+
const s = (outcome.settled ?? meteredSettlement(terms, lock, usage)).settlement;
|
|
902
|
+
const decimals = directPaymentCurrency(s.currency).decimals;
|
|
903
|
+
const amounts = confirmed.ok
|
|
904
|
+
? {
|
|
905
|
+
charged: baseUnitsToDecimal(confirmed.paidBaseUnits, decimals),
|
|
906
|
+
fee: baseUnitsToDecimal(confirmed.feeBaseUnits, decimals),
|
|
907
|
+
provider: baseUnitsToDecimal(confirmed.providerBaseUnits, decimals),
|
|
908
|
+
refund: baseUnitsToDecimal(confirmed.refundedBaseUnits, decimals),
|
|
909
|
+
}
|
|
910
|
+
: { charged: s.charged, fee: s.fee, provider: s.provider, refund: s.refund };
|
|
911
|
+
const reddi = {
|
|
912
|
+
requestId,
|
|
913
|
+
provider: config.wallet,
|
|
914
|
+
model: config.model,
|
|
915
|
+
// Token counts are the model's report. The amounts are the confirmed settle's when `confirmed` is true, and otherwise what the settle asked for.
|
|
916
|
+
metered: { inputTokens: s.inputTokens, outputTokens: s.outputTokens, currency: s.currency, ...amounts, capped: s.capped, settleSignature, confirmed: confirmed.ok },
|
|
917
|
+
};
|
|
918
|
+
const responseText = JSON.stringify({ ...upstream, reddi });
|
|
919
|
+
let receiptHeader;
|
|
920
|
+
if (confirmed.ok) {
|
|
921
|
+
try {
|
|
922
|
+
const statement = {
|
|
923
|
+
schemaVersion: "reddi.receipt.v2",
|
|
924
|
+
providerId: config.wallet,
|
|
925
|
+
declaredModel: config.model,
|
|
926
|
+
requestHash,
|
|
927
|
+
responseHash: sha256Hex(responseText),
|
|
928
|
+
payment: {
|
|
929
|
+
network: config.network,
|
|
930
|
+
txSignature: settleSignature,
|
|
931
|
+
currency: s.currency,
|
|
932
|
+
mint: terms.mint.toBase58(),
|
|
933
|
+
amount: confirmed.paidBaseUnits.toString(),
|
|
934
|
+
fee: confirmed.feeBaseUnits > 0n ? { amount: confirmed.feeBaseUnits.toString(), treasury: ESCROW_PROTOCOL_TREASURY.toBase58() } : { amount: "0" },
|
|
935
|
+
payer: lock.payer.toBase58(),
|
|
936
|
+
settlement: "metered-escrow",
|
|
937
|
+
metered: { inputTokens: String(s.inputTokens), outputTokens: String(s.outputTokens), maxAmount: lock.maxBaseUnits.toString(), refunded: confirmed.refundedBaseUnits.toString() },
|
|
938
|
+
},
|
|
939
|
+
issuedAt: (deps.now?.() ?? new Date()).toISOString(),
|
|
940
|
+
};
|
|
941
|
+
const signed = await signReddiReceiptV2(statement, deps.signMessage);
|
|
942
|
+
const encoded = Buffer.from(JSON.stringify(signed), "utf8").toString("base64url");
|
|
943
|
+
if (encoded.length <= MAX_RECEIPT_HEADER_CHARS)
|
|
944
|
+
receiptHeader = encoded;
|
|
945
|
+
}
|
|
946
|
+
catch {
|
|
947
|
+
// The buyer still gets the answer the settle paid for.
|
|
948
|
+
log({ event: "receipt_failed", requestId, escrow });
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
else {
|
|
952
|
+
// The settle landed, but what it moved could not be read back. No financial statement is signed on a guess.
|
|
953
|
+
log({ event: "receipt_withheld", requestId, escrow, settleSignature, reason: confirmed.reason });
|
|
954
|
+
}
|
|
955
|
+
log({ event: "paid_call", requestId, escrow, settleSignature, charged: amounts.charged, fee: amounts.fee, confirmed: confirmed.ok, currency: s.currency, inputTokens: s.inputTokens, outputTokens: s.outputTokens, receipt: receiptHeader !== undefined });
|
|
956
|
+
return new Response(responseText, { status: 200, headers: receiptHeader ? { ...JSON_HEADERS, [PROVIDER_RECEIPT_HEADER]: receiptHeader } : JSON_HEADERS });
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* A single call's settle recorded as pending whose answer is no longer held
|
|
960
|
+
* (after a restart, or held too long). Finds out where it stands: if it
|
|
961
|
+
* landed the buyer paid and the operator is alerted to make it right; if it
|
|
962
|
+
* cannot land and the escrow is still locked, the lock is declined so the
|
|
963
|
+
* buyer gets it all back.
|
|
964
|
+
*/
|
|
965
|
+
async function reconcileOrphan(record) {
|
|
966
|
+
const where = await deps.chain.signatureState(record.signature, record.lastValidBlockHeight);
|
|
967
|
+
if (where === "unknown") {
|
|
968
|
+
await deps.chain.sendSigned({ signature: record.signature, transaction: record.transaction, lastValidBlockHeight: record.lastValidBlockHeight }).catch(() => undefined);
|
|
969
|
+
return "pending";
|
|
970
|
+
}
|
|
971
|
+
if (where === "landed") {
|
|
972
|
+
await Promise.resolve(pendingSettles.save({ ...record, status: "landed" })).catch(() => undefined);
|
|
973
|
+
log({ event: "paid_answer_lost", escrow: record.escrow, settleSignature: record.signature, alert: true });
|
|
974
|
+
return "landed";
|
|
975
|
+
}
|
|
976
|
+
await Promise.resolve(pendingSettles.save({ ...record, status: "dropped" })).catch(() => undefined);
|
|
977
|
+
// Nothing was charged by it. Give the lock back if it is still there.
|
|
978
|
+
const header = { escrow: new PublicKey(record.escrow) };
|
|
979
|
+
if ((await escrowState(header.escrow)) === "locked") {
|
|
980
|
+
try {
|
|
981
|
+
const account = await deps.chain.readAccount(header.escrow);
|
|
982
|
+
const decoded = account ? decodeTokenEscrowAccount(Buffer.from(account.data)) : undefined;
|
|
983
|
+
if (decoded) {
|
|
984
|
+
const lock = await verifyMeteredLock({ header: { escrow: header.escrow, payer: decoded.payer, nonce: Uint8Array.from(decoded.nonce) }, terms, minimum: 0n, readAccount, readSlot, replayStore: deps.replayStore, purpose: "session-settle", acceptRatedEscrows: true });
|
|
985
|
+
if (lock.ok) {
|
|
986
|
+
const signature = await deps.chain.sendInstructions([meteredDecline(terms, lock)]);
|
|
987
|
+
log({ event: "pending_settle_declined", escrow: record.escrow, signature });
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
catch {
|
|
992
|
+
log({ event: "pending_settle_decline_failed", escrow: record.escrow, alert: true });
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
return "dropped";
|
|
996
|
+
}
|
|
997
|
+
/** Looks again at single-call settles whose outcome was not known and whose answer is no longer held. */
|
|
998
|
+
async function reconcilePendingCalls() {
|
|
999
|
+
const now = nowMs();
|
|
1000
|
+
for (const [escrow, call] of waitingCalls) {
|
|
1001
|
+
if (now - call.createdMs > HELD_ANSWER_MS)
|
|
1002
|
+
waitingCalls.delete(escrow);
|
|
1003
|
+
}
|
|
1004
|
+
let records;
|
|
1005
|
+
try {
|
|
1006
|
+
records = await Promise.resolve(pendingSettles.load());
|
|
1007
|
+
}
|
|
1008
|
+
catch {
|
|
1009
|
+
return;
|
|
1010
|
+
}
|
|
1011
|
+
for (const record of records) {
|
|
1012
|
+
if (record.status !== "pending" || waitingCalls.has(record.escrow) || answering.has(record.escrow))
|
|
1013
|
+
continue;
|
|
1014
|
+
answering.add(record.escrow);
|
|
1015
|
+
await reconcileOrphan(record).catch(() => undefined).finally(() => answering.delete(record.escrow));
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
async function handle(request) {
|
|
1019
|
+
const url = new URL(request.url);
|
|
1020
|
+
if (request.method === "POST" && url.pathname === "/v1/session/close") {
|
|
1021
|
+
try {
|
|
1022
|
+
return await closeRequest(request);
|
|
1023
|
+
}
|
|
1024
|
+
catch {
|
|
1025
|
+
log({ event: "unexpected_error" });
|
|
1026
|
+
return refuse(500, "internal_error", "The provider hit an unexpected error.");
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (request.method === "GET" && url.pathname.startsWith("/v1/session/"))
|
|
1030
|
+
return sessionRead(request, decodeURIComponent(url.pathname.slice("/v1/session/".length)));
|
|
1031
|
+
if (request.method === "GET" && url.pathname === "/healthz")
|
|
1032
|
+
return json(200, { ok: true, name: config.name, network: config.network, acceptingPayments: !config.paused });
|
|
1033
|
+
if (request.method === "GET" && url.pathname === "/v1/models")
|
|
1034
|
+
return json(200, { object: "list", data: [{ id: config.model, object: "model", owned_by: config.wallet }] });
|
|
1035
|
+
if (request.method === "GET" && url.pathname === "/.well-known/reddi-agent.json")
|
|
1036
|
+
return json(200, providerMetadata(config));
|
|
1037
|
+
if (request.method === "GET" && url.pathname === ADL_PATH)
|
|
1038
|
+
return new Response(adlText, { status: 200, headers: { "content-type": "application/yaml; charset=utf-8", "cache-control": "public, max-age=300" } });
|
|
1039
|
+
if (request.method === "POST" && url.pathname === "/v1/chat/completions") {
|
|
1040
|
+
try {
|
|
1041
|
+
return await paidChat(request);
|
|
1042
|
+
}
|
|
1043
|
+
catch {
|
|
1044
|
+
log({ event: "unexpected_error" });
|
|
1045
|
+
return refuse(500, "internal_error", "The provider hit an unexpected error.");
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
return refuse(404, "not_found", "No such route.");
|
|
1049
|
+
}
|
|
1050
|
+
return Object.assign(handle, { settleDueSessions });
|
|
1051
|
+
}
|