@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.cjs CHANGED
@@ -51,10 +51,12 @@ __export(index_exports, {
51
51
  MusicClient: () => MusicClient,
52
52
  NETWORK_ALIASES: () => NETWORK_ALIASES,
53
53
  OpenAI: () => OpenAI,
54
+ PAYMENT_REPLAY: () => PAYMENT_REPLAY,
54
55
  PHONE_PRICES: () => PHONE_PRICES,
55
56
  PORTAL_URL: () => PORTAL_URL,
56
57
  PORTRAIT_ENROLLMENT_PRICE_USD: () => PORTRAIT_ENROLLMENT_PRICE_USD,
57
58
  PaymentError: () => PaymentError,
59
+ PaymentReplayError: () => PaymentReplayError,
58
60
  PhoneClient: () => PhoneClient,
59
61
  PortraitClient: () => PortraitClient,
60
62
  PriceClient: () => PriceClient,
@@ -77,6 +79,7 @@ __export(index_exports, {
77
79
  VoiceClient: () => VoiceClient,
78
80
  WALLET_DIR_PATH: () => WALLET_DIR_PATH,
79
81
  WALLET_FILE_PATH: () => WALLET_FILE_PATH,
82
+ buildPaymentRejectedError: () => buildPaymentRejectedError,
80
83
  clearCache: () => clearCache,
81
84
  createPaymentPayload: () => createPaymentPayload,
82
85
  createSolanaPaymentPayload: () => createSolanaPaymentPayload,
@@ -101,12 +104,14 @@ __export(index_exports, {
101
104
  getWalletAddress: () => getWalletAddress,
102
105
  importSolanaWallet: () => importSolanaWallet,
103
106
  importWallet: () => importWallet,
107
+ isPaymentReplay: () => isPaymentReplay,
104
108
  listDiscoveredSolanaWallets: () => listDiscoveredSolanaWallets,
105
109
  listDiscoveredWallets: () => listDiscoveredWallets2,
106
110
  loadSolanaWallet: () => loadSolanaWallet,
107
111
  loadWallet: () => loadWallet,
108
112
  logCost: () => logCost,
109
113
  parsePaymentRequired: () => parsePaymentRequired,
114
+ paymentRejectedErrorFromBody: () => paymentRejectedErrorFromBody,
110
115
  readSettlement: () => readSettlement,
111
116
  retryDisposition: () => retryDisposition,
112
117
  saveSolanaWallet: () => saveSolanaWallet,
@@ -160,9 +165,42 @@ var RetiredEndpointError = class extends BlockrunError {
160
165
  }
161
166
  };
162
167
  var PaymentError = class extends BlockrunError {
163
- constructor(message) {
168
+ /** HTTP status of the refusal, when it came from the gateway. */
169
+ statusCode;
170
+ /** The gateway's refusal body, sanitized; recovery fields kept verbatim. */
171
+ response;
172
+ constructor(message, options) {
164
173
  super(message);
165
174
  this.name = "PaymentError";
175
+ if (options?.statusCode !== void 0) this.statusCode = options.statusCode;
176
+ if (options?.response !== void 0) this.response = options.response;
177
+ }
178
+ };
179
+ var PAYMENT_REPLAY = "PAYMENT_REPLAY";
180
+ var PaymentReplayError = class extends PaymentError {
181
+ code = PAYMENT_REPLAY;
182
+ serverMessage;
183
+ details;
184
+ pollUrl;
185
+ jobId;
186
+ recoverable;
187
+ walletAuth;
188
+ payer;
189
+ constructor(message, options) {
190
+ super(message, options);
191
+ this.name = "PaymentReplayError";
192
+ const body = options?.response ?? {};
193
+ const str = (v) => typeof v === "string" && v ? v : void 0;
194
+ this.serverMessage = str(body.message);
195
+ this.details = str(body.details);
196
+ this.pollUrl = str(body.poll_url);
197
+ this.jobId = str(body.job_id) ?? str(body.id);
198
+ if (typeof body.recoverable === "boolean") this.recoverable = body.recoverable;
199
+ const walletAuth = body.wallet_auth;
200
+ if (walletAuth && typeof walletAuth === "object" && !Array.isArray(walletAuth)) {
201
+ this.walletAuth = walletAuth;
202
+ }
203
+ this.payer = str(body.payer);
166
204
  }
167
205
  };
168
206
  var APIError = class extends BlockrunError {
@@ -319,6 +357,83 @@ function validateResourceUrl(url, baseUrl) {
319
357
  return `${baseUrl}/v1/chat/completions`;
320
358
  }
321
359
  }
360
+ var REPLAY_FIELDS = [
361
+ "error",
362
+ "message",
363
+ "details",
364
+ "code",
365
+ "payer",
366
+ "id",
367
+ "job_id",
368
+ "poll_url",
369
+ "recoverable",
370
+ "wallet_auth",
371
+ "status"
372
+ ];
373
+ function asRecord(body) {
374
+ return body && typeof body === "object" && !Array.isArray(body) ? body : {};
375
+ }
376
+ function bodyCode(body) {
377
+ if (typeof body.code === "string") return body.code;
378
+ const nested = asRecord(body.error);
379
+ return typeof nested.code === "string" ? nested.code : void 0;
380
+ }
381
+ function isPaymentReplay(body) {
382
+ return bodyCode(asRecord(body))?.toUpperCase() === PAYMENT_REPLAY;
383
+ }
384
+ function namesEarlierResult(body) {
385
+ const record = asRecord(body);
386
+ return ["recoverable", "poll_url", "job_id", "wallet_auth"].some((key) => Boolean(record[key]));
387
+ }
388
+ function boundedString(value, max) {
389
+ return typeof value === "string" && value.length > 0 && value.length < max ? value : void 0;
390
+ }
391
+ function replayError(body, statusCode) {
392
+ const detail = {};
393
+ for (const key of REPLAY_FIELDS) if (body[key] !== void 0 && body[key] !== null) detail[key] = body[key];
394
+ detail.code = PAYMENT_REPLAY;
395
+ for (const field of PAYMENT_FACT_FIELDS) if (typeof body[field] === "string") detail[field] = body[field];
396
+ const serverMessage = typeof body.message === "string" ? body.message : "";
397
+ const pollUrl = typeof body.poll_url === "string" ? body.poll_url : "";
398
+ const details = typeof body.details === "string" ? body.details : "";
399
+ 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.";
400
+ if (pollUrl) text += ` Its result can be collected at ${pollUrl}.`;
401
+ if (serverMessage) text += ` Gateway: ${serverMessage}`;
402
+ if (details && details !== serverMessage) text += ` (${details})`;
403
+ return new PaymentReplayError(text, { statusCode, response: detail });
404
+ }
405
+ function paymentRejectedErrorFromBody(body, statusCode = 402, options = {}) {
406
+ const record = asRecord(body);
407
+ if (options.replay ?? isPaymentReplay(record)) return replayError(record, statusCode);
408
+ const sanitized = { ...sanitizeErrorResponse(record) };
409
+ const details = boundedString(record.details, 256);
410
+ if (details) sanitized.details = details;
411
+ const invalidMessage = boundedString(record.invalidMessage, 256);
412
+ if (invalidMessage) sanitized.invalidMessage = invalidMessage;
413
+ const reason = boundedString(record.reason, 128);
414
+ if (reason) sanitized.reason = reason;
415
+ const nested = asRecord(record.error);
416
+ const title = typeof record.error === "string" ? record.error : typeof nested.message === "string" ? nested.message : "";
417
+ const serverMessage = typeof record.message === "string" ? record.message : "";
418
+ let detailPart = details || title;
419
+ if (!details && serverMessage && serverMessage !== detailPart) {
420
+ detailPart = detailPart ? `${detailPart}: ${serverMessage}` : serverMessage;
421
+ }
422
+ if (invalidMessage) detailPart = detailPart ? `${detailPart} (${invalidMessage})` : invalidMessage;
423
+ const message = detailPart ? `Payment rejected by gateway: ${detailPart}` : `Payment rejected by gateway (HTTP ${statusCode}); it gave no reason`;
424
+ return new PaymentError(message, { statusCode, response: sanitized });
425
+ }
426
+ async function buildPaymentRejectedError(response, options = {}) {
427
+ let body;
428
+ try {
429
+ const text = await response.text();
430
+ body = text ? JSON.parse(text) : {};
431
+ } catch {
432
+ body = {};
433
+ }
434
+ const replay = options.replay ? options.replay(body) || void 0 : void 0;
435
+ return paymentRejectedErrorFromBody(body, response.status, { replay });
436
+ }
322
437
 
323
438
  // src/api-key.ts
324
439
  var TRANSIENT_STATUS = /* @__PURE__ */ new Set([502, 503, 504, 522, 524]);
@@ -5202,7 +5317,7 @@ function getCostSummary() {
5202
5317
  }
5203
5318
 
5204
5319
  // src/version.ts
5205
- var SDK_VERSION = "4.0.0";
5320
+ var SDK_VERSION = "4.2.0";
5206
5321
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5207
5322
 
5208
5323
  // src/client.ts
@@ -5770,7 +5885,7 @@ var LLMClient = class _LLMClient {
5770
5885
  body: JSON.stringify(body)
5771
5886
  }, timeoutMs);
5772
5887
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
5773
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
5888
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
5774
5889
  if (!retryResp2.ok) {
5775
5890
  let errorBody;
5776
5891
  try {
@@ -5784,7 +5899,7 @@ var LLMClient = class _LLMClient {
5784
5899
  }
5785
5900
  }
5786
5901
  if (retryResponse.status === 402) {
5787
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
5902
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
5788
5903
  }
5789
5904
  if (!retryResponse.ok) {
5790
5905
  let errorBody;
@@ -5990,7 +6105,7 @@ var LLMClient = class _LLMClient {
5990
6105
  },
5991
6106
  body: JSON.stringify(body)
5992
6107
  });
5993
- if (streamResp.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6108
+ if (streamResp.status === 402) throw await buildPaymentRejectedError(streamResp, { replay: namesEarlierResult });
5994
6109
  if (!streamResp.ok) {
5995
6110
  let errorBody;
5996
6111
  try {
@@ -6117,7 +6232,7 @@ var LLMClient = class _LLMClient {
6117
6232
  body: JSON.stringify(body)
6118
6233
  });
6119
6234
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6120
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6235
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6121
6236
  if (!retryResp2.ok) {
6122
6237
  let errorBody;
6123
6238
  try {
@@ -6132,7 +6247,7 @@ var LLMClient = class _LLMClient {
6132
6247
  }
6133
6248
  }
6134
6249
  if (retryResponse.status === 402) {
6135
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6250
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6136
6251
  }
6137
6252
  if (!retryResponse.ok) {
6138
6253
  let errorBody;
@@ -6257,7 +6372,7 @@ var LLMClient = class _LLMClient {
6257
6372
  }
6258
6373
  });
6259
6374
  if (retryResp2.status !== 502 && retryResp2.status !== 503) {
6260
- if (retryResp2.status === 402) throw new PaymentError("Payment was rejected. Check your wallet balance.");
6375
+ if (retryResp2.status === 402) throw await buildPaymentRejectedError(retryResp2, { replay: namesEarlierResult });
6261
6376
  if (!retryResp2.ok) {
6262
6377
  let errorBody;
6263
6378
  try {
@@ -6272,7 +6387,7 @@ var LLMClient = class _LLMClient {
6272
6387
  }
6273
6388
  }
6274
6389
  if (retryResponse.status === 402) {
6275
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
6390
+ throw await buildPaymentRejectedError(retryResponse, { replay: namesEarlierResult });
6276
6391
  }
6277
6392
  if (!retryResponse.ok) {
6278
6393
  let errorBody;
@@ -7037,9 +7152,7 @@ var ImageClient = class {
7037
7152
  body: JSON.stringify(body)
7038
7153
  });
7039
7154
  if (retryResponse.status === 402) {
7040
- throw new PaymentError(
7041
- "Payment was rejected. Check your wallet balance."
7042
- );
7155
+ throw await buildPaymentRejectedError(retryResponse);
7043
7156
  }
7044
7157
  if (!retryResponse.ok) {
7045
7158
  let errorBody;
@@ -7092,6 +7205,7 @@ var ImageClient = class {
7092
7205
  continue;
7093
7206
  }
7094
7207
  const pollBody = await pollResp.json().catch(() => ({}));
7208
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7095
7209
  if (!pollResp.ok) {
7096
7210
  throw new APIError(
7097
7211
  `API error during poll: ${pollResp.status}`,
@@ -7291,7 +7405,7 @@ var MusicClient = class {
7291
7405
  body: JSON.stringify(body)
7292
7406
  });
7293
7407
  if (retryResponse.status === 402) {
7294
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7408
+ throw await buildPaymentRejectedError(retryResponse);
7295
7409
  }
7296
7410
  if (!retryResponse.ok) {
7297
7411
  let errorBody;
@@ -7350,6 +7464,7 @@ var MusicClient = class {
7350
7464
  }
7351
7465
  if (pollResp.status === 202 || TRANSIENT_POLL_STATUSES.has(pollResp.status)) continue;
7352
7466
  const pollBody = await pollResp.json().catch(() => ({}));
7467
+ if (pollResp.status === 402) throw paymentRejectedErrorFromBody(pollBody, 402);
7353
7468
  if (!pollResp.ok) {
7354
7469
  throw new APIError(
7355
7470
  `API error during poll of ${pollPath}: ${pollResp.status}`,
@@ -7570,7 +7685,7 @@ var SpeechClient = class {
7570
7685
  body: JSON.stringify(body)
7571
7686
  });
7572
7687
  if (retryResponse.status === 402) {
7573
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7688
+ throw await buildPaymentRejectedError(retryResponse);
7574
7689
  }
7575
7690
  if (!retryResponse.ok) {
7576
7691
  let errorBody;
@@ -7842,7 +7957,7 @@ var VideoClient = class {
7842
7957
  body: JSON.stringify(body)
7843
7958
  });
7844
7959
  if (submitResp.status === 402) {
7845
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
7960
+ throw await buildPaymentRejectedError(submitResp);
7846
7961
  }
7847
7962
  if (submitResp.status !== 200 && submitResp.status !== 202) {
7848
7963
  await this.throwApiError(submitResp, "Submit failed");
@@ -7892,6 +8007,9 @@ var VideoClient = class {
7892
8007
  return data;
7893
8008
  }
7894
8009
  if (pollResp.status === 402) {
8010
+ if (isPaymentReplay(pollData)) {
8011
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status, { replay: true });
8012
+ }
7895
8013
  if (resignsLeft > 0) {
7896
8014
  resignsLeft--;
7897
8015
  const challenge = await this.fetchWithTimeout(pollUrl, { method: "GET" });
@@ -7903,9 +8021,7 @@ var VideoClient = class {
7903
8021
  continue;
7904
8022
  }
7905
8023
  }
7906
- throw new PaymentError(
7907
- "Payment verification failed mid-poll (not a signature-expiry). Check the wallet balance and that you poll from the wallet that submitted the job."
7908
- );
8024
+ throw paymentRejectedErrorFromBody(pollData, pollResp.status);
7909
8025
  }
7910
8026
  if (pollResp.status !== 200 && pollResp.status !== 202 && pollResp.status !== 504) {
7911
8027
  await this.throwApiError(pollResp, "Poll failed");
@@ -8169,7 +8285,7 @@ var VoiceClient = class {
8169
8285
  body: JSON.stringify(body)
8170
8286
  });
8171
8287
  if (retryResponse.status === 402) {
8172
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8288
+ throw await buildPaymentRejectedError(retryResponse);
8173
8289
  }
8174
8290
  if (!retryResponse.ok) {
8175
8291
  let errorBody;
@@ -8401,7 +8517,7 @@ var PhoneClient = class {
8401
8517
  body: JSON.stringify(body)
8402
8518
  });
8403
8519
  if (retry.status === 402) {
8404
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8520
+ throw await buildPaymentRejectedError(retry);
8405
8521
  }
8406
8522
  const data = await this.unwrap(retry, true);
8407
8523
  if (!settlementSkipped(retry)) {
@@ -8569,7 +8685,7 @@ var PortraitClient = class {
8569
8685
  body: JSON.stringify(body)
8570
8686
  });
8571
8687
  if (retry.status === 402) {
8572
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8688
+ throw await buildPaymentRejectedError(retry);
8573
8689
  }
8574
8690
  const data = await this.unwrap(retry, true);
8575
8691
  if (!settlementSkipped(retry)) {
@@ -8731,7 +8847,7 @@ var SearchClient = class {
8731
8847
  body: JSON.stringify(body)
8732
8848
  });
8733
8849
  if (retry.status === 402) {
8734
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
8850
+ throw await buildPaymentRejectedError(retry);
8735
8851
  }
8736
8852
  if (!retry.ok) {
8737
8853
  let errorBody;
@@ -8922,7 +9038,7 @@ var PriceClient = class {
8922
9038
  headers: { "PAYMENT-SIGNATURE": paymentPayload }
8923
9039
  });
8924
9040
  if (retry.status === 402) {
8925
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9041
+ throw await buildPaymentRejectedError(retry);
8926
9042
  }
8927
9043
  if (!retry.ok) {
8928
9044
  let errorBody;
@@ -9113,7 +9229,7 @@ var SurfClient = class {
9113
9229
  }
9114
9230
  const retry = await this.fetchWithTimeout(url, retryInit);
9115
9231
  if (retry.status === 402) {
9116
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9232
+ throw await buildPaymentRejectedError(retry);
9117
9233
  }
9118
9234
  if (!retry.ok) {
9119
9235
  await this.throwApiError(retry, `Surf request failed after payment (${method} ${url})`);
@@ -9381,7 +9497,7 @@ var RpcClient = class {
9381
9497
  body: JSON.stringify(body)
9382
9498
  });
9383
9499
  if (retryResponse.status === 402) {
9384
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9500
+ throw await buildPaymentRejectedError(retryResponse);
9385
9501
  }
9386
9502
  if (!retryResponse.ok) {
9387
9503
  let errorBody;
@@ -9556,7 +9672,7 @@ var BlockrunClient = class {
9556
9672
  body: JSON.stringify(body ?? {})
9557
9673
  });
9558
9674
  if (submitResp.status === 402) {
9559
- throw new PaymentError("Payment was rejected. Check your wallet balance.");
9675
+ throw await buildPaymentRejectedError(submitResp);
9560
9676
  }
9561
9677
  if (submitResp.status !== 200 && submitResp.status !== 202) {
9562
9678
  await this.throwApiError(submitResp, `poll submit failed (${submitUrl})`);
@@ -9652,9 +9768,7 @@ var BlockrunClient = class {
9652
9768
  body: requestBody
9653
9769
  });
9654
9770
  if (streamResp.status === 402) {
9655
- throw new PaymentError(
9656
- "Payment was rejected. Check your wallet balance."
9657
- );
9771
+ throw await buildPaymentRejectedError(streamResp);
9658
9772
  }
9659
9773
  if (!streamResp.ok) {
9660
9774
  await this.throwApiError(streamResp, `stream failed after payment (${url})`);
@@ -9731,9 +9845,7 @@ var BlockrunClient = class {
9731
9845
  }
9732
9846
  const retry = await this.fetchWithTimeout(url, retryInit);
9733
9847
  if (retry.status === 402) {
9734
- throw new PaymentError(
9735
- "Payment was rejected. Check your wallet balance."
9736
- );
9848
+ throw await buildPaymentRejectedError(retry);
9737
9849
  }
9738
9850
  if (!retry.ok) {
9739
9851
  await this.throwApiError(retry, `${method} ${url} failed after payment`);
@@ -10365,6 +10477,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
10365
10477
  };
10366
10478
  }
10367
10479
 
10480
+ // src/stream-receipt.ts
10481
+ var STREAM_RECEIPT_HEADER = "X-BlockRun-Stream-Receipt";
10482
+ var RECEIPT_EVENT = "payment-response";
10483
+ var EVENT_END = /\r?\n\r?\n/;
10484
+ function isReceiptBlock(block) {
10485
+ return block.split(/\r?\n/).some((line) => line.trim() === `event: ${RECEIPT_EVENT}` || line.trim() === `event:${RECEIPT_EVENT}`);
10486
+ }
10487
+ function parseReceiptBlock(block) {
10488
+ const data = block.split(/\r?\n/).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).replace(/^ /, "")).join("\n");
10489
+ try {
10490
+ const parsed = JSON.parse(data);
10491
+ if (typeof parsed?.status !== "string") return void 0;
10492
+ return { status: parsed.status, ...typeof parsed.payment_response === "string" ? { paymentResponse: parsed.payment_response } : {} };
10493
+ } catch {
10494
+ return void 0;
10495
+ }
10496
+ }
10497
+ function withoutReceiptEvent(body) {
10498
+ const decoder = new TextDecoder();
10499
+ const encoder = new TextEncoder();
10500
+ let pending = "";
10501
+ return body.pipeThrough(
10502
+ new TransformStream({
10503
+ transform(chunk, controller) {
10504
+ pending += decoder.decode(chunk, { stream: true });
10505
+ let out = "";
10506
+ for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
10507
+ const end = match.index + match[0].length;
10508
+ const block = pending.slice(0, end);
10509
+ pending = pending.slice(end);
10510
+ if (!isReceiptBlock(block)) out += block;
10511
+ }
10512
+ if (out) controller.enqueue(encoder.encode(out));
10513
+ },
10514
+ flush(controller) {
10515
+ const rest = pending + decoder.decode();
10516
+ if (rest && !isReceiptBlock(rest)) controller.enqueue(encoder.encode(rest));
10517
+ }
10518
+ })
10519
+ );
10520
+ }
10521
+ async function readReceiptEvent(body) {
10522
+ const reader = body.getReader();
10523
+ const decoder = new TextDecoder();
10524
+ let pending = "";
10525
+ try {
10526
+ for (; ; ) {
10527
+ const { done, value } = await reader.read();
10528
+ if (done) return void 0;
10529
+ pending += decoder.decode(value, { stream: true });
10530
+ for (let match = EVENT_END.exec(pending); match; match = EVENT_END.exec(pending)) {
10531
+ const end = match.index + match[0].length;
10532
+ const block = pending.slice(0, end);
10533
+ pending = pending.slice(end);
10534
+ if (isReceiptBlock(block)) {
10535
+ void reader.cancel().catch(() => void 0);
10536
+ return parseReceiptBlock(block);
10537
+ }
10538
+ }
10539
+ }
10540
+ } catch {
10541
+ return void 0;
10542
+ } finally {
10543
+ try {
10544
+ reader.releaseLock();
10545
+ } catch {
10546
+ }
10547
+ }
10548
+ }
10549
+ async function lookupReceipt(apiUrl, paymentHeader, opts = {}) {
10550
+ const doFetch = opts.fetch ?? fetch;
10551
+ const attempts = opts.attempts ?? 8;
10552
+ const delayMs = opts.delayMs ?? 2e3;
10553
+ const sleep4 = opts.sleep ?? ((ms) => new Promise((resolve2) => setTimeout(resolve2, ms)));
10554
+ for (let attempt = 0; attempt < attempts; attempt++) {
10555
+ if (attempt > 0) await sleep4(Math.min(delayMs * 2 ** (attempt - 1), 15e3));
10556
+ let answer;
10557
+ try {
10558
+ const res = await doFetch(`${apiUrl}/v1/batch/receipt`, {
10559
+ method: "POST",
10560
+ headers: { "Content-Type": "application/json" },
10561
+ body: JSON.stringify({ paymentHeader })
10562
+ });
10563
+ if (res.status >= 500) continue;
10564
+ if (!res.ok) return void 0;
10565
+ answer = await res.json();
10566
+ } catch {
10567
+ continue;
10568
+ }
10569
+ if (answer?.status !== "pending") return answer;
10570
+ }
10571
+ return void 0;
10572
+ }
10573
+ function isEventStream(response) {
10574
+ return (response.headers.get("content-type") ?? "").includes("text/event-stream");
10575
+ }
10576
+
10368
10577
  // src/solana-batch.ts
10369
10578
  var import_async_hooks = require("async_hooks");
10370
10579
  var import_crypto2 = require("crypto");
@@ -13056,18 +13265,23 @@ async function readPaymentFailureBody(response) {
13056
13265
  }
13057
13266
  }
13058
13267
  async function isSafeStaleBlockhashResponse(response) {
13268
+ const body = await readPaymentFailure(response);
13269
+ return body !== null && isSafeStaleBlockhashBody(body);
13270
+ }
13271
+ async function readPaymentFailure(response) {
13059
13272
  const length = Number(response.headers.get("content-length") || "0");
13060
- if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return false;
13273
+ if (Number.isFinite(length) && length > MAX_PAYMENT_FAILURE_BYTES) return null;
13061
13274
  const text = await readPaymentFailureBody(response);
13062
- if (text === null) return false;
13063
- let body;
13275
+ if (text === null) return null;
13064
13276
  try {
13065
13277
  const parsed = JSON.parse(text);
13066
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;
13067
- body = parsed;
13278
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
13279
+ return parsed;
13068
13280
  } catch {
13069
- return false;
13281
+ return null;
13070
13282
  }
13283
+ }
13284
+ function isSafeStaleBlockhashBody(body) {
13071
13285
  const nested = body.error && typeof body.error === "object" && !Array.isArray(body.error) ? body.error : void 0;
13072
13286
  const errorLabel = typeof body.error === "string" ? body.error : "";
13073
13287
  const code = normalizePaymentSignal(body.code ?? nested?.code);
@@ -13422,6 +13636,7 @@ var SolanaLLMClient = class {
13422
13636
  * @returns a response whose body has not been read.
13423
13637
  */
13424
13638
  async openPaidStream(url, requestBody) {
13639
+ const closesAtStart = await this.batchPayer?.closeFence();
13425
13640
  for (let staleRetries = 0; ; ) {
13426
13641
  const response = await this.fetchWithTimeout(url, {
13427
13642
  method: "POST",
@@ -13439,11 +13654,15 @@ var SolanaLLMClient = class {
13439
13654
  throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
13440
13655
  }
13441
13656
  try {
13442
- const { paymentPayload, costUsd } = await this.signPaymentFrom402(
13443
- url,
13444
- response,
13445
- staleRetries > 0
13446
- );
13657
+ let exactPayment;
13658
+ if (this.batchPayer && staleRetries === 0) {
13659
+ const batch = await this.openBatchStream(url, requestBody, await this.readPaymentRequired(response), closesAtStart);
13660
+ if (batch.kind === "stream") return batch.response;
13661
+ exactPayment = await this.signExactPayment(url, batch.paymentRequired, false);
13662
+ } else {
13663
+ exactPayment = await this.signPaymentFrom402(url, response, staleRetries > 0);
13664
+ }
13665
+ const { paymentPayload, costUsd } = exactPayment;
13447
13666
  const paid = await this.fetchWithTimeout(url, {
13448
13667
  method: "POST",
13449
13668
  headers: {
@@ -13463,6 +13682,82 @@ var SolanaLLMClient = class {
13463
13682
  }
13464
13683
  }
13465
13684
  }
13685
+ /**
13686
+ * Pay a stream with batch-settlement, when the gateway offers it.
13687
+ *
13688
+ * A stream's charge is committed after its headers are sent, so its receipt
13689
+ * cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
13690
+ * buffered call with. The request asks for it as a final SSE event instead
13691
+ * ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
13692
+ * its branch at once, live, with the receipt event taken out; the payer reads
13693
+ * the other branch to that event and is handed the answer with the receipt
13694
+ * restored as its header, so the channel advances exactly as it does for a
13695
+ * buffered call. A stream that ends without the event (cut, failed upstream,
13696
+ * an older gateway) is looked up at `POST /v1/batch/receipt`.
13697
+ *
13698
+ * The payer's branch reads to the receipt even when the caller stops early,
13699
+ * so the connection stays open: the gateway charges for what the model
13700
+ * generates either way, and only an open stream brings its receipt back.
13701
+ *
13702
+ * @returns the caller's stream, or the requirements to pay `exact` against
13703
+ * when batch is unavailable for this call.
13704
+ */
13705
+ async openBatchStream(url, requestBody, paymentRequired, closesAtStart) {
13706
+ const headers = { "Content-Type": "application/json", "User-Agent": USER_AGENT, [STREAM_RECEIPT_HEADER]: "1" };
13707
+ let handOff;
13708
+ const handedOff = new Promise((resolve2) => {
13709
+ handOff = resolve2;
13710
+ });
13711
+ const attempt = this.batchPayer.pay(
13712
+ paymentRequired,
13713
+ async (paymentHeaders) => {
13714
+ const answer = await this.fetchWithTimeout(url, { method: "POST", headers: { ...headers, ...paymentHeaders }, body: requestBody });
13715
+ if (!answer.ok || !answer.body || !isEventStream(answer)) return answer;
13716
+ const [forCaller, forPayer] = answer.body.tee();
13717
+ handOff(new Response(withoutReceiptEvent(forCaller), { status: answer.status, statusText: answer.statusText, headers: answer.headers }));
13718
+ let receipt = (await readReceiptEvent(forPayer))?.paymentResponse;
13719
+ const signed = paymentHeaders["PAYMENT-SIGNATURE"];
13720
+ if (receipt === void 0 && signed) receipt = (await lookupReceipt(this.apiUrl, signed))?.payment_response;
13721
+ const settled2 = new Headers(answer.headers);
13722
+ if (receipt) settled2.set("PAYMENT-RESPONSE", receipt);
13723
+ return new Response(null, { status: answer.status, statusText: answer.statusText, headers: settled2 });
13724
+ },
13725
+ // A fresh, unpaid challenge after a 429 wait, as chatCompletion sends.
13726
+ async () => {
13727
+ const challenge = await this.sendUnpaid(url, { method: "POST", headers, body: requestBody });
13728
+ if (challenge.status === 402) {
13729
+ try {
13730
+ return { kind: "challenge", paymentRequired: await this.readPaymentRequired(challenge) };
13731
+ } catch (error) {
13732
+ throw withDisposition(error, "unpaid");
13733
+ }
13734
+ }
13735
+ if (challenge.ok) return { kind: "served", response: challenge };
13736
+ throw await unpaidApiError(challenge);
13737
+ },
13738
+ closesAtStart
13739
+ );
13740
+ const settled = attempt.then(
13741
+ (outcome2) => ({ outcome: outcome2 }),
13742
+ (error) => ({ error })
13743
+ );
13744
+ const first = await Promise.race([handedOff.then((response) => ({ response })), settled]);
13745
+ if ("response" in first) {
13746
+ void settled.then((result) => {
13747
+ if ("outcome" in result && result.outcome.kind === "paid") this.recordSettlement(result.outcome.chargedUsd, result.outcome.response);
13748
+ });
13749
+ return { kind: "stream", response: first.response };
13750
+ }
13751
+ if ("error" in first) throw first.error;
13752
+ const outcome = first.outcome;
13753
+ if (outcome.kind === "paid") {
13754
+ this.recordSettlement(outcome.chargedUsd, outcome.response);
13755
+ return { kind: "stream", response: outcome.response };
13756
+ }
13757
+ if (outcome.kind === "served") return { kind: "stream", response: outcome.response };
13758
+ if (outcome.kind === "failed") throw outcome.error;
13759
+ return { kind: "exact", paymentRequired: outcome.paymentRequired ?? paymentRequired };
13760
+ }
13466
13761
  /**
13467
13762
  * Resolve an endpoint path against this client's API root.
13468
13763
  *
@@ -14060,6 +14355,9 @@ var SolanaLLMClient = class {
14060
14355
  lastStatus = data.status || lastStatus;
14061
14356
  failIfFailed(data, paid.status);
14062
14357
  if (paid.status === 200 && lastStatus === "completed") return deliver(data, paid);
14358
+ if (paid.status === 402 && isPaymentReplay(data)) {
14359
+ throw withDisposition(paymentRejectedErrorFromBody(data, 402, { replay: true }), "paid-or-in-doubt");
14360
+ }
14063
14361
  if (paid.status === 402 && kind === "video") {
14064
14362
  if (data.error === "Payment verification failed" && !await isSafeStaleBlockhashResponse(new Response(JSON.stringify(data), { status: 402 }))) {
14065
14363
  throw new PaymentError(
@@ -14334,10 +14632,11 @@ var SolanaLLMClient = class {
14334
14632
  */
14335
14633
  async assertPaid(response) {
14336
14634
  if (response.status === 402) {
14337
- if (await isSafeStaleBlockhashResponse(response)) {
14635
+ const body = await readPaymentFailure(response);
14636
+ if (body !== null && isSafeStaleBlockhashBody(body)) {
14338
14637
  throw withDisposition(new SafeStaleBlockhashError(), "unpaid");
14339
14638
  }
14340
- throw withDisposition(new PaymentError("Payment was rejected. Check your Solana USDC balance."), "paid-or-in-doubt");
14639
+ throw withDisposition(paymentRejectedErrorFromBody(body ?? {}, 402), "paid-or-in-doubt");
14341
14640
  }
14342
14641
  if (!response.ok) {
14343
14642
  let errorBody;
@@ -14897,9 +15196,7 @@ var AnthropicClient = class {
14897
15196
  signal: controller.signal
14898
15197
  });
14899
15198
  if (response.status === 402) {
14900
- throw new Error(
14901
- "Payment was rejected. Check your wallet balance."
14902
- );
15199
+ throw await buildPaymentRejectedError(response);
14903
15200
  }
14904
15201
  }
14905
15202
  return response;
@@ -14947,10 +15244,12 @@ var AnthropicClient = class {
14947
15244
  MusicClient,
14948
15245
  NETWORK_ALIASES,
14949
15246
  OpenAI,
15247
+ PAYMENT_REPLAY,
14950
15248
  PHONE_PRICES,
14951
15249
  PORTAL_URL,
14952
15250
  PORTRAIT_ENROLLMENT_PRICE_USD,
14953
15251
  PaymentError,
15252
+ PaymentReplayError,
14954
15253
  PhoneClient,
14955
15254
  PortraitClient,
14956
15255
  PriceClient,
@@ -14973,6 +15272,7 @@ var AnthropicClient = class {
14973
15272
  VoiceClient,
14974
15273
  WALLET_DIR_PATH,
14975
15274
  WALLET_FILE_PATH,
15275
+ buildPaymentRejectedError,
14976
15276
  clearCache,
14977
15277
  createPaymentPayload,
14978
15278
  createSolanaPaymentPayload,
@@ -14996,12 +15296,14 @@ var AnthropicClient = class {
14996
15296
  getWalletAddress,
14997
15297
  importSolanaWallet,
14998
15298
  importWallet,
15299
+ isPaymentReplay,
14999
15300
  listDiscoveredSolanaWallets,
15000
15301
  listDiscoveredWallets,
15001
15302
  loadSolanaWallet,
15002
15303
  loadWallet,
15003
15304
  logCost,
15004
15305
  parsePaymentRequired,
15306
+ paymentRejectedErrorFromBody,
15005
15307
  readSettlement,
15006
15308
  retryDisposition,
15007
15309
  saveSolanaWallet,