@redditech/provider-kit 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,11 +32,49 @@
32
32
  import { createHash, randomUUID } from "node:crypto";
33
33
  import { hashReddiReceiptV2, signReddiReceiptV2 } from "@redditech/agent-protocol/receipt-v2";
34
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";
35
+ import { baseUnitsToDecimal, checkMeteredPayout, checkProviderCluster, confirmMeteredSettlement, decodeTokenEscrowAccount, directPaymentCurrency, ESCROW_PROTOCOL_TREASURY, estimateInputTokens, inputTokenBound, meteredDecline, meteredOffer, meteredSettlement, minimumLockBaseUnits, outputLimit, readMeteredPaymentHeader, lockMatchesSession, readSessionHeaders, recordedInstruction, sessionCallAction, sessionPaymentHeader, sessionSettlement, SOLANA_GENESIS_HASHES, tokenEscrowAddresses, usageFrom, verifyMeteredLock, verifySessionRequestWithTransactions, } from "@redditech/x402-solana";
36
36
  import { MemoryPendingSettleStore } from "./pending.js";
37
37
  import { MAX_BODY_BYTES } from "./config.js";
38
38
  import { ADL_PATH, providerAdlText } from "./adl.js";
39
+ import { UpstreamError } from "./upstream.js";
40
+ import { BUSY_MESSAGES, Capacity } from "./capacity.js";
41
+ import { MemoryHeldAnswerStore, MemoryLockLease } from "./state.js";
39
42
  export const PROVIDER_RECEIPT_HEADER = "x-reddi-provider-receipt";
43
+ /**
44
+ * Reads a request body as text, stopping as soon as it passes MAX_BODY_BYTES:
45
+ * a chunked body states no length, so the count is kept while reading and the
46
+ * rest is never buffered.
47
+ */
48
+ export async function readBodyText(request, limit = MAX_BODY_BYTES) {
49
+ const stated = Number(request.headers.get("content-length") ?? "0");
50
+ if (stated > limit) {
51
+ await request.body?.cancel().catch(() => undefined);
52
+ return { ok: false, reason: "too_large" };
53
+ }
54
+ if (!request.body)
55
+ return { ok: true, text: "" };
56
+ const reader = request.body.getReader();
57
+ const chunks = [];
58
+ let size = 0;
59
+ try {
60
+ for (;;) {
61
+ const { done, value } = await reader.read();
62
+ if (done)
63
+ break;
64
+ size += value.byteLength;
65
+ if (size > limit) {
66
+ await reader.cancel().catch(() => undefined);
67
+ return { ok: false, reason: "too_large" };
68
+ }
69
+ chunks.push(value);
70
+ }
71
+ }
72
+ catch {
73
+ // A body that broke off is never treated as an empty request.
74
+ return { ok: false, reason: "unreadable" };
75
+ }
76
+ return { ok: true, text: Buffer.concat(chunks).toString("utf8") };
77
+ }
40
78
  /** The closing receipt of a session, on the answer that settled it. */
41
79
  export const SESSION_RECEIPT_HEADER = "x-reddi-session-receipt";
42
80
  /** On an answer that asked to close the session: settled, declined, or pending (tried again shortly). */
@@ -45,6 +83,13 @@ const JSON_HEADERS = { "content-type": "application/json; charset=utf-8" };
45
83
  const MAX_RECEIPT_HEADER_CHARS = 4096;
46
84
  /** How long the answer of a call whose settle outcome is not known is held for the buyer to collect. */
47
85
  const HELD_ANSWER_MS = 10 * 60_000;
86
+ /**
87
+ * How long one request may hold a lock's lease while it settles or collects.
88
+ * Longer than a request may run on a serverless host (300 s), so a live
89
+ * request never loses it; short enough that a lease left by a crashed instance
90
+ * clears on its own.
91
+ */
92
+ const LOCK_LEASE_MS = 330_000;
48
93
  const sha256Hex = (text) => createHash("sha256").update(Buffer.from(text, "utf8")).digest("hex");
49
94
  function json(status, body, headers = {}) {
50
95
  return new Response(JSON.stringify(body), { status, headers: { ...JSON_HEADERS, ...headers } });
@@ -91,6 +136,9 @@ export function providerMetadata(config) {
91
136
  }
92
137
  export function createProviderHandler(config, deps) {
93
138
  const { terms } = config;
139
+ // Same rule as parseProviderConfig, for callers that build the handler themselves.
140
+ if (deps.sessions && config.network === "solana-mainnet-beta")
141
+ throw new Error("sessions are not offered on mainnet yet: build the handler without a session ledger");
94
142
  // The provider's ADL, made once from the config it runs on.
95
143
  const adlText = providerAdlText(config).text;
96
144
  const log = deps.log ?? (() => undefined);
@@ -103,9 +151,9 @@ export function createProviderHandler(config, deps) {
103
151
  const today = () => (deps.now?.() ?? new Date()).toISOString().slice(0, 10);
104
152
  const pendingSettles = deps.pendingSettles ?? new MemoryPendingSettleStore();
105
153
  // Answers of single calls whose settle was sent but not yet known to land, by escrow.
106
- const waitingCalls = new Map();
154
+ const heldAnswers = deps.heldAnswers ?? new MemoryHeldAnswerStore();
107
155
  /** Single-call locks whose settle is being sent or looked at right now. */
108
- const answering = new Set();
156
+ const lease = deps.lease ?? new MemoryLockLease();
109
157
  const subsidyLeft = () => {
110
158
  if (subsidy.day !== today())
111
159
  Object.assign(subsidy, { day: today(), used: 0 });
@@ -233,7 +281,7 @@ export function createProviderHandler(config, deps) {
233
281
  subsidy.used += 1;
234
282
  let next;
235
283
  try {
236
- const again = await checkMeteredPayout({ terms, escrow: lock.terms, readAccount: (address) => deps.chain.readAccount(address), allowPayerAssociatedAccount: true, createRefundAccount: reserved || lock.payout.createRefundAccount === true });
284
+ const again = await checkMeteredPayout({ terms, escrow: lock.terms, readAccount: (address) => deps.chain.readAccount(address), allowPayerAssociatedAccount: true, createRefundAccount: reserved || lock.payout.createRefundAccount === true, instance: { escrow: escrowAddress, createdSlot: lock.createdSlot } });
237
285
  if (again.ok)
238
286
  next = await prepare(again.payout);
239
287
  if (next?.payout?.createRefundAccount)
@@ -252,6 +300,20 @@ export function createProviderHandler(config, deps) {
252
300
  return { ok: false };
253
301
  }
254
302
  const nowMs = () => (deps.now?.() ?? new Date()).getTime();
303
+ const limits = deps.capacity ?? new Capacity(config.capacity);
304
+ // A capacity store that cannot be read counts as busy for a moment: fail closed, nothing is taken.
305
+ const unknownCapacity = { ok: false, reason: "cooling_down", retryAfterSeconds: 10 };
306
+ const capacity = {
307
+ check: (at) => limits.check(at).catch(() => unknownCapacity),
308
+ take: (at) => limits.take(at).catch(() => unknownCapacity),
309
+ coolDown: (at) => limits.coolDown(at),
310
+ };
311
+ const busy = (v, message, extra = {}) => refuse(503, "provider_busy", `${BUSY_MESSAGES[v.reason]} ${message}`, { charged: false, busy: { reason: v.reason, retryAfterSeconds: v.retryAfterSeconds }, ...extra }, { "retry-after": String(v.retryAfterSeconds) });
312
+ /** A 429 from the model means it is rate limited: stop offering calls for the cooldown. */
313
+ const noteUpstreamFailure = async (error) => {
314
+ if (error instanceof UpstreamError && error.status === 429)
315
+ await capacity.coolDown(nowMs()).catch(() => undefined);
316
+ };
255
317
  const issuedAt = () => (deps.now?.() ?? new Date()).toISOString();
256
318
  const decimals = directPaymentCurrency(terms.price.currency).decimals;
257
319
  const readAccount = (address) => deps.chain.readAccount(address);
@@ -326,10 +388,11 @@ export function createProviderHandler(config, deps) {
326
388
  * With `lockBoundDelegations`, the payer's consent may instead be a memo it signed in the lock transaction (#925).
327
389
  */
328
390
  /** 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. */
391
+ const otherLockRefusal = () => refuse(401, "session_auth_invalid", "The delegation was given in the transaction of another lock at this address. Delegate for this lock.", { charged: false });
329
392
  function lockSlotMismatch(auth, createdSlot) {
330
393
  if (auth.lockSlot === undefined || auth.lockSlot === createdSlot)
331
394
  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 });
395
+ return otherLockRefusal();
333
396
  }
334
397
  async function sessionAuth(request, action, escrow, payer, sequence, body) {
335
398
  const auth = await verifySessionRequestWithTransactions({ headers: request.headers, genesisHash: signingGenesisHash, action, escrow, payer, provider: terms.payee, sequence, body, nowMs: nowMs(), ...(readTransaction ? { readTransaction } : {}) });
@@ -357,12 +420,14 @@ export function createProviderHandler(config, deps) {
357
420
  return mismatch;
358
421
  let lock;
359
422
  try {
360
- lock = await verifyMeteredLock({ header: c.header, terms, minimum: c.minimum, readAccount, readSlot, replayStore: deps.replayStore, purpose: "session-call" });
423
+ lock = await verifyMeteredLock({ header: c.header, terms, minimum: c.minimum, readAccount, readSlot, replayStore: deps.replayStore, purpose: "session-call", ...(auth.lockSlot !== undefined ? { lockSlot: auth.lockSlot } : {}) });
361
424
  }
362
425
  catch {
363
426
  return refuse(503, "payment_check_unavailable", "The lock could not be checked. Nothing was charged for this call; send it again.", { charged: false });
364
427
  }
365
428
  if (!lock.ok) {
429
+ if (lock.reason === "lock_instance_mismatch")
430
+ return otherLockRefusal();
366
431
  if (lock.reason === "payment_check_unavailable")
367
432
  clusterConfirmed = false;
368
433
  // No more calls fit before the refund window opens: settle what was served while there is time.
@@ -387,16 +452,22 @@ export function createProviderHandler(config, deps) {
387
452
  }
388
453
  const reservation = begun.reservation;
389
454
  const requestId = randomUUID();
455
+ const slot = await capacity.take(nowMs());
456
+ if (!slot.ok) {
457
+ ledger.release(reservation);
458
+ return busy(slot, `Nothing was charged for this call; the session stays open and call ${c.sequence} can be sent again in ${slot.retryAfterSeconds} seconds.`, { escrow });
459
+ }
390
460
  let upstream;
391
461
  try {
392
462
  upstream = await deps.upstream.createChatCompletion({ model: config.upstream.model, messages: c.upstreamMessages, ...(c.temperature === undefined ? {} : { temperature: c.temperature }), max_tokens: c.worstCase.outputTokens });
393
463
  }
394
464
  catch (error) {
465
+ await noteUpstreamFailure(error);
395
466
  ledger.release(reservation);
396
467
  log({ event: "upstream_failed", requestId, escrow, sequence: c.sequence, detail: error instanceof Error ? error.message : "unknown" });
397
468
  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
469
  }
399
- const usage = usageFrom(upstream, c.worstCase.inputTokens);
470
+ const usage = usageFrom(upstream, estimateInputTokens(c.upstreamMessages));
400
471
  const next = ledger.preview(reservation, usage);
401
472
  const reddi = {
402
473
  requestId,
@@ -680,7 +751,10 @@ export function createProviderHandler(config, deps) {
680
751
  return refuse(400, "invalid_receipt", "The escrow address is not the one this payer and nonce give.");
681
752
  }
682
753
  const escrow = header.escrow.toBase58();
683
- const auth = await sessionAuth(request, "close", header.escrow, header.payer, 0, await request.text().catch(() => ""));
754
+ const read = await readBodyText(request);
755
+ if (!read.ok)
756
+ return read.reason === "too_large" ? refuse(413, "request_too_large", "The request body is too large.") : refuse(400, "invalid_request", "The request body could not be read.");
757
+ const auth = await sessionAuth(request, "close", header.escrow, header.payer, 0, read.text);
684
758
  if (!auth.ok)
685
759
  return auth.response;
686
760
  if (!deps.sessions.get(escrow))
@@ -721,12 +795,10 @@ export function createProviderHandler(config, deps) {
721
795
  if (config.paused) {
722
796
  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
797
  }
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.");
798
+ const read = await readBodyText(request);
799
+ if (!read.ok)
800
+ return read.reason === "too_large" ? refuse(413, "request_too_large", "The request body is too large.") : refuse(400, "invalid_request", "The request body could not be read.");
801
+ const requestText = read.text;
730
802
  let body;
731
803
  try {
732
804
  const parsed = JSON.parse(requestText);
@@ -750,6 +822,10 @@ export function createProviderHandler(config, deps) {
750
822
  const offer = meteredOffer(terms, upstreamMessages, requestedMax, config.network);
751
823
  const header = readMeteredPaymentHeader(request.headers);
752
824
  if (header === undefined) {
825
+ // A busy provider says so before the buyer locks anything.
826
+ const free = await capacity.check(nowMs());
827
+ if (!free.ok)
828
+ return busy(free, `Nothing was asked of you; try again in ${free.retryAfterSeconds} seconds.`);
753
829
  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
830
  }
755
831
  if ("error" in header)
@@ -762,16 +838,21 @@ export function createProviderHandler(config, deps) {
762
838
  }
763
839
  clusterConfirmed = true;
764
840
  }
841
+ // The floor on payment counts one token a UTF-8 byte, so dense text cannot buy a call below list price.
765
842
  const outputTokens = outputLimit(terms, requestedMax);
766
- const inputEstimate = estimateInputTokens(upstreamMessages);
767
- const minimum = tokenCostBaseUnits(terms.price, { inputTokens: inputEstimate, outputTokens });
843
+ const inputBound = inputTokenBound(upstreamMessages);
844
+ const minimum = minimumLockBaseUnits(terms, upstreamMessages, requestedMax);
768
845
  const sessionHeaders = readSessionHeaders(request.headers);
769
846
  if (sessionHeaders !== undefined) {
770
847
  if ("error" in sessionHeaders)
771
848
  return refuse(400, "session_invalid", sessionHeaders.error, { charged: false });
772
849
  if (!deps.sessions)
773
850
  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 });
851
+ return sessionCall({ header, sequence: sessionHeaders.sequence, close: sessionHeaders.close, requestText, headers: request.headers, upstreamMessages, temperature, worstCase: { inputTokens: inputBound, outputTokens }, minimum });
852
+ }
853
+ // The escrow must be the one this payer and nonce lock, so a payer's signature speaks only for its own escrow.
854
+ if (!tokenEscrowAddresses({ programId: terms.programId, payer: header.payer, nonce: header.nonce }).escrow.equals(header.escrow)) {
855
+ return refuse(402, "invalid_receipt", "The escrow is not the one this payer and nonce lock.", { charged: false });
775
856
  }
776
857
  // The lock's escrow, payer and nonce are public: only the payer's signature shows who is calling (#866).
777
858
  const auth = await sessionAuth(request, "single", header.escrow, header.payer, 0, requestText);
@@ -779,26 +860,40 @@ export function createProviderHandler(config, deps) {
779
860
  return auth.response;
780
861
  // A call whose settle was sent but not yet known to land: the same request collects its answer.
781
862
  // 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());
863
+ const checking = refuse(503, "settle_pending", "This lock's settle is already being checked. Try again shortly.", { charged: "unknown" }, { "retry-after": "10" });
864
+ let claimed;
785
865
  try {
786
- const held = await collectHeld(header.escrow.toBase58(), requestText);
866
+ claimed = await lease.claim(header.escrow.toBase58(), LOCK_LEASE_MS, nowMs());
867
+ }
868
+ catch {
869
+ return refuse(503, "payment_check_unavailable", "The payment could not be checked. Nothing was accepted; present the same lock again.", { charged: false });
870
+ }
871
+ if (!claimed)
872
+ return checking;
873
+ try {
874
+ const held = await collectHeld(header.escrow.toBase58(), requestText, { payer: header.payer, ...(auth.lockSlot !== undefined ? { lockSlot: auth.lockSlot } : {}) });
787
875
  if (held)
788
876
  return held;
789
877
  }
790
878
  finally {
791
- answering.delete(header.escrow.toBase58());
879
+ await lease.release(header.escrow.toBase58()).catch(() => undefined);
792
880
  }
881
+ // Busy: the lock is not read or used, so the same request works once the provider has room.
882
+ const free = await capacity.check(nowMs());
883
+ if (!free.ok)
884
+ return busy(free, `Nothing was accepted and your lock is untouched; send the same request again in ${free.retryAfterSeconds} seconds.`);
793
885
  let lock;
794
886
  try {
795
- lock = await verifyMeteredLock({ header, terms, minimum, readAccount: (address) => deps.chain.readAccount(address), readSlot: () => deps.chain.readSlot(), replayStore: deps.replayStore });
887
+ // A proof for another lock at this address is refused before this lock is remembered.
888
+ lock = await verifyMeteredLock({ header, terms, minimum, readAccount: (address) => deps.chain.readAccount(address), readSlot: () => deps.chain.readSlot(), replayStore: deps.replayStore, ...(auth.lockSlot !== undefined ? { lockSlot: auth.lockSlot } : {}) });
796
889
  }
797
890
  catch {
798
891
  // The replay store could not record the escrow, so it cannot be accepted.
799
892
  return refuse(503, "payment_check_unavailable", "The payment could not be recorded. Nothing was accepted; present the same lock again.", { charged: false });
800
893
  }
801
894
  if (!lock.ok) {
895
+ if (lock.reason === "lock_instance_mismatch")
896
+ return otherLockRefusal();
802
897
  if (lock.reason === "payment_check_unavailable")
803
898
  clusterConfirmed = false;
804
899
  const status = lock.reason === "payment_check_unavailable" || lock.reason === "provider_not_ready" ? 503 : lock.reason === "duplicate_nonce" ? 409 : 402;
@@ -811,31 +906,45 @@ export function createProviderHandler(config, deps) {
811
906
  return otherLock;
812
907
  const escrow = header.escrow.toBase58();
813
908
  const requestId = randomUUID();
909
+ const giveBack = async () => {
910
+ try {
911
+ return await deps.chain.sendInstructions([meteredDecline(terms, lock)]);
912
+ }
913
+ catch {
914
+ return undefined;
915
+ }
916
+ };
917
+ // Counted only once the lock is good, so requests without a valid lock cannot use up the limits.
918
+ const slot = await capacity.take(nowMs());
919
+ if (!slot.ok) {
920
+ // Filled up between the check and now: the lock is given back whole.
921
+ const declineSignature = await giveBack();
922
+ log({ event: "provider_busy", requestId, escrow, reason: slot.reason, declined: declineSignature !== undefined });
923
+ return busy(slot, declineSignature ? "Nothing was charged and your lock was refunded in full." : `Nothing was charged; your maximum stays locked in escrow ${escrow} and you can refund it once its refund window opens.`, { escrow, ...(declineSignature ? { refundSignature: declineSignature } : {}) });
924
+ }
814
925
  let upstream;
815
926
  try {
816
927
  upstream = await deps.upstream.createChatCompletion({ model: config.upstream.model, messages: upstreamMessages, ...(temperature === undefined ? {} : { temperature }), max_tokens: outputTokens });
817
928
  }
818
929
  catch (error) {
930
+ await noteUpstreamFailure(error);
819
931
  // 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
- }
932
+ const declineSignature = await giveBack();
827
933
  log({ event: "upstream_failed", requestId, escrow, declined: declineSignature !== undefined, detail: error instanceof Error ? error.message : "unknown" });
828
934
  return refuse(502, "model_unavailable", declineSignature
829
935
  ? "The model did not answer. Nothing was charged and your lock was refunded in full."
830
936
  : `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
937
  }
832
- const usage = usageFrom(upstream, inputEstimate);
833
- answering.add(escrow);
938
+ const usage = usageFrom(upstream, estimateInputTokens(upstreamMessages));
939
+ // This request alone accepted the lock (the replay store saw to that), so the lease only keeps a retry from looking at it mid-settle.
940
+ // Not getting it is no reason to stop: the settle goes ahead.
941
+ const leased = await lease.claim(escrow, LOCK_LEASE_MS, nowMs()).catch(() => false);
834
942
  try {
835
- return await settleAndAnswer({ escrow, escrowAddress: header.escrow, lock, requestId, requestText, upstream, usage, createdMs: nowMs() });
943
+ return await settleAndAnswer({ escrow, lock, requestId, requestHash: sha256Hex(requestText), upstream, usage, createdMs: nowMs() });
836
944
  }
837
945
  finally {
838
- answering.delete(escrow);
946
+ if (leased)
947
+ await lease.release(escrow).catch(() => undefined);
839
948
  }
840
949
  }
841
950
  /**
@@ -843,15 +952,27 @@ export function createProviderHandler(config, deps) {
843
952
  * same request collects its held answer, and a settle whose answer was lost
844
953
  * is looked up. Undefined when the lock has neither.
845
954
  */
846
- async function collectHeld(escrow, requestText) {
847
- const waiting = waitingCalls.get(escrow);
955
+ async function findPending(escrow) {
956
+ if (pendingSettles.findPending)
957
+ return pendingSettles.findPending(escrow);
958
+ return (await Promise.resolve(pendingSettles.load())).find((r) => r.escrow === escrow && r.status === "pending");
959
+ }
960
+ async function collectHeld(escrow, requestText, caller) {
961
+ const waiting = await heldAnswers.get(escrow);
962
+ // Only the payer of the lock that paid may collect its answer or learn of its settle. To anyone else
963
+ // there is nothing held here, and the lock check that follows refuses them.
964
+ if (waiting && (!waiting.lock.payer.equals(caller.payer) || (caller.lockSlot !== undefined && caller.lockSlot !== waiting.lock.createdSlot)))
965
+ return undefined;
848
966
  if (waiting) {
849
- if (sha256Hex(waiting.requestText) !== sha256Hex(requestText))
967
+ if (waiting.requestHash !== sha256Hex(requestText))
850
968
  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");
969
+ const recorded = await findPending(waiting.escrow);
852
970
  return settleAndAnswer(waiting, recorded);
853
971
  }
854
- const orphan = (await Promise.resolve(pendingSettles.load())).find((r) => r.escrow === escrow && r.status === "pending");
972
+ const orphan = await findPending(escrow);
973
+ // A record from before the payer was kept names no payer: nobody collects through it, and the sweep still settles it.
974
+ if (orphan && (orphan.payer !== caller.payer.toBase58() || (caller.lockSlot !== undefined && orphan.createdSlot !== caller.lockSlot.toString())))
975
+ return undefined;
855
976
  if (orphan) {
856
977
  const where = await reconcileOrphan(orphan);
857
978
  if (where === "landed")
@@ -870,12 +991,12 @@ export function createProviderHandler(config, deps) {
870
991
  * counted as paid by another transaction on the escrow.
871
992
  */
872
993
  async function settleAndAnswer(call, resume) {
873
- const { escrow, lock, requestId, usage, upstream } = call;
874
- const requestHash = sha256Hex(call.requestText);
994
+ const { escrow, lock, requestId, usage, upstream, requestHash } = call;
995
+ const escrowAddress = new PublicKey(escrow);
875
996
  let last = resume;
876
997
  const record = async (pending) => {
877
998
  if (pending) {
878
- last = { ...pending, escrow, requestHash, status: "pending" };
999
+ last = { ...pending, escrow, requestHash, payer: lock.payer.toBase58(), createdSlot: lock.createdSlot.toString(), status: "pending" };
879
1000
  await pendingSettles.save(last);
880
1001
  }
881
1002
  else if (last) {
@@ -883,12 +1004,13 @@ export function createProviderHandler(config, deps) {
883
1004
  await pendingSettles.save(last);
884
1005
  }
885
1006
  };
886
- const outcome = await settleLock(lock, call.escrowAddress, requestId, (payout) => meteredSettlement(terms, lock, usage, payout), record, resume);
1007
+ const outcome = await settleLock(lock, escrowAddress, requestId, (payout) => meteredSettlement(terms, lock, usage, payout), record, resume);
887
1008
  if (outcome.ok === "pending") {
888
- waitingCalls.set(escrow, call);
1009
+ // Held for the same request to collect. If it cannot be held, the sweep still finds the recorded settle.
1010
+ await heldAnswers.hold(call).catch(() => log({ event: "answer_not_held", requestId, escrow, alert: true }));
889
1011
  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
1012
  }
891
- waitingCalls.delete(escrow);
1013
+ await heldAnswers.drop(escrow).catch(() => undefined);
892
1014
  if (outcome.ok === "closed") {
893
1015
  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
1016
  }
@@ -974,14 +1096,19 @@ export function createProviderHandler(config, deps) {
974
1096
  return "landed";
975
1097
  }
976
1098
  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.
1099
+ // Nothing was charged by it. Give the lock back if it is still there, and only that lock: another lock now
1100
+ // at the same address (a later job) is not this settle's to decline.
978
1101
  const header = { escrow: new PublicKey(record.escrow) };
1102
+ if (record.payer === undefined || record.createdSlot === undefined) {
1103
+ log({ event: "pending_settle_unbound", escrow: record.escrow, alert: true });
1104
+ return "dropped";
1105
+ }
979
1106
  if ((await escrowState(header.escrow)) === "locked") {
980
1107
  try {
981
1108
  const account = await deps.chain.readAccount(header.escrow);
982
1109
  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 });
1110
+ if (decoded && decoded.payer.toBase58() === record.payer && decoded.createdSlot.toString() === record.createdSlot) {
1111
+ 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, lockSlot: BigInt(record.createdSlot) });
985
1112
  if (lock.ok) {
986
1113
  const signature = await deps.chain.sendInstructions([meteredDecline(terms, lock)]);
987
1114
  log({ event: "pending_settle_declined", escrow: record.escrow, signature });
@@ -997,10 +1124,7 @@ export function createProviderHandler(config, deps) {
997
1124
  /** Looks again at single-call settles whose outcome was not known and whose answer is no longer held. */
998
1125
  async function reconcilePendingCalls() {
999
1126
  const now = nowMs();
1000
- for (const [escrow, call] of waitingCalls) {
1001
- if (now - call.createdMs > HELD_ANSWER_MS)
1002
- waitingCalls.delete(escrow);
1003
- }
1127
+ await heldAnswers.expire(now - HELD_ANSWER_MS);
1004
1128
  let records;
1005
1129
  try {
1006
1130
  records = await Promise.resolve(pendingSettles.load());
@@ -1009,10 +1133,11 @@ export function createProviderHandler(config, deps) {
1009
1133
  return;
1010
1134
  }
1011
1135
  for (const record of records) {
1012
- if (record.status !== "pending" || waitingCalls.has(record.escrow) || answering.has(record.escrow))
1136
+ if (record.status !== "pending" || (await heldAnswers.get(record.escrow)))
1013
1137
  continue;
1014
- answering.add(record.escrow);
1015
- await reconcileOrphan(record).catch(() => undefined).finally(() => answering.delete(record.escrow));
1138
+ if (!(await lease.claim(record.escrow, LOCK_LEASE_MS, nowMs())))
1139
+ continue;
1140
+ await reconcileOrphan(record).catch(() => undefined).finally(() => lease.release(record.escrow).catch(() => undefined));
1016
1141
  }
1017
1142
  }
1018
1143
  async function handle(request) {
@@ -1028,8 +1153,10 @@ export function createProviderHandler(config, deps) {
1028
1153
  }
1029
1154
  if (request.method === "GET" && url.pathname.startsWith("/v1/session/"))
1030
1155
  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 });
1156
+ if (request.method === "GET" && url.pathname === "/healthz") {
1157
+ const free = await capacity.check(nowMs());
1158
+ return json(200, { ok: true, name: config.name, network: config.network, acceptingPayments: !config.paused, available: free.ok, ...(free.ok ? {} : { busy: { reason: free.reason, retryAfterSeconds: free.retryAfterSeconds } }) });
1159
+ }
1033
1160
  if (request.method === "GET" && url.pathname === "/v1/models")
1034
1161
  return json(200, { object: "list", data: [{ id: config.model, object: "model", owned_by: config.wallet }] });
1035
1162
  if (request.method === "GET" && url.pathname === "/.well-known/reddi-agent.json")
@@ -8,3 +8,7 @@ export * from "./handler.js";
8
8
  export * from "./doctor.js";
9
9
  export * from "./server.js";
10
10
  export * from "./adl.js";
11
+ export * from "./capacity.js";
12
+ export * from "./state.js";
13
+ export * from "./postgres.js";
14
+ export * from "./serverless.js";
package/dist/src/index.js CHANGED
@@ -8,3 +8,7 @@ export * from "./handler.js";
8
8
  export * from "./doctor.js";
9
9
  export * from "./server.js";
10
10
  export * from "./adl.js";
11
+ export * from "./capacity.js";
12
+ export * from "./state.js";
13
+ export * from "./postgres.js";
14
+ export * from "./serverless.js";
@@ -19,3 +19,13 @@ export declare function loadProviderKey(input: {
19
19
  readFile?: (path: string) => string;
20
20
  fileMode?: (path: string) => number;
21
21
  }): ProviderKeyResult;
22
+ /**
23
+ * The key from an environment variable holding the same JSON array a keypair
24
+ * file holds, for hosts with no private disk (a serverless host's sensitive
25
+ * environment variables). The variable's value is never echoed.
26
+ */
27
+ export declare function loadProviderKeyFromEnv(input: {
28
+ env: Record<string, string | undefined>;
29
+ name: string;
30
+ wallet: string;
31
+ }): ProviderKeyResult;
package/dist/src/keys.js CHANGED
@@ -35,19 +35,44 @@ export function loadProviderKey(input) {
35
35
  // The error is not echoed: it could carry file contents.
36
36
  return { ok: false, message: "the key file could not be read" };
37
37
  }
38
+ return keyFromBytes(bytes, input.wallet, "the key file");
39
+ }
40
+ /**
41
+ * The key from an environment variable holding the same JSON array a keypair
42
+ * file holds, for hosts with no private disk (a serverless host's sensitive
43
+ * environment variables). The variable's value is never echoed.
44
+ */
45
+ export function loadProviderKeyFromEnv(input) {
46
+ const raw = input.env[input.name]?.trim();
47
+ if (!raw)
48
+ return { ok: false, message: `no key is set: put the provider wallet's keypair (a JSON array of 64 numbers) in ${input.name}` };
49
+ let bytes;
50
+ try {
51
+ const parsed = JSON.parse(raw);
52
+ if (!Array.isArray(parsed) || parsed.length !== 64 || !parsed.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {
53
+ return { ok: false, message: `${input.name} is not a 64-byte Solana keypair` };
54
+ }
55
+ bytes = parsed;
56
+ }
57
+ catch {
58
+ return { ok: false, message: `${input.name} could not be read as a keypair` };
59
+ }
60
+ return keyFromBytes(bytes, input.wallet, input.name);
61
+ }
62
+ function keyFromBytes(bytes, wallet, source) {
38
63
  let keypair;
39
64
  try {
40
- // Refuses a file whose public half does not belong to its secret half.
65
+ // Refuses a key whose public half does not belong to its secret half.
41
66
  keypair = Keypair.fromSecretKey(Uint8Array.from(bytes));
42
67
  }
43
68
  catch {
44
- return { ok: false, message: "the key file is not a valid Solana keypair" };
69
+ return { ok: false, message: `${source} is not a valid Solana keypair` };
45
70
  }
46
71
  finally {
47
72
  bytes.fill(0);
48
73
  }
49
- if (keypair.publicKey.toBase58() !== input.wallet)
50
- return { ok: false, message: "the key file does not belong to the wallet in the config" };
74
+ if (keypair.publicKey.toBase58() !== wallet)
75
+ return { ok: false, message: `${source} does not belong to the wallet in the config` };
51
76
  const privateKey = createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, Buffer.from(keypair.secretKey.subarray(0, 32))]), format: "der", type: "pkcs8" });
52
77
  return { ok: true, key: { keypair, signMessage: (message) => edSign(null, message, privateKey) } };
53
78
  }
@@ -3,13 +3,19 @@ export interface PendingCallSettle extends PendingSettle {
3
3
  escrow: string;
4
4
  /** SHA-256 of the request body the settle pays for: only the same request may collect the answer. */
5
5
  requestHash: string;
6
+ /** The lock this settle ends: its payer, and its lock slot as a decimal string. Only that payer may ask after it, and only that lock is ever declined in its place. */
7
+ payer?: string;
8
+ createdSlot?: string;
6
9
  /** `pending`: outcome not known. `landed`: it landed. `dropped`: it cannot land, and nothing was charged by it. */
7
10
  status: "pending" | "landed" | "dropped";
8
11
  }
9
12
  export interface PendingSettleStore {
10
- load(): PendingCallSettle[];
11
- /** Durable before it returns. */
12
- save(record: PendingCallSettle): void;
13
+ /** Every record, or at least every one still `pending`. */
14
+ load(): PendingCallSettle[] | Promise<PendingCallSettle[]>;
15
+ /** Durable before it returns (or before its promise resolves). */
16
+ save(record: PendingCallSettle): void | Promise<void>;
17
+ /** The `pending` record of one escrow, when the store can look one up without loading them all. */
18
+ findPending?(escrow: string): Promise<PendingCallSettle | undefined>;
13
19
  }
14
20
  export declare class FilePendingSettleStore implements PendingSettleStore {
15
21
  private readonly path;