@blockrun/llm 4.0.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -27,9 +27,42 @@ var RetiredEndpointError = class extends BlockrunError {
27
27
  }
28
28
  };
29
29
  var PaymentError = class extends BlockrunError {
30
- constructor(message) {
30
+ /** HTTP status of the refusal, when it came from the gateway. */
31
+ statusCode;
32
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
33
+ response;
34
+ constructor(message, options) {
31
35
  super(message);
32
36
  this.name = "PaymentError";
37
+ if (options?.statusCode !== void 0) this.statusCode = options.statusCode;
38
+ if (options?.response !== void 0) this.response = options.response;
39
+ }
40
+ };
41
+ var PAYMENT_REPLAY = "PAYMENT_REPLAY";
42
+ var PaymentReplayError = class extends PaymentError {
43
+ code = PAYMENT_REPLAY;
44
+ serverMessage;
45
+ details;
46
+ pollUrl;
47
+ jobId;
48
+ recoverable;
49
+ walletAuth;
50
+ payer;
51
+ constructor(message, options) {
52
+ super(message, options);
53
+ this.name = "PaymentReplayError";
54
+ const body = options?.response ?? {};
55
+ const str = (v) => typeof v === "string" && v ? v : void 0;
56
+ this.serverMessage = str(body.message);
57
+ this.details = str(body.details);
58
+ this.pollUrl = str(body.poll_url);
59
+ this.jobId = str(body.job_id) ?? str(body.id);
60
+ if (typeof body.recoverable === "boolean") this.recoverable = body.recoverable;
61
+ const walletAuth = body.wallet_auth;
62
+ if (walletAuth && typeof walletAuth === "object" && !Array.isArray(walletAuth)) {
63
+ this.walletAuth = walletAuth;
64
+ }
65
+ this.payer = str(body.payer);
33
66
  }
34
67
  };
35
68
  var APIError = class extends BlockrunError {
@@ -186,6 +219,83 @@ function validateResourceUrl(url, baseUrl) {
186
219
  return `${baseUrl}/v1/chat/completions`;
187
220
  }
188
221
  }
222
+ var REPLAY_FIELDS = [
223
+ "error",
224
+ "message",
225
+ "details",
226
+ "code",
227
+ "payer",
228
+ "id",
229
+ "job_id",
230
+ "poll_url",
231
+ "recoverable",
232
+ "wallet_auth",
233
+ "status"
234
+ ];
235
+ function asRecord(body) {
236
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
237
+ }
238
+ function bodyCode(body) {
239
+ if (typeof body.code === "string") return body.code;
240
+ const nested = asRecord(body.error);
241
+ return typeof nested.code === "string" ? nested.code : void 0;
242
+ }
243
+ function isPaymentReplay(body) {
244
+ return bodyCode(asRecord(body))?.toUpperCase() === PAYMENT_REPLAY;
245
+ }
246
+ function namesEarlierResult(body) {
247
+ const record = asRecord(body);
248
+ return ["recoverable", "poll_url", "job_id", "wallet_auth"].some((key) => Boolean(record[key]));
249
+ }
250
+ function boundedString(value, max) {
251
+ return typeof value === "string" && value.length > 0 && value.length < max ? value : void 0;
252
+ }
253
+ function replayError(body, statusCode) {
254
+ const detail = {};
255
+ for (const key of REPLAY_FIELDS) if (body[key] !== void 0 && body[key] !== null) detail[key] = body[key];
256
+ detail.code = PAYMENT_REPLAY;
257
+ for (const field of PAYMENT_FACT_FIELDS) if (typeof body[field] === "string") detail[field] = body[field];
258
+ const serverMessage = typeof body.message === "string" ? body.message : "";
259
+ const pollUrl = typeof body.poll_url === "string" ? body.poll_url : "";
260
+ const details = typeof body.details === "string" ? body.details : "";
261
+ let text = "Payment authorization already used (PAYMENT_REPLAY): an earlier request with this authorization was accepted and may already have been charged. Nothing new was signed; a fresh payment for the same request can charge twice.";
262
+ if (pollUrl) text += ` Its result can be collected at ${pollUrl}.`;
263
+ if (serverMessage) text += ` Gateway: ${serverMessage}`;
264
+ if (details && details !== serverMessage) text += ` (${details})`;
265
+ return new PaymentReplayError(text, { statusCode, response: detail });
266
+ }
267
+ function paymentRejectedErrorFromBody(body, statusCode = 402, options = {}) {
268
+ const record = asRecord(body);
269
+ if (options.replay ?? isPaymentReplay(record)) return replayError(record, statusCode);
270
+ const sanitized = { ...sanitizeErrorResponse(record) };
271
+ const details = boundedString(record.details, 256);
272
+ if (details) sanitized.details = details;
273
+ const invalidMessage = boundedString(record.invalidMessage, 256);
274
+ if (invalidMessage) sanitized.invalidMessage = invalidMessage;
275
+ const reason = boundedString(record.reason, 128);
276
+ if (reason) sanitized.reason = reason;
277
+ const nested = asRecord(record.error);
278
+ const title = typeof record.error === "string" ? record.error : typeof nested.message === "string" ? nested.message : "";
279
+ const serverMessage = typeof record.message === "string" ? record.message : "";
280
+ let detailPart = details || title;
281
+ if (!details && serverMessage && serverMessage !== detailPart) {
282
+ detailPart = detailPart ? `${detailPart}: ${serverMessage}` : serverMessage;
283
+ }
284
+ if (invalidMessage) detailPart = detailPart ? `${detailPart} (${invalidMessage})` : invalidMessage;
285
+ const message = detailPart ? `Payment rejected by gateway: ${detailPart}` : `Payment rejected by gateway (HTTP ${statusCode}); it gave no reason`;
286
+ return new PaymentError(message, { statusCode, response: sanitized });
287
+ }
288
+ async function buildPaymentRejectedError(response, options = {}) {
289
+ let body;
290
+ try {
291
+ const text = await response.text();
292
+ body = text ? JSON.parse(text) : {};
293
+ } catch {
294
+ body = {};
295
+ }
296
+ const replay = options.replay ? options.replay(body) || void 0 : void 0;
297
+ return paymentRejectedErrorFromBody(body, response.status, { replay });
298
+ }
189
299
 
190
300
  // src/api-key.ts
191
301
  var TRANSIENT_STATUS = /* @__PURE__ */ new Set([502, 503, 504, 522, 524]);
@@ -5069,7 +5179,7 @@ function getCostSummary() {
5069
5179
  }
5070
5180
 
5071
5181
  // src/version.ts
5072
- var SDK_VERSION = "4.0.0";
5182
+ var SDK_VERSION = "4.2.0";
5073
5183
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5074
5184
 
5075
5185
  // src/client.ts
@@ -5637,7 +5747,7 @@ var LLMClient = class _LLMClient {
5637
5747
  body: JSON.stringify(body)
5638
5748
  }, timeoutMs);
5639
5749
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5640
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5750
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5641
5751
  if (!retryResp2.ok) {
5642
5752
  let errorBody;
5643
5753
  try {
@@ -5651,7 +5761,7 @@ var LLMClient = class _LLMClient {
5651
5761
  }
5652
5762
  }
5653
5763
  if (retryResponse.status === 402) {
5654
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
5764
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
5655
5765
  }
5656
5766
  if (!retryResponse.ok) {
5657
5767
  let errorBody;
@@ -5857,7 +5967,7 @@ var LLMClient = class _LLMClient {
5857
5967
  },
5858
5968
  body: JSON.stringify(body)
5859
5969
  });
5860
- if (streamResp.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5970
+ if (streamResp.status === 402) throw await buildPaymentRejectedError(streamResp, { replay: namesEarlierResult });
5861
5971
  if (!streamResp.ok) {
5862
5972
  let errorBody;
5863
5973
  try {
@@ -5984,7 +6094,7 @@ var LLMClient = class _LLMClient {
5984
6094
  body: JSON.stringify(body)
5985
6095
  });
5986
6096
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5987
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6097
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5988
6098
  if (!retryResp2.ok) {
5989
6099
  let errorBody;
5990
6100
  try {
@@ -5999,7 +6109,7 @@ var LLMClient = class _LLMClient {
5999
6109
  }
6000
6110
  }
6001
6111
  if (retryResponse.status === 402) {
6002
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6112
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6003
6113
  }
6004
6114
  if (!retryResponse.ok) {
6005
6115
  let errorBody;
@@ -6124,7 +6234,7 @@ var LLMClient = class _LLMClient {
6124
6234
  }
6125
6235
  });
6126
6236
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6127
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6237
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6128
6238
  if (!retryResp2.ok) {
6129
6239
  let errorBody;
6130
6240
  try {
@@ -6139,7 +6249,7 @@ var LLMClient = class _LLMClient {
6139
6249
  }
6140
6250
  }
6141
6251
  if (retryResponse.status === 402) {
6142
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6252
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6143
6253
  }
6144
6254
  if (!retryResponse.ok) {
6145
6255
  let errorBody;
@@ -6904,9 +7014,7 @@ var ImageClient = class {
6904
7014
  body: JSON.stringify(body)
6905
7015
  });
6906
7016
  if (retryResponse.status === 402) {
6907
- throw new PaymentError(
6908
- "Payment was rejected. Check your wallet balance."
6909
- );
7017
+ throw await buildPaymentRejectedError(retryResponse);
6910
7018
  }
6911
7019
  if (!retryResponse.ok) {
6912
7020
  let errorBody;
@@ -6959,6 +7067,7 @@ var ImageClient = class {
6959
7067
  continue;
6960
7068
  }
6961
7069
  const pollBody = await pollResp.json().catch(() => ({}));
7070
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
6962
7071
  if (!pollResp.ok) {
6963
7072
  throw new APIError(
6964
7073
  `API error during poll: ${pollResp.status}`,
@@ -7158,7 +7267,7 @@ var MusicClient = class {
7158
7267
  body: JSON.stringify(body)
7159
7268
  });
7160
7269
  if (retryResponse.status === 402) {
7161
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7270
+ throw await buildPaymentRejectedError(retryResponse);
7162
7271
  }
7163
7272
  if (!retryResponse.ok) {
7164
7273
  let errorBody;
@@ -7217,6 +7326,7 @@ var MusicClient = class {
7217
7326
  }
7218
7327
  if (pollResp.status === 202 || TRANSIENT_POLL_STATUSES.has(pollResp.status)) continue;
7219
7328
  const pollBody = await pollResp.json().catch(() => ({}));
7329
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7220
7330
  if (!pollResp.ok) {
7221
7331
  throw new APIError(
7222
7332
  `API error during poll of ${pollPath}: ${pollResp.status}`,
@@ -7437,7 +7547,7 @@ var SpeechClient = class {
7437
7547
  body: JSON.stringify(body)
7438
7548
  });
7439
7549
  if (retryResponse.status === 402) {
7440
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7550
+ throw await buildPaymentRejectedError(retryResponse);
7441
7551
  }
7442
7552
  if (!retryResponse.ok) {
7443
7553
  let errorBody;
@@ -7709,7 +7819,7 @@ var VideoClient = class {
7709
7819
  body: JSON.stringify(body)
7710
7820
  });
7711
7821
  if (submitResp.status === 402) {
7712
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7822
+ throw await buildPaymentRejectedError(submitResp);
7713
7823
  }
7714
7824
  if (submitResp.status !== 200 && submitResp.status !== 202) {
7715
7825
  await this.throwApiError(submitResp, "Submit failed");
@@ -7759,6 +7869,9 @@ var VideoClient = class {
7759
7869
  return data;
7760
7870
  }
7761
7871
  if (pollResp.status === 402) {
7872
+ if (isPaymentReplay(pollData)) {
7873
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status, { replay: true });
7874
+ }
7762
7875
  if (resignsLeft > 0) {
7763
7876
  resignsLeft--;
7764
7877
  const challenge = await this.fetchWithTimeout(pollUrl, { method: "GET" });
@@ -7770,9 +7883,7 @@ var VideoClient = class {
7770
7883
  continue;
7771
7884
  }
7772
7885
  }
7773
- throw new PaymentError(
7774
- "Payment verification failed mid-poll (not a signature-expiry). Check the wallet balance and that you poll from the wallet that submitted the job."
7775
- );
7886
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status);
7776
7887
  }
7777
7888
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
7778
7889
  await this.throwApiError(pollResp, "Poll failed");
@@ -8036,7 +8147,7 @@ var VoiceClient = class {
8036
8147
  body: JSON.stringify(body)
8037
8148
  });
8038
8149
  if (retryResponse.status === 402) {
8039
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8150
+ throw await buildPaymentRejectedError(retryResponse);
8040
8151
  }
8041
8152
  if (!retryResponse.ok) {
8042
8153
  let errorBody;
@@ -8268,7 +8379,7 @@ var PhoneClient = class {
8268
8379
  body: JSON.stringify(body)
8269
8380
  });
8270
8381
  if (retry.status === 402) {
8271
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8382
+ throw await buildPaymentRejectedError(retry);
8272
8383
  }
8273
8384
  const data = await this.unwrap(retry, true);
8274
8385
  if (!settlementSkipped(retry)) {
@@ -8436,7 +8547,7 @@ var PortraitClient = class {
8436
8547
  body: JSON.stringify(body)
8437
8548
  });
8438
8549
  if (retry.status === 402) {
8439
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8550
+ throw await buildPaymentRejectedError(retry);
8440
8551
  }
8441
8552
  const data = await this.unwrap(retry, true);
8442
8553
  if (!settlementSkipped(retry)) {
@@ -8598,7 +8709,7 @@ var SearchClient = class {
8598
8709
  body: JSON.stringify(body)
8599
8710
  });
8600
8711
  if (retry.status === 402) {
8601
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8712
+ throw await buildPaymentRejectedError(retry);
8602
8713
  }
8603
8714
  if (!retry.ok) {
8604
8715
  let errorBody;
@@ -8789,7 +8900,7 @@ var PriceClient = class {
8789
8900
  headers: { "PAYMENT-SIGNATURE": paymentPayload }
8790
8901
  });
8791
8902
  if (retry.status === 402) {
8792
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8903
+ throw await buildPaymentRejectedError(retry);
8793
8904
  }
8794
8905
  if (!retry.ok) {
8795
8906
  let errorBody;
@@ -8980,7 +9091,7 @@ var SurfClient = class {
8980
9091
  }
8981
9092
  const retry = await this.fetchWithTimeout(url, retryInit);
8982
9093
  if (retry.status === 402) {
8983
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9094
+ throw await buildPaymentRejectedError(retry);
8984
9095
  }
8985
9096
  if (!retry.ok) {
8986
9097
  await this.throwApiError(retry, `Surf request failed after payment (${method} ${url})`);
@@ -9248,7 +9359,7 @@ var RpcClient = class {
9248
9359
  body: JSON.stringify(body)
9249
9360
  });
9250
9361
  if (retryResponse.status === 402) {
9251
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9362
+ throw await buildPaymentRejectedError(retryResponse);
9252
9363
  }
9253
9364
  if (!retryResponse.ok) {
9254
9365
  let errorBody;
@@ -9423,7 +9534,7 @@ var BlockrunClient = class {
9423
9534
  body: JSON.stringify(body ?? {})
9424
9535
  });
9425
9536
  if (submitResp.status === 402) {
9426
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9537
+ throw await buildPaymentRejectedError(submitResp);
9427
9538
  }
9428
9539
  if (submitResp.status !== 200 && submitResp.status !== 202) {
9429
9540
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
@@ -9519,9 +9630,7 @@ var BlockrunClient = class {
9519
9630
  body: requestBody
9520
9631
  });
9521
9632
  if (streamResp.status === 402) {
9522
- throw new PaymentError(
9523
- "Payment was rejected. Check your wallet balance."
9524
- );
9633
+ throw await buildPaymentRejectedError(streamResp);
9525
9634
  }
9526
9635
  if (!streamResp.ok) {
9527
9636
  await this.throwApiError(streamResp, `stream failed after payment (${url})`);
@@ -9598,9 +9707,7 @@ var BlockrunClient = class {
9598
9707
  }
9599
9708
  const retry = await this.fetchWithTimeout(url, retryInit);
9600
9709
  if (retry.status === 402) {
9601
- throw new PaymentError(
9602
- "Payment was rejected. Check your wallet balance."
9603
- );
9710
+ throw await buildPaymentRejectedError(retry);
9604
9711
  }
9605
9712
  if (!retry.ok) {
9606
9713
  await this.throwApiError(retry, `${method} ${url} failed after payment`);
@@ -10232,6 +10339,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
10232
10339
  };
10233
10340
  }
10234
10341
 
10342
+ // src/stream-receipt.ts
10343
+ var STREAM_RECEIPT_HEADER = "X-BlockRun-Stream-Receipt";
10344
+ var RECEIPT_EVENT = "payment-response";
10345
+ var EVENT_END = /\r?\n\r?\n/;
10346
+ function isReceiptBlock(block) {
10347
+ return block.split(/\r?\n/).some((line) => line.trim() === `event: ${RECEIPT_EVENT}` || line.trim() === `event:${RECEIPT_EVENT}`);
10348
+ }
10349
+ function parseReceiptBlock(block) {
10350
+ const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
10351
+ try {
10352
+ const parsed = JSON.parse(data);
10353
+ if (typeof parsed?.status !== "string") return void 0;
10354
+ return { status: parsed.status, ...typeof parsed.payment_response === "string" ? { paymentResponse: parsed.payment_response } : {} };
10355
+ } catch {
10356
+ return void 0;
10357
+ }
10358
+ }
10359
+ function withoutReceiptEvent(body) {
10360
+ const decoder = new TextDecoder();
10361
+ const encoder = new TextEncoder();
10362
+ let pending = "";
10363
+ return body.pipeThrough(
10364
+ new TransformStream({
10365
+ transform(chunk, controller) {
10366
+ pending += decoder.decode(chunk, { stream: true });
10367
+ let out = "";
10368
+ for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
10369
+ const end = match.index + match[0].length;
10370
+ const block = pending.slice(0, end);
10371
+ pending = pending.slice(end);
10372
+ if (!isReceiptBlock(block)) out += block;
10373
+ }
10374
+ if (out) controller.enqueue(encoder.encode(out));
10375
+ },
10376
+ flush(controller) {
10377
+ const rest = pending + decoder.decode();
10378
+ if (rest && !isReceiptBlock(rest)) controller.enqueue(encoder.encode(rest));
10379
+ }
10380
+ })
10381
+ );
10382
+ }
10383
+ async function readReceiptEvent(body) {
10384
+ const reader = body.getReader();
10385
+ const decoder = new TextDecoder();
10386
+ let pending = "";
10387
+ try {
10388
+ for (; ; ) {
10389
+ const { done, value } = await reader.read();
10390
+ if (done) return void 0;
10391
+ pending += decoder.decode(value, { stream: true });
10392
+ for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
10393
+ const end = match.index + match[0].length;
10394
+ const block = pending.slice(0, end);
10395
+ pending = pending.slice(end);
10396
+ if (isReceiptBlock(block)) {
10397
+ void reader.cancel().catch(() => void 0);
10398
+ return parseReceiptBlock(block);
10399
+ }
10400
+ }
10401
+ }
10402
+ } catch {
10403
+ return void 0;
10404
+ } finally {
10405
+ try {
10406
+ reader.releaseLock();
10407
+ } catch {
10408
+ }
10409
+ }
10410
+ }
10411
+ async function lookupReceipt(apiUrl, paymentHeader, opts = {}) {
10412
+ const doFetch = opts.fetch ?? fetch;
10413
+ const attempts = opts.attempts ?? 8;
10414
+ const delayMs = opts.delayMs ?? 2e3;
10415
+ const sleep4 = opts.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
10416
+ for (let attempt = 0; attempt < attempts; attempt++) {
10417
+ if (attempt > 0) await sleep4(Math.min(delayMs * 2 ** (attempt - 1), 15e3));
10418
+ let answer;
10419
+ try {
10420
+ const res = await doFetch(`${apiUrl}/v1/batch/receipt`, {
10421
+ method: "POST",
10422
+ headers: { "Content-Type": "application/json" },
10423
+ body: JSON.stringify({ paymentHeader })
10424
+ });
10425
+ if (res.status >= 500) continue;
10426
+ if (!res.ok) return void 0;
10427
+ answer = await res.json();
10428
+ } catch {
10429
+ continue;
10430
+ }
10431
+ if (answer?.status !== "pending") return answer;
10432
+ }
10433
+ return void 0;
10434
+ }
10435
+ function isEventStream(response) {
10436
+ return (response.headers.get("content-type") ?? "").includes("text/event-stream");
10437
+ }
10438
+
10235
10439
  // src/solana-batch.ts
10236
10440
  import { AsyncLocalStorage } from "async_hooks";
10237
10441
  import { randomUUID } from "crypto";
@@ -12923,18 +13127,23 @@ async function readPaymentFailureBody(response) {
12923
13127
  }
12924
13128
  }
12925
13129
  async function isSafeStaleBlockhashResponse(response) {
13130
+ const body = await readPaymentFailure(response);
13131
+ return body !== null && isSafeStaleBlockhashBody(body);
13132
+ }
13133
+ async function readPaymentFailure(response) {
12926
13134
  const length = Number(response.headers.get("content-length") || "0");
12927
- if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return false;
13135
+ if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return null;
12928
13136
  const text = await readPaymentFailureBody(response);
12929
- if (text === null) return false;
12930
- let body;
13137
+ if (text === null) return null;
12931
13138
  try {
12932
13139
  const parsed = JSON.parse(text);
12933
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
12934
- body = parsed;
13140
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
13141
+ return parsed;
12935
13142
  } catch {
12936
- return false;
13143
+ return null;
12937
13144
  }
13145
+ }
13146
+ function isSafeStaleBlockhashBody(body) {
12938
13147
  const nested = body.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error : void 0;
12939
13148
  const errorLabel = typeof body.error === "string" ? body.error : "";
12940
13149
  const code = normalizePaymentSignal(body.code ?? nested?.code);
@@ -13289,6 +13498,7 @@ var SolanaLLMClient = class {
13289
13498
  * @returns a response whose body has not been read.
13290
13499
  */
13291
13500
  async openPaidStream(url, requestBody) {
13501
+ const closesAtStart = await this.batchPayer?.closeFence();
13292
13502
  for (let staleRetries = 0; ; ) {
13293
13503
  const response = await this.fetchWithTimeout(url, {
13294
13504
  method: "POST",
@@ -13306,11 +13516,15 @@ var SolanaLLMClient = class {
13306
13516
  throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
13307
13517
  }
13308
13518
  try {
13309
- const { paymentPayload, costUsd } = await this.signPaymentFrom402(
13310
- url,
13311
- response,
13312
- staleRetries > 0
13313
- );
13519
+ let exactPayment;
13520
+ if (this.batchPayer && staleRetries === 0) {
13521
+ const batch = await this.openBatchStream(url, requestBody, await this.readPaymentRequired(response), closesAtStart);
13522
+ if (batch.kind === "stream") return batch.response;
13523
+ exactPayment = await this.signExactPayment(url, batch.paymentRequired, false);
13524
+ } else {
13525
+ exactPayment = await this.signPaymentFrom402(url, response, staleRetries > 0);
13526
+ }
13527
+ const { paymentPayload, costUsd } = exactPayment;
13314
13528
  const paid = await this.fetchWithTimeout(url, {
13315
13529
  method: "POST",
13316
13530
  headers: {
@@ -13330,6 +13544,82 @@ var SolanaLLMClient = class {
13330
13544
  }
13331
13545
  }
13332
13546
  }
13547
+ /**
13548
+ * Pay a stream with batch-settlement, when the gateway offers it.
13549
+ *
13550
+ * A stream's charge is committed after its headers are sent, so its receipt
13551
+ * cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
13552
+ * buffered call with. The request asks for it as a final SSE event instead
13553
+ * ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
13554
+ * its branch at once, live, with the receipt event taken out; the payer reads
13555
+ * the other branch to that event and is handed the answer with the receipt
13556
+ * restored as its header, so the channel advances exactly as it does for a
13557
+ * buffered call. A stream that ends without the event (cut, failed upstream,
13558
+ * an older gateway) is looked up at `POST /v1/batch/receipt`.
13559
+ *
13560
+ * The payer's branch reads to the receipt even when the caller stops early,
13561
+ * so the connection stays open: the gateway charges for what the model
13562
+ * generates either way, and only an open stream brings its receipt back.
13563
+ *
13564
+ * @returns the caller's stream, or the requirements to pay `exact` against
13565
+ * when batch is unavailable for this call.
13566
+ */
13567
+ async openBatchStream(url, requestBody, paymentRequired, closesAtStart) {
13568
+ const headers = { "Content-Type": "application/json", "User-Agent": USER_AGENT, [STREAM_RECEIPT_HEADER]: "1" };
13569
+ let handOff;
13570
+ const handedOff = new Promise((resolve2) => {
13571
+ handOff = resolve2;
13572
+ });
13573
+ const attempt = this.batchPayer.pay(
13574
+ paymentRequired,
13575
+ async (paymentHeaders) => {
13576
+ const answer = await this.fetchWithTimeout(url, { method: "POST", headers: { ...headers, ...paymentHeaders }, body: requestBody });
13577
+ if (!answer.ok || !answer.body || !isEventStream(answer)) return answer;
13578
+ const [forCaller, forPayer] = answer.body.tee();
13579
+ handOff(new Response(withoutReceiptEvent(forCaller), { status: answer.status, statusText: answer.statusText, headers: answer.headers }));
13580
+ let receipt = (await readReceiptEvent(forPayer))?.paymentResponse;
13581
+ const signed = paymentHeaders["PAYMENT-SIGNATURE"];
13582
+ if (receipt === void 0 && signed) receipt = (await lookupReceipt(this.apiUrl, signed))?.payment_response;
13583
+ const settled2 = new Headers(answer.headers);
13584
+ if (receipt) settled2.set("PAYMENT-RESPONSE", receipt);
13585
+ return new Response(null, { status: answer.status, statusText: answer.statusText, headers: settled2 });
13586
+ },
13587
+ // A fresh, unpaid challenge after a 429 wait, as chatCompletion sends.
13588
+ async () => {
13589
+ const challenge = await this.sendUnpaid(url, { method: "POST", headers, body: requestBody });
13590
+ if (challenge.status === 402) {
13591
+ try {
13592
+ return { kind: "challenge", paymentRequired: await this.readPaymentRequired(challenge) };
13593
+ } catch (error) {
13594
+ throw withDisposition(error, "unpaid");
13595
+ }
13596
+ }
13597
+ if (challenge.ok) return { kind: "served", response: challenge };
13598
+ throw await unpaidApiError(challenge);
13599
+ },
13600
+ closesAtStart
13601
+ );
13602
+ const settled = attempt.then(
13603
+ (outcome2) => ({ outcome: outcome2 }),
13604
+ (error) => ({ error })
13605
+ );
13606
+ const first = await Promise.race([handedOff.then((response) => ({ response })), settled]);
13607
+ if ("response" in first) {
13608
+ void settled.then((result) => {
13609
+ if ("outcome" in result && result.outcome.kind === "paid") this.recordSettlement(result.outcome.chargedUsd, result.outcome.response);
13610
+ });
13611
+ return { kind: "stream", response: first.response };
13612
+ }
13613
+ if ("error" in first) throw first.error;
13614
+ const outcome = first.outcome;
13615
+ if (outcome.kind === "paid") {
13616
+ this.recordSettlement(outcome.chargedUsd, outcome.response);
13617
+ return { kind: "stream", response: outcome.response };
13618
+ }
13619
+ if (outcome.kind === "served") return { kind: "stream", response: outcome.response };
13620
+ if (outcome.kind === "failed") throw outcome.error;
13621
+ return { kind: "exact", paymentRequired: outcome.paymentRequired ?? paymentRequired };
13622
+ }
13333
13623
  /**
13334
13624
  * Resolve an endpoint path against this client's API root.
13335
13625
  *
@@ -13927,6 +14217,9 @@ var SolanaLLMClient = class {
13927
14217
  lastStatus = data.status || lastStatus;
13928
14218
  failIfFailed(data, paid.status);
13929
14219
  if (paid.status === 200 && lastStatus === "completed") return deliver(data, paid);
14220
+ if (paid.status === 402 && isPaymentReplay(data)) {
14221
+ throw withDisposition(paymentRejectedErrorFromBody(data, 402, { replay: true }), "paid-or-in-doubt");
14222
+ }
13930
14223
  if (paid.status === 402 && kind === "video") {
13931
14224
  if (data.error === "Payment verification failed" && !await isSafeStaleBlockhashResponse(new Response(JSON.stringify(data), { status: 402 }))) {
13932
14225
  throw new PaymentError(
@@ -14201,10 +14494,11 @@ var SolanaLLMClient = class {
14201
14494
  */
14202
14495
  async assertPaid(response) {
14203
14496
  if (response.status === 402) {
14204
- if (await isSafeStaleBlockhashResponse(response)) {
14497
+ const body = await readPaymentFailure(response);
14498
+ if (body !== null && isSafeStaleBlockhashBody(body)) {
14205
14499
  throw withDisposition(new SafeStaleBlockhashError(), "unpaid");
14206
14500
  }
14207
- throw withDisposition(new PaymentError("Payment was rejected. Check your Solana USDC balance."), "paid-or-in-doubt");
14501
+ throw withDisposition(paymentRejectedErrorFromBody(body ?? {}, 402), "paid-or-in-doubt");
14208
14502
  }
14209
14503
  if (!response.ok) {
14210
14504
  let errorBody;
@@ -14764,9 +15058,7 @@ var AnthropicClient = class {
14764
15058
  signal: controller.signal
14765
15059
  });
14766
15060
  if (response.status === 402) {
14767
- throw new Error(
14768
- "Payment was rejected. Check your wallet balance."
14769
- );
15061
+ throw await buildPaymentRejectedError(response);
14770
15062
  }
14771
15063
  }
14772
15064
  return response;
@@ -14813,10 +15105,12 @@ export {
14813
15105
  MusicClient,
14814
15106
  NETWORK_ALIASES,
14815
15107
  OpenAI,
15108
+ PAYMENT_REPLAY,
14816
15109
  PHONE_PRICES,
14817
15110
  PORTAL_URL,
14818
15111
  PORTRAIT_ENROLLMENT_PRICE_USD,
14819
15112
  PaymentError,
15113
+ PaymentReplayError,
14820
15114
  PhoneClient,
14821
15115
  PortraitClient,
14822
15116
  PriceClient,
@@ -14839,6 +15133,7 @@ export {
14839
15133
  VoiceClient,
14840
15134
  WALLET_DIR_PATH,
14841
15135
  WALLET_FILE_PATH,
15136
+ buildPaymentRejectedError,
14842
15137
  clearCache,
14843
15138
  createPaymentPayload,
14844
15139
  createSolanaPaymentPayload,
@@ -14863,12 +15158,14 @@ export {
14863
15158
  getWalletAddress,
14864
15159
  importSolanaWallet,
14865
15160
  importWallet,
15161
+ isPaymentReplay,
14866
15162
  listDiscoveredSolanaWallets,
14867
15163
  listDiscoveredWallets2 as listDiscoveredWallets,
14868
15164
  loadSolanaWallet,
14869
15165
  loadWallet,
14870
15166
  logCost,
14871
15167
  parsePaymentRequired,
15168
+ paymentRejectedErrorFromBody,
14872
15169
  readSettlement,
14873
15170
  retryDisposition,
14874
15171
  saveSolanaWallet,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "4.0.0",
3
+ "version": "4.2.0",
4
4
  "type": "module",
5
5
  "description": "TypeScript SDK for BlockRun - every frontier model behind one OpenAI-compatible client. Pay with a BlockRun API key or per-call in USDC. Smart routing picks the cheapest capable model. No rate limits.",
6
6
  "main": "dist/index.cjs",