@blockrun/llm 4.1.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/README.md CHANGED
@@ -732,7 +732,7 @@ await client.closeBatchChannel();
732
732
  - **Explicit trust.** `operators` has no default, and the SDK never learns a trusted key from a 402.
733
733
  - **Bounded exposure.** `maxDeposit` caps the escrow deposited and not yet settled on-chain; it is the most the operator could claim without another authorization from you.
734
734
  - **Never pays twice.** Anything that goes wrong before a batch payment is sent falls back to `exact`. Once one is sent, a call whose payment may have been charged throws `BatchPaymentUnresolvedError` and is never paid again (no new payment, no `exact`, no fallback model).
735
- - **Non-streaming chat only.** `chat`, `chatCompletion`, `smartChat` and `smartChatCompletion` use batch; `stream()` and media jobs pay `exact`.
735
+ - **Chat, buffered and streamed.** `chat`, `chatCompletion`, `smartChat`, `smartChatCompletion` and `stream()` use batch; media jobs pay `exact`. A stream's receipt arrives as a final SSE event the SDK reads and removes before your loop sees it (it never reaches your chunks), or, for a stream that is cut, from `POST /v1/batch/receipt` afterwards. Its charge is booked in `getSpending()` once that receipt is in, which can be a few seconds after your loop ends: the model may keep generating after a disconnect, and that is charged too.
736
736
  - **One channel per wallet.** All clients for a wallet share one channel, saved to `~/.blockrun/solana-batch/<wallet>.json` (mode `0600`) so a restart reuses it.
737
737
  - **One process per wallet.** The process that opens the channel holds its store's lock until it exits. Other processes on that wallet (worker pools, PM2/cluster workers, parallel runs) pay `exact`, reported as `channel_store_locked`. Give each worker its own wallet, or route calls through one process. `batch.onLocked: "wait"` waits up to `batch.lockWaitMs` (default 60 s) for the lock, and `"throw"` raises `BatchChannelLockedError` (unpaid, nothing signed) instead of paying `exact`.
738
738
  - **Observable.** Every fallback, backoff, recovery and re-read writes one stderr line; `batch.onEvent` and `client.getBatchStats()` expose the same events and counters.
package/dist/index.cjs CHANGED
@@ -5317,7 +5317,7 @@ function getCostSummary() {
5317
5317
  }
5318
5318
 
5319
5319
  // src/version.ts
5320
- var SDK_VERSION = "4.1.0";
5320
+ var SDK_VERSION = "4.2.0";
5321
5321
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5322
5322
 
5323
5323
  // src/client.ts
@@ -10477,6 +10477,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
10477
10477
  };
10478
10478
  }
10479
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
+
10480
10577
  // src/solana-batch.ts
10481
10578
  var import_async_hooks = require("async_hooks");
10482
10579
  var import_crypto2 = require("crypto");
@@ -13539,6 +13636,7 @@ var SolanaLLMClient = class {
13539
13636
  * @returns a response whose body has not been read.
13540
13637
  */
13541
13638
  async openPaidStream(url, requestBody) {
13639
+ const closesAtStart = await this.batchPayer?.closeFence();
13542
13640
  for (let staleRetries = 0; ; ) {
13543
13641
  const response = await this.fetchWithTimeout(url, {
13544
13642
  method: "POST",
@@ -13556,11 +13654,15 @@ var SolanaLLMClient = class {
13556
13654
  throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
13557
13655
  }
13558
13656
  try {
13559
- const { paymentPayload, costUsd } = await this.signPaymentFrom402(
13560
- url,
13561
- response,
13562
- staleRetries > 0
13563
- );
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;
13564
13666
  const paid = await this.fetchWithTimeout(url, {
13565
13667
  method: "POST",
13566
13668
  headers: {
@@ -13580,6 +13682,82 @@ var SolanaLLMClient = class {
13580
13682
  }
13581
13683
  }
13582
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
+ }
13583
13761
  /**
13584
13762
  * Resolve an endpoint path against this client's API root.
13585
13763
  *
package/dist/index.d.cts CHANGED
@@ -3931,6 +3931,27 @@ declare class SolanaLLMClient {
3931
3931
  * @returns a response whose body has not been read.
3932
3932
  */
3933
3933
  private openPaidStream;
3934
+ /**
3935
+ * Pay a stream with batch-settlement, when the gateway offers it.
3936
+ *
3937
+ * A stream's charge is committed after its headers are sent, so its receipt
3938
+ * cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
3939
+ * buffered call with. The request asks for it as a final SSE event instead
3940
+ * ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
3941
+ * its branch at once, live, with the receipt event taken out; the payer reads
3942
+ * the other branch to that event and is handed the answer with the receipt
3943
+ * restored as its header, so the channel advances exactly as it does for a
3944
+ * buffered call. A stream that ends without the event (cut, failed upstream,
3945
+ * an older gateway) is looked up at `POST /v1/batch/receipt`.
3946
+ *
3947
+ * The payer's branch reads to the receipt even when the caller stops early,
3948
+ * so the connection stays open: the gateway charges for what the model
3949
+ * generates either way, and only an open stream brings its receipt back.
3950
+ *
3951
+ * @returns the caller's stream, or the requirements to pay `exact` against
3952
+ * when batch is unavailable for this call.
3953
+ */
3954
+ private openBatchStream;
3934
3955
  /**
3935
3956
  * Resolve an endpoint path against this client's API root.
3936
3957
  *
package/dist/index.d.ts CHANGED
@@ -3931,6 +3931,27 @@ declare class SolanaLLMClient {
3931
3931
  * @returns a response whose body has not been read.
3932
3932
  */
3933
3933
  private openPaidStream;
3934
+ /**
3935
+ * Pay a stream with batch-settlement, when the gateway offers it.
3936
+ *
3937
+ * A stream's charge is committed after its headers are sent, so its receipt
3938
+ * cannot be the `PAYMENT-RESPONSE` header the batch payer reconciles a
3939
+ * buffered call with. The request asks for it as a final SSE event instead
3940
+ * ({@link STREAM_RECEIPT_HEADER}). The body is split in two: the caller gets
3941
+ * its branch at once, live, with the receipt event taken out; the payer reads
3942
+ * the other branch to that event and is handed the answer with the receipt
3943
+ * restored as its header, so the channel advances exactly as it does for a
3944
+ * buffered call. A stream that ends without the event (cut, failed upstream,
3945
+ * an older gateway) is looked up at `POST /v1/batch/receipt`.
3946
+ *
3947
+ * The payer's branch reads to the receipt even when the caller stops early,
3948
+ * so the connection stays open: the gateway charges for what the model
3949
+ * generates either way, and only an open stream brings its receipt back.
3950
+ *
3951
+ * @returns the caller's stream, or the requirements to pay `exact` against
3952
+ * when batch is unavailable for this call.
3953
+ */
3954
+ private openBatchStream;
3934
3955
  /**
3935
3956
  * Resolve an endpoint path against this client's API root.
3936
3957
  *
package/dist/index.js CHANGED
@@ -5179,7 +5179,7 @@ function getCostSummary() {
5179
5179
  }
5180
5180
 
5181
5181
  // src/version.ts
5182
- var SDK_VERSION = "4.1.0";
5182
+ var SDK_VERSION = "4.2.0";
5183
5183
  var USER_AGENT = `blockrun-ts/${SDK_VERSION}`;
5184
5184
 
5185
5185
  // src/client.ts
@@ -10339,6 +10339,103 @@ function signPollOwnership(secretKey, kind, jobId, nowMs = Date.now()) {
10339
10339
  };
10340
10340
  }
10341
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
+
10342
10439
  // src/solana-batch.ts
10343
10440
  import { AsyncLocalStorage } from "async_hooks";
10344
10441
  import { randomUUID } from "crypto";
@@ -13401,6 +13498,7 @@ var SolanaLLMClient = class {
13401
13498
  * @returns a response whose body has not been read.
13402
13499
  */
13403
13500
  async openPaidStream(url, requestBody) {
13501
+ const closesAtStart = await this.batchPayer?.closeFence();
13404
13502
  for (let staleRetries = 0; ; ) {
13405
13503
  const response = await this.fetchWithTimeout(url, {
13406
13504
  method: "POST",
@@ -13418,11 +13516,15 @@ var SolanaLLMClient = class {
13418
13516
  throw new APIError(`API error: ${response.status}`, response.status, sanitizeErrorResponse(errorBody));
13419
13517
  }
13420
13518
  try {
13421
- const { paymentPayload, costUsd } = await this.signPaymentFrom402(
13422
- url,
13423
- response,
13424
- staleRetries > 0
13425
- );
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;
13426
13528
  const paid = await this.fetchWithTimeout(url, {
13427
13529
  method: "POST",
13428
13530
  headers: {
@@ -13442,6 +13544,82 @@ var SolanaLLMClient = class {
13442
13544
  }
13443
13545
  }
13444
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
+ }
13445
13623
  /**
13446
13624
  * Resolve an endpoint path against this client's API root.
13447
13625
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockrun/llm",
3
- "version": "4.1.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",