@cydm/pie 2.7.3 → 2.7.5

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.
@@ -512,6 +512,338 @@ function hashText(text) {
512
512
  return hasher.digest();
513
513
  }
514
514
 
515
+ // ../../node_modules/@noble/hashes/esm/utils.js
516
+ function isBytes(a) {
517
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
518
+ }
519
+ function abytes(b, ...lengths) {
520
+ if (!isBytes(b))
521
+ throw new Error("Uint8Array expected");
522
+ if (lengths.length > 0 && !lengths.includes(b.length))
523
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
524
+ }
525
+ function aexists(instance, checkFinished = true) {
526
+ if (instance.destroyed)
527
+ throw new Error("Hash instance has been destroyed");
528
+ if (checkFinished && instance.finished)
529
+ throw new Error("Hash#digest() has already been called");
530
+ }
531
+ function aoutput(out, instance) {
532
+ abytes(out);
533
+ const min = instance.outputLen;
534
+ if (out.length < min) {
535
+ throw new Error("digestInto() expects output buffer of length at least " + min);
536
+ }
537
+ }
538
+ function clean(...arrays) {
539
+ for (let i = 0; i < arrays.length; i++) {
540
+ arrays[i].fill(0);
541
+ }
542
+ }
543
+ function createView(arr) {
544
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
545
+ }
546
+ function rotr(word, shift) {
547
+ return word << 32 - shift | word >>> shift;
548
+ }
549
+ function utf8ToBytes(str) {
550
+ if (typeof str !== "string")
551
+ throw new Error("string expected");
552
+ return new Uint8Array(new TextEncoder().encode(str));
553
+ }
554
+ function toBytes(data) {
555
+ if (typeof data === "string")
556
+ data = utf8ToBytes(data);
557
+ abytes(data);
558
+ return data;
559
+ }
560
+ var Hash = class {
561
+ };
562
+ function createHasher(hashCons) {
563
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
564
+ const tmp = hashCons();
565
+ hashC.outputLen = tmp.outputLen;
566
+ hashC.blockLen = tmp.blockLen;
567
+ hashC.create = () => hashCons();
568
+ return hashC;
569
+ }
570
+
571
+ // ../../node_modules/@noble/hashes/esm/_md.js
572
+ function setBigUint64(view, byteOffset, value, isLE) {
573
+ if (typeof view.setBigUint64 === "function")
574
+ return view.setBigUint64(byteOffset, value, isLE);
575
+ const _32n = BigInt(32);
576
+ const _u32_max = BigInt(4294967295);
577
+ const wh = Number(value >> _32n & _u32_max);
578
+ const wl = Number(value & _u32_max);
579
+ const h = isLE ? 4 : 0;
580
+ const l = isLE ? 0 : 4;
581
+ view.setUint32(byteOffset + h, wh, isLE);
582
+ view.setUint32(byteOffset + l, wl, isLE);
583
+ }
584
+ function Chi(a, b, c) {
585
+ return a & b ^ ~a & c;
586
+ }
587
+ function Maj(a, b, c) {
588
+ return a & b ^ a & c ^ b & c;
589
+ }
590
+ var HashMD = class extends Hash {
591
+ constructor(blockLen, outputLen, padOffset, isLE) {
592
+ super();
593
+ this.finished = false;
594
+ this.length = 0;
595
+ this.pos = 0;
596
+ this.destroyed = false;
597
+ this.blockLen = blockLen;
598
+ this.outputLen = outputLen;
599
+ this.padOffset = padOffset;
600
+ this.isLE = isLE;
601
+ this.buffer = new Uint8Array(blockLen);
602
+ this.view = createView(this.buffer);
603
+ }
604
+ update(data) {
605
+ aexists(this);
606
+ data = toBytes(data);
607
+ abytes(data);
608
+ const { view, buffer, blockLen } = this;
609
+ const len = data.length;
610
+ for (let pos = 0; pos < len; ) {
611
+ const take = Math.min(blockLen - this.pos, len - pos);
612
+ if (take === blockLen) {
613
+ const dataView = createView(data);
614
+ for (; blockLen <= len - pos; pos += blockLen)
615
+ this.process(dataView, pos);
616
+ continue;
617
+ }
618
+ buffer.set(data.subarray(pos, pos + take), this.pos);
619
+ this.pos += take;
620
+ pos += take;
621
+ if (this.pos === blockLen) {
622
+ this.process(view, 0);
623
+ this.pos = 0;
624
+ }
625
+ }
626
+ this.length += data.length;
627
+ this.roundClean();
628
+ return this;
629
+ }
630
+ digestInto(out) {
631
+ aexists(this);
632
+ aoutput(out, this);
633
+ this.finished = true;
634
+ const { buffer, view, blockLen, isLE } = this;
635
+ let { pos } = this;
636
+ buffer[pos++] = 128;
637
+ clean(this.buffer.subarray(pos));
638
+ if (this.padOffset > blockLen - pos) {
639
+ this.process(view, 0);
640
+ pos = 0;
641
+ }
642
+ for (let i = pos; i < blockLen; i++)
643
+ buffer[i] = 0;
644
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
645
+ this.process(view, 0);
646
+ const oview = createView(out);
647
+ const len = this.outputLen;
648
+ if (len % 4)
649
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
650
+ const outLen = len / 4;
651
+ const state = this.get();
652
+ if (outLen > state.length)
653
+ throw new Error("_sha2: outputLen bigger than state");
654
+ for (let i = 0; i < outLen; i++)
655
+ oview.setUint32(4 * i, state[i], isLE);
656
+ }
657
+ digest() {
658
+ const { buffer, outputLen } = this;
659
+ this.digestInto(buffer);
660
+ const res = buffer.slice(0, outputLen);
661
+ this.destroy();
662
+ return res;
663
+ }
664
+ _cloneInto(to) {
665
+ to || (to = new this.constructor());
666
+ to.set(...this.get());
667
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
668
+ to.destroyed = destroyed;
669
+ to.finished = finished;
670
+ to.length = length;
671
+ to.pos = pos;
672
+ if (length % blockLen)
673
+ to.buffer.set(buffer);
674
+ return to;
675
+ }
676
+ clone() {
677
+ return this._cloneInto();
678
+ }
679
+ };
680
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
681
+ 1779033703,
682
+ 3144134277,
683
+ 1013904242,
684
+ 2773480762,
685
+ 1359893119,
686
+ 2600822924,
687
+ 528734635,
688
+ 1541459225
689
+ ]);
690
+
691
+ // ../../node_modules/@noble/hashes/esm/sha2.js
692
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
693
+ 1116352408,
694
+ 1899447441,
695
+ 3049323471,
696
+ 3921009573,
697
+ 961987163,
698
+ 1508970993,
699
+ 2453635748,
700
+ 2870763221,
701
+ 3624381080,
702
+ 310598401,
703
+ 607225278,
704
+ 1426881987,
705
+ 1925078388,
706
+ 2162078206,
707
+ 2614888103,
708
+ 3248222580,
709
+ 3835390401,
710
+ 4022224774,
711
+ 264347078,
712
+ 604807628,
713
+ 770255983,
714
+ 1249150122,
715
+ 1555081692,
716
+ 1996064986,
717
+ 2554220882,
718
+ 2821834349,
719
+ 2952996808,
720
+ 3210313671,
721
+ 3336571891,
722
+ 3584528711,
723
+ 113926993,
724
+ 338241895,
725
+ 666307205,
726
+ 773529912,
727
+ 1294757372,
728
+ 1396182291,
729
+ 1695183700,
730
+ 1986661051,
731
+ 2177026350,
732
+ 2456956037,
733
+ 2730485921,
734
+ 2820302411,
735
+ 3259730800,
736
+ 3345764771,
737
+ 3516065817,
738
+ 3600352804,
739
+ 4094571909,
740
+ 275423344,
741
+ 430227734,
742
+ 506948616,
743
+ 659060556,
744
+ 883997877,
745
+ 958139571,
746
+ 1322822218,
747
+ 1537002063,
748
+ 1747873779,
749
+ 1955562222,
750
+ 2024104815,
751
+ 2227730452,
752
+ 2361852424,
753
+ 2428436474,
754
+ 2756734187,
755
+ 3204031479,
756
+ 3329325298
757
+ ]);
758
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
759
+ var SHA256 = class extends HashMD {
760
+ constructor(outputLen = 32) {
761
+ super(64, outputLen, 8, false);
762
+ this.A = SHA256_IV[0] | 0;
763
+ this.B = SHA256_IV[1] | 0;
764
+ this.C = SHA256_IV[2] | 0;
765
+ this.D = SHA256_IV[3] | 0;
766
+ this.E = SHA256_IV[4] | 0;
767
+ this.F = SHA256_IV[5] | 0;
768
+ this.G = SHA256_IV[6] | 0;
769
+ this.H = SHA256_IV[7] | 0;
770
+ }
771
+ get() {
772
+ const { A, B, C, D, E, F, G, H } = this;
773
+ return [A, B, C, D, E, F, G, H];
774
+ }
775
+ // prettier-ignore
776
+ set(A, B, C, D, E, F, G, H) {
777
+ this.A = A | 0;
778
+ this.B = B | 0;
779
+ this.C = C | 0;
780
+ this.D = D | 0;
781
+ this.E = E | 0;
782
+ this.F = F | 0;
783
+ this.G = G | 0;
784
+ this.H = H | 0;
785
+ }
786
+ process(view, offset) {
787
+ for (let i = 0; i < 16; i++, offset += 4)
788
+ SHA256_W[i] = view.getUint32(offset, false);
789
+ for (let i = 16; i < 64; i++) {
790
+ const W15 = SHA256_W[i - 15];
791
+ const W2 = SHA256_W[i - 2];
792
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
793
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
794
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
795
+ }
796
+ let { A, B, C, D, E, F, G, H } = this;
797
+ for (let i = 0; i < 64; i++) {
798
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
799
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
800
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
801
+ const T2 = sigma0 + Maj(A, B, C) | 0;
802
+ H = G;
803
+ G = F;
804
+ F = E;
805
+ E = D + T1 | 0;
806
+ D = C;
807
+ C = B;
808
+ B = A;
809
+ A = T1 + T2 | 0;
810
+ }
811
+ A = A + this.A | 0;
812
+ B = B + this.B | 0;
813
+ C = C + this.C | 0;
814
+ D = D + this.D | 0;
815
+ E = E + this.E | 0;
816
+ F = F + this.F | 0;
817
+ G = G + this.G | 0;
818
+ H = H + this.H | 0;
819
+ this.set(A, B, C, D, E, F, G, H);
820
+ }
821
+ roundClean() {
822
+ clean(SHA256_W);
823
+ }
824
+ destroy() {
825
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
826
+ clean(this.buffer);
827
+ }
828
+ };
829
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
830
+
831
+ // ../../packages/platform/src/sha256.ts
832
+ function createSha256Hasher() {
833
+ const hash = sha256.create();
834
+ return {
835
+ update(bytes) {
836
+ hash.update(bytes);
837
+ },
838
+ digestHex() {
839
+ const bytes = hash.digest();
840
+ let hex = "";
841
+ for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
842
+ return hex;
843
+ }
844
+ };
845
+ }
846
+
515
847
  // ../../packages/platform/src/detector.ts
516
848
  function isPuerTS() {
517
849
  try {
@@ -3126,7 +3458,7 @@ var NodeConnection = class {
3126
3458
  this.resolveClosed = resolve;
3127
3459
  });
3128
3460
  socket.on("error", (error) => this.fail(failure(
3129
- error.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ? "overflow" : this.opened ? "protocol" : "handshake",
3461
+ error.code === "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH" ? "overflow" : !this.opened ? "handshake" : error.code?.startsWith("WS_ERR_") ? "protocol" : "closed",
3130
3462
  "WebSocket transport failed"
3131
3463
  )));
3132
3464
  socket.on("open", () => {
@@ -5626,12 +5958,21 @@ var DEFAULT_RESPONSES_STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1e3;
5626
5958
  var DEFAULT_RESPONSES_FIRST_BYTE_TIMEOUT_MS = 3 * 60 * 1e3;
5627
5959
  var REASONING_STREAM_IDLE_TIMEOUT_MS = 5 * 60 * 1e3;
5628
5960
  var REASONING_FIRST_BYTE_TIMEOUT_MS = 5 * 60 * 1e3;
5629
- function parseSSEDataLine2(line) {
5630
- const trimmed = line.trim();
5631
- if (!trimmed || trimmed.startsWith(":")) return null;
5632
- if (!trimmed.startsWith("data:")) return null;
5633
- const data = trimmed.slice(5);
5634
- return data.startsWith(" ") ? data.slice(1) : data;
5961
+ async function* readSSEData(lines) {
5962
+ let data = [];
5963
+ let firstLine = true;
5964
+ for await (const rawLine of lines) {
5965
+ let line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
5966
+ if (firstLine && line.startsWith("\uFEFF")) line = line.slice(1);
5967
+ firstLine = false;
5968
+ if (line === "") {
5969
+ if (data.length > 0) yield data.join("\n");
5970
+ data = [];
5971
+ } else if (line === "data" || line.startsWith("data:")) {
5972
+ const value = line === "data" ? "" : line.slice(5);
5973
+ data.push(value.startsWith(" ") ? value.slice(1) : value);
5974
+ }
5975
+ }
5635
5976
  }
5636
5977
  function singleAttemptSupport() {
5637
5978
  let capabilities;
@@ -5663,20 +6004,11 @@ function resolveSSEBudgets(options, model) {
5663
6004
  const reasoning = model.reasoning === true;
5664
6005
  const defaultFirstByte = reasoning ? REASONING_FIRST_BYTE_TIMEOUT_MS : DEFAULT_RESPONSES_FIRST_BYTE_TIMEOUT_MS;
5665
6006
  const defaultIdle = reasoning ? REASONING_STREAM_IDLE_TIMEOUT_MS : DEFAULT_RESPONSES_STREAM_IDLE_TIMEOUT_MS;
5666
- if (firstResponse !== void 0 || streamIdle !== void 0) {
5667
- return {
5668
- http: {
5669
- firstByteTimeoutMs: firstResponse ?? defaultFirstByte,
5670
- streamIdleTimeoutMs: streamIdle ?? defaultIdle
5671
- },
5672
- requestTimeoutMs
5673
- };
5674
- }
5675
- if (options?.timeoutMs !== void 0) return { http: { timeoutMs: options.timeoutMs }, requestTimeoutMs };
6007
+ const legacy = options?.timeoutMs !== void 0 && Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : void 0;
5676
6008
  return {
5677
6009
  http: {
5678
- firstByteTimeoutMs: defaultFirstByte,
5679
- streamIdleTimeoutMs: defaultIdle
6010
+ firstByteTimeoutMs: firstResponse ?? legacy ?? defaultFirstByte,
6011
+ streamIdleTimeoutMs: streamIdle ?? legacy ?? defaultIdle
5680
6012
  },
5681
6013
  requestTimeoutMs
5682
6014
  };
@@ -5696,8 +6028,11 @@ function streamResponsesSSE(model, context, options) {
5696
6028
  let budgets = {};
5697
6029
  let totalTimer;
5698
6030
  let internalTimeout;
5699
- let localFailure = false;
6031
+ let localFailure = true;
5700
6032
  let providerRejected = false;
6033
+ let providerErrorMessage;
6034
+ let transportLost = false;
6035
+ let endedWithoutTerminal = false;
5701
6036
  const requestAbort = new AbortController();
5702
6037
  const onUserAbort = () => requestAbort.abort();
5703
6038
  const clearTotalTimer = () => {
@@ -5731,8 +6066,8 @@ function streamResponsesSSE(model, context, options) {
5731
6066
  throw error;
5732
6067
  }
5733
6068
  budgets = {
5734
- firstResponseTimeoutMs: resolved.http.firstByteTimeoutMs ?? resolved.http.timeoutMs,
5735
- streamIdleTimeoutMs: resolved.http.streamIdleTimeoutMs ?? resolved.http.timeoutMs,
6069
+ firstResponseTimeoutMs: resolved.http.firstByteTimeoutMs,
6070
+ streamIdleTimeoutMs: resolved.http.streamIdleTimeoutMs,
5736
6071
  requestTimeoutMs: resolved.requestTimeoutMs
5737
6072
  };
5738
6073
  options?.signal?.addEventListener("abort", onUserAbort, { once: true });
@@ -5776,6 +6111,7 @@ function streamResponsesSSE(model, context, options) {
5776
6111
  };
5777
6112
  const body = JSON.stringify(payload);
5778
6113
  reportSubmission(options, body, { transport: "sse", reusedConnection: false, continuation: false, attempt: 1 });
6114
+ localFailure = false;
5779
6115
  submitted = true;
5780
6116
  phase = "submission_attempted";
5781
6117
  lifecycle();
@@ -5788,20 +6124,36 @@ function streamResponsesSSE(model, context, options) {
5788
6124
  retryPolicy: "never",
5789
6125
  ...resolved.http,
5790
6126
  label: `${model.provider}/${model.id}`
6127
+ }).catch((error) => {
6128
+ const status = error && typeof error === "object" ? error.status ?? error.statusCode : void 0;
6129
+ if (typeof status === "number" && status >= 400) {
6130
+ providerRejected = true;
6131
+ providerErrorMessage = `API error ${status}: ${error instanceof Error ? error.message : "request rejected"}`;
6132
+ }
6133
+ transportLost = !providerRejected && !(error instanceof ResponsesProtocolError || error instanceof SyntaxError);
6134
+ throw error;
5791
6135
  });
5792
6136
  if (!response.ok) {
5793
- const errorBody = await response.text().catch(() => "");
5794
6137
  providerRejected = true;
5795
- throw new Error(`API error ${response.status}: ${errorBody}`);
6138
+ providerErrorMessage = `API error ${response.status}`;
6139
+ const errorBody = await response.text().catch(() => "");
6140
+ if (errorBody) providerErrorMessage += `: ${errorBody}`;
6141
+ throw new Error(providerErrorMessage);
5796
6142
  }
5797
6143
  if (!response.readSSELines) {
5798
- throw new Error("SSE streaming not supported on this platform");
6144
+ throw new ResponsesProtocolError("SSE streaming not supported on this platform");
6145
+ }
6146
+ async function* transportLines() {
6147
+ try {
6148
+ yield* response.readSSELines(requestAbort.signal);
6149
+ } catch (error) {
6150
+ transportLost = !(error instanceof ResponsesProtocolError || error instanceof SyntaxError);
6151
+ throw error;
6152
+ }
5799
6153
  }
5800
- for await (const line of response.readSSELines(requestAbort.signal)) {
6154
+ for await (const data of readSSEData(transportLines())) {
5801
6155
  receivedMessageCount += 1;
5802
6156
  lastReceiveAt = monotonicNow();
5803
- const data = parseSSEDataLine2(line);
5804
- if (data === null) continue;
5805
6157
  if (phase === "submission_attempted") {
5806
6158
  phase = "first_application_message";
5807
6159
  lifecycle();
@@ -5822,7 +6174,9 @@ function streamResponsesSSE(model, context, options) {
5822
6174
  if (typeof event.type === "string" && (event.type.startsWith("response.output") || event.type.startsWith("response.content") || event.type.startsWith("response.reasoning"))) {
5823
6175
  sawModelContent = true;
5824
6176
  }
5825
- for (const assistantEvent of reducer.feed(event)) {
6177
+ const events = reducer.feed(event);
6178
+ if (reducer.isTerminal && reducer.message.stopReason === "error") reducer.message.retryable = false;
6179
+ for (const assistantEvent of events) {
5826
6180
  stream.push(assistantEvent);
5827
6181
  }
5828
6182
  if (reducer.isTerminal) {
@@ -5840,6 +6194,7 @@ function streamResponsesSSE(model, context, options) {
5840
6194
  if (requestAbort.signal.aborted) {
5841
6195
  throw new Error(internalTimeout ? `Responses request timeout (${internalTimeout})` : "Request was aborted");
5842
6196
  }
6197
+ endedWithoutTerminal = true;
5843
6198
  throw reducer.finishWithoutTerminal();
5844
6199
  } catch (error) {
5845
6200
  if (reducer.isTerminal) {
@@ -5853,10 +6208,11 @@ function streamResponsesSSE(model, context, options) {
5853
6208
  if (!internalTimeout && (adapterTimeoutKind === "first_byte" || adapterTimeoutKind === "stream_idle")) {
5854
6209
  internalTimeout = adapterTimeoutKind === "first_byte" ? "first_response" : "stream_idle";
5855
6210
  }
5856
- message.errorMessage = internalTimeout ? `Responses request timeout (${internalTimeout}) after ${Math.round(monotonicNow() - startedAt)}ms` : error instanceof Error ? error.message : JSON.stringify(error);
6211
+ const protocolFailure = !endedWithoutTerminal && (error instanceof ResponsesProtocolError || error instanceof SyntaxError || !transportLost && error instanceof TypeError);
6212
+ message.errorMessage = providerErrorMessage ?? (internalTimeout && !protocolFailure ? `Responses request timeout (${internalTimeout}) after ${Math.round(monotonicNow() - startedAt)}ms` : error instanceof Error ? error.message : JSON.stringify(error));
5857
6213
  const compat = getResponsesCompat(model);
5858
- const streamLost = !internalTimeout && submitted && !localFailure && !providerRejected && message.stopReason === "error";
5859
- if (internalTimeout && compat.timeoutReplay) {
6214
+ const streamLost = (endedWithoutTerminal || transportLost) && !protocolFailure && !internalTimeout && submitted && !localFailure && !providerRejected && message.stopReason === "error";
6215
+ if (internalTimeout && !protocolFailure && submitted && !providerRejected && !localFailure && !userAborted && compat.timeoutReplay) {
5860
6216
  message.replayEligible = true;
5861
6217
  message.replayClass = internalTimeout;
5862
6218
  } else if (streamLost && compat.timeoutReplay) {
@@ -5882,9 +6238,112 @@ function streamResponsesSSE(model, context, options) {
5882
6238
  return stream;
5883
6239
  }
5884
6240
 
6241
+ // ../../packages/ai/src/providers/responses/responses-continuation.ts
6242
+ function jsonSha256(value) {
6243
+ return hashJson(value);
6244
+ }
6245
+ function hashJson(value, parts) {
6246
+ const hash = createSha256Hasher();
6247
+ const bytes = new Uint8Array(8192);
6248
+ let used = 0;
6249
+ const byte = (n) => {
6250
+ bytes[used++] = n;
6251
+ if (used === bytes.length) {
6252
+ hash.update(bytes);
6253
+ used = 0;
6254
+ }
6255
+ };
6256
+ const emit = (text) => {
6257
+ for (let i = 0; i < text.length; i++) {
6258
+ const cp = text.codePointAt(i);
6259
+ if (cp < 128) byte(cp);
6260
+ else if (cp < 2048) {
6261
+ byte(192 | cp >> 6);
6262
+ byte(128 | cp & 63);
6263
+ } else if (cp < 65536) {
6264
+ byte(224 | cp >> 12);
6265
+ byte(128 | cp >> 6 & 63);
6266
+ byte(128 | cp & 63);
6267
+ } else {
6268
+ byte(240 | cp >> 18);
6269
+ byte(128 | cp >> 12 & 63);
6270
+ byte(128 | cp >> 6 & 63);
6271
+ byte(128 | cp & 63);
6272
+ i++;
6273
+ }
6274
+ }
6275
+ };
6276
+ const string = (text) => {
6277
+ emit('"');
6278
+ for (let start = 0; start < text.length; ) {
6279
+ let end = Math.min(start + 2048, text.length);
6280
+ if (end < text.length && text.charCodeAt(end - 1) >= 55296 && text.charCodeAt(end - 1) <= 56319) end--;
6281
+ const escaped = JSON.stringify(text.slice(start, end));
6282
+ emit(escaped.slice(1, -1));
6283
+ start = end;
6284
+ }
6285
+ emit('"');
6286
+ };
6287
+ const ancestors = /* @__PURE__ */ new Set();
6288
+ const omitted = (v) => v === void 0 || typeof v === "function" || typeof v === "symbol";
6289
+ const visit = (v) => {
6290
+ if (typeof v === "string") {
6291
+ string(v);
6292
+ return;
6293
+ }
6294
+ if (v === null || typeof v !== "object") {
6295
+ const encoded = JSON.stringify(v);
6296
+ if (encoded === void 0) throw new TypeError("Not a JSON value");
6297
+ emit(encoded);
6298
+ return;
6299
+ }
6300
+ const prototype = Object.getPrototypeOf(v);
6301
+ if (!Array.isArray(v) && prototype !== Object.prototype && prototype !== null || typeof v.toJSON === "function") throw new TypeError("Not a JSON snapshot");
6302
+ if (ancestors.has(v)) throw new TypeError("Circular JSON snapshot");
6303
+ ancestors.add(v);
6304
+ if (Array.isArray(v)) {
6305
+ emit("[");
6306
+ for (let i = 0; i < v.length; i++) {
6307
+ if (Object.getOwnPropertyDescriptor(v, i)?.get) throw new TypeError("Not a JSON snapshot");
6308
+ if (i) emit(",");
6309
+ visit(omitted(v[i]) ? null : v[i]);
6310
+ }
6311
+ emit("]");
6312
+ } else {
6313
+ emit("{");
6314
+ let first = true;
6315
+ for (const key of Object.keys(v)) {
6316
+ if (Object.getOwnPropertyDescriptor(v, key)?.get) throw new TypeError("Not a JSON snapshot");
6317
+ const entry = v[key];
6318
+ if (omitted(entry)) continue;
6319
+ if (!first) emit(",");
6320
+ first = false;
6321
+ string(key);
6322
+ emit(":");
6323
+ visit(entry);
6324
+ }
6325
+ emit("}");
6326
+ }
6327
+ ancestors.delete(v);
6328
+ };
6329
+ if (parts) {
6330
+ emit("[");
6331
+ for (let i = 0; i < parts.count + parts.output.length; i++) {
6332
+ if (i) emit(",");
6333
+ const item = i < parts.count ? parts.input[i] : parts.output[i - parts.count];
6334
+ visit(omitted(item) ? null : item);
6335
+ }
6336
+ emit("]");
6337
+ } else visit(value);
6338
+ if (used) hash.update(bytes.subarray(0, used));
6339
+ return hash.digestHex();
6340
+ }
6341
+ function inputSha256(input, count = input.length, output = []) {
6342
+ return hashJson(void 0, { input, count, output });
6343
+ }
6344
+
5885
6345
  // ../../packages/ai/src/providers/responses/responses-ws.ts
5886
6346
  var owners = /* @__PURE__ */ new WeakMap();
5887
- var MAX_ANCHOR_BYTES = 1024 * 1024;
5888
6347
  var DEFAULT_CONNECT_TIMEOUT_MS = 3e4;
5889
6348
  var DEFAULT_FIRST_RESPONSE_TIMEOUT_MS = 2 * 60 * 1e3;
5890
6349
  var DEFAULT_STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1e3;
@@ -6000,9 +6459,22 @@ function streamResponsesWS(model, context, options) {
6000
6459
  void (async () => {
6001
6460
  let sent = false;
6002
6461
  let finished = false;
6462
+ let candidateAnchor;
6003
6463
  let terminalEvents = [];
6004
6464
  let fallback = false;
6005
6465
  let timedOut;
6466
+ let providerRejected = false;
6467
+ let localFailure = true;
6468
+ let transportLost = false;
6469
+ let endedWithoutTerminal = false;
6470
+ const transportIO = async (operation) => {
6471
+ try {
6472
+ return await operation();
6473
+ } catch (error) {
6474
+ transportLost = !(error instanceof ResponsesProtocolError || error instanceof SyntaxError) && (!(error instanceof WebSocketTransportError) || error.kind === "closed" || error.kind === "timeout");
6475
+ throw error;
6476
+ }
6477
+ };
6006
6478
  let retryDecision = "none";
6007
6479
  let requestTimer;
6008
6480
  let totalTimer;
@@ -6169,12 +6641,23 @@ function streamResponsesWS(model, context, options) {
6169
6641
  }
6170
6642
  const key = options?.apiKey || getEnvApiKey(model.provider, model.apiKeyEnv);
6171
6643
  if (!key) throw new Error(`No API key for provider: ${model.provider}`);
6172
- const payload = buildResponsesCreateEvent(model, context, options);
6644
+ const encoded = buildResponsesCreateEvent(model, context, options);
6645
+ const { input, ...encodedSettings } = encoded;
6646
+ const settings = JSON.parse(JSON.stringify(encodedSettings));
6647
+ const payload = { ...settings, input };
6173
6648
  const headers = { Authorization: `Bearer ${key}`, ...model.headers, ...options?.headers };
6174
- const { input, ...settings } = payload;
6175
- const identity = JSON.stringify([model.provider, model.api, model.id, model.baseUrl, headers, settings]);
6649
+ const endpoint = websocketUrl(model.baseUrl);
6650
+ let continuationReason = "no_anchor";
6651
+ const identityValue = [1, model.provider, model.api, model.id, endpoint, headers, settings, compat];
6652
+ let identity;
6653
+ try {
6654
+ identity = jsonSha256(identityValue);
6655
+ } catch {
6656
+ }
6657
+ if (!identity) state.anchor = void 0;
6176
6658
  clearConnectionIdleTimer(state);
6177
- if (state.identity !== identity || state.connection?.state() !== "open") {
6659
+ if (!identity || state.identity !== identity || state.connection?.state() !== "open") {
6660
+ if (state.anchor) continuationReason = state.identity !== identity ? "identity_changed" : "connection_changed";
6178
6661
  const stale = state.connection;
6179
6662
  state.connection = void 0;
6180
6663
  state.anchor = void 0;
@@ -6185,27 +6668,34 @@ function streamResponsesWS(model, context, options) {
6185
6668
  reusedConnection = !!state.connection;
6186
6669
  if (state.abort.signal.aborted) throw new Error("Request aborted");
6187
6670
  lifecycle("request_start");
6671
+ localFailure = false;
6188
6672
  const client = getWebSocketClient();
6189
6673
  if (!client) {
6190
6674
  if (options?.transport === "auto") {
6191
6675
  await runSSEFallback();
6192
6676
  return;
6193
6677
  }
6194
- throw new Error("WebSocket transport is not available on this host.");
6678
+ throw new ResponsesProtocolError("WebSocket transport is not available on this host.");
6195
6679
  }
6196
6680
  let connection = state.connection;
6197
6681
  if (!connection) {
6198
6682
  try {
6199
- connection = await client.connect(websocketUrl(model.baseUrl), {
6683
+ connection = await client.connect(endpoint, {
6200
6684
  headers,
6201
6685
  signal: requestAbort.signal,
6202
6686
  connectTimeoutMs: budgets.connectTimeoutMs
6203
6687
  });
6204
6688
  } catch (error) {
6205
6689
  if (error instanceof WebSocketTransportError && error.kind === "timeout") timedOut = "connect";
6206
- if (options?.transport === "auto" && error instanceof WebSocketTransportError && error.kind === "handshake" && [404, 405, 426, 501].includes(error.status ?? 0) && !options.signal?.aborted && !state.abort.signal.aborted) {
6207
- await runSSEFallback();
6208
- return;
6690
+ if (error instanceof WebSocketTransportError && error.kind === "handshake" && !options?.signal?.aborted && !state.abort.signal.aborted) {
6691
+ const status = error.status ?? 0;
6692
+ providerRejected = status > 0;
6693
+ const endpointHasNoWebsockets = options?.transport === "auto" && [404, 405, 426, 501].includes(status);
6694
+ const wsEdgeRefused = status === 0 || status === 429 || status >= 500 && status <= 599;
6695
+ if (endpointHasNoWebsockets || wsEdgeRefused) {
6696
+ await runSSEFallback();
6697
+ return;
6698
+ }
6209
6699
  }
6210
6700
  throw error;
6211
6701
  }
@@ -6221,28 +6711,57 @@ function streamResponsesWS(model, context, options) {
6221
6711
  const activeConnection = connection;
6222
6712
  const fullInput = input;
6223
6713
  const anchor = state.anchor;
6224
- if (!options?.onPayload && model.compat?.responsesContinuation && anchor && fullInput.length > anchor.count && JSON.stringify(fullInput.slice(0, anchor.count)) === anchor.prefix) {
6225
- payload.previous_response_id = anchor.id;
6226
- payload.input = fullInput.slice(anchor.count);
6714
+ let prefixHashMs = 0;
6715
+ if (options?.onPayload) continuationReason = "payload_hook";
6716
+ else if (!compat.responsesContinuation) continuationReason = "disabled";
6717
+ else if (!identity) continuationReason = "hash_unavailable";
6718
+ else if (anchor) continuationReason = fullInput.length <= anchor.confirmedItemCount ? "history_shortened" : "history_changed";
6719
+ if (!options?.onPayload && compat.responsesContinuation && identity && anchor && anchor.connectionGeneration === connectionGeneration && anchor.requestIdentitySha256 === identity && fullInput.length > anchor.confirmedItemCount) {
6720
+ const hashStarted = monotonicNow();
6721
+ try {
6722
+ if (inputSha256(fullInput, anchor.confirmedItemCount) === anchor.prefixSha256) {
6723
+ continuationReason = "verified_prefix";
6724
+ payload.previous_response_id = anchor.responseId;
6725
+ payload.input = fullInput.slice(anchor.confirmedItemCount);
6726
+ }
6727
+ } catch {
6728
+ continuationReason = "hash_unavailable";
6729
+ }
6730
+ prefixHashMs = monotonicNow() - hashStarted;
6227
6731
  }
6228
6732
  state.anchor = void 0;
6229
6733
  for (let attempt = 0; attempt < 2; attempt++) {
6230
6734
  let rebuild = false;
6231
- options?.onPayload?.(payload);
6735
+ let body;
6736
+ try {
6737
+ options?.onPayload?.(payload);
6738
+ body = JSON.stringify(payload);
6739
+ } catch (error) {
6740
+ localFailure = true;
6741
+ throw error;
6742
+ }
6232
6743
  if (state.abort.signal.aborted || requestAbort.signal.aborted) throw new Error("Request aborted");
6233
6744
  sent = true;
6234
- const body = JSON.stringify(payload);
6235
- reportSubmission(options, body, { transport: "websocket", reusedConnection: reusedConnection || attempt > 0, continuation: !!payload.previous_response_id, attempt: attempt + 1 });
6745
+ reportSubmission(options, body, {
6746
+ transport: "websocket",
6747
+ reusedConnection: reusedConnection || attempt > 0,
6748
+ continuation: !!payload.previous_response_id,
6749
+ attempt: attempt + 1,
6750
+ continuationReason,
6751
+ fullInputItems: fullInput.length,
6752
+ sentInputItems: Array.isArray(payload.input) ? payload.input.length : void 0,
6753
+ prefixHashMs
6754
+ });
6236
6755
  lifecycle("submission_attempted", { submissionAttempted: true });
6237
6756
  armPhaseTimer("first_response", budgets.firstResponseTimeoutMs);
6238
- await activeConnection.send(body, { signal: requestAbort.signal });
6757
+ await transportIO(() => activeConnection.send(body, { signal: requestAbort.signal }));
6239
6758
  let started = false;
6240
6759
  let responseId;
6241
6760
  const receiveIterator = activeConnection.receive(requestAbort.signal)[Symbol.asyncIterator]();
6242
6761
  let receiveDone = false;
6243
6762
  try {
6244
6763
  while (true) {
6245
- const step = await receiveIterator.next();
6764
+ const step = await transportIO(() => receiveIterator.next());
6246
6765
  if (step.done) {
6247
6766
  receiveDone = true;
6248
6767
  break;
@@ -6265,6 +6784,7 @@ function streamResponsesWS(model, context, options) {
6265
6784
  if (!started && attempt === 0 && payload.previous_response_id && event.type === "error" && event.status === 400 && isRecord2(event.error) && event.error.code === "previous_response_not_found" && event.error.param === "previous_response_id") {
6266
6785
  delete payload.previous_response_id;
6267
6786
  payload.input = fullInput;
6787
+ continuationReason = "previous_response_not_found";
6268
6788
  rebuild = true;
6269
6789
  break;
6270
6790
  }
@@ -6282,10 +6802,19 @@ function streamResponsesWS(model, context, options) {
6282
6802
  if (reducer.message.stopReason === "error") reducer.message.retryable = false;
6283
6803
  const response = reducer.terminalResponse;
6284
6804
  state.lastResponseId = response?.id;
6285
- if (!options?.onPayload && response?.status === "completed" && reducer.message.stopReason !== "error") {
6286
- const prefixItems = [...fullInput, ...buildResponsesOutput(reducer.message)];
6287
- const prefix = JSON.stringify(prefixItems);
6288
- if (prefix.length * 2 <= MAX_ANCHOR_BYTES) state.anchor = { id: response.id, prefix, count: prefixItems.length };
6805
+ if (!options?.onPayload && compat.responsesContinuation && identity && response?.status === "completed" && reducer.message.stopReason !== "error") {
6806
+ try {
6807
+ const output = buildResponsesOutput(reducer.message);
6808
+ candidateAnchor = {
6809
+ version: 1,
6810
+ responseId: response.id,
6811
+ confirmedItemCount: fullInput.length + output.length,
6812
+ prefixSha256: inputSha256(fullInput, fullInput.length, output),
6813
+ requestIdentitySha256: identity,
6814
+ connectionGeneration
6815
+ };
6816
+ } catch {
6817
+ }
6289
6818
  }
6290
6819
  finished = true;
6291
6820
  clearRequestTimers();
@@ -6306,7 +6835,10 @@ function streamResponsesWS(model, context, options) {
6306
6835
  retryDecision = "rebuild_previous_response";
6307
6836
  continue;
6308
6837
  }
6309
- if (!reducer.isTerminal) throw reducer.finishWithoutTerminal();
6838
+ if (!reducer.isTerminal) {
6839
+ endedWithoutTerminal = true;
6840
+ throw reducer.finishWithoutTerminal();
6841
+ }
6310
6842
  break;
6311
6843
  }
6312
6844
  } catch (error) {
@@ -6315,16 +6847,20 @@ function streamResponsesWS(model, context, options) {
6315
6847
  const userAborted = options?.signal?.aborted === true;
6316
6848
  const ownerDisposed = !userAborted && !timedOut && state.abort.signal.aborted;
6317
6849
  message.stopReason = userAborted || ownerDisposed ? "aborted" : "error";
6318
- const cause = timedOut ? `Responses request timeout (${timedOut}) after ${ageMs()}ms` : error instanceof Error ? error.message : String(error);
6850
+ const protocolFailure = !endedWithoutTerminal && (error instanceof ResponsesProtocolError || error instanceof SyntaxError || !transportLost && error instanceof TypeError || error instanceof WebSocketTransportError && (error.kind === "protocol" || error.kind === "overflow"));
6851
+ const cause = providerRejected && error instanceof WebSocketTransportError ? `${error.message} (HTTP status ${error.status})` : timedOut && !protocolFailure ? `Responses request timeout (${timedOut}) after ${ageMs()}ms` : error instanceof Error ? error.message : String(error);
6319
6852
  message.errorMessage = cause;
6320
- const streamLost = !timedOut && message.stopReason === "error";
6321
- if (timedOut && compat.timeoutReplay) {
6853
+ const streamLost = (endedWithoutTerminal || transportLost) && !protocolFailure && sent && !timedOut && !providerRejected && message.stopReason === "error";
6854
+ if (timedOut && timedOut !== "connect" && !protocolFailure && !localFailure && sent && !providerRejected && !userAborted && !ownerDisposed && compat.timeoutReplay) {
6322
6855
  message.replayEligible = true;
6323
6856
  message.replayClass = timedOut;
6324
6857
  } else if (streamLost && compat.timeoutReplay) {
6325
6858
  message.replayEligible = true;
6326
6859
  message.replayClass = receivedMessageCount === 0 ? "stream_lost" : "stream_lost_partial";
6327
6860
  }
6861
+ if (localFailure || providerRejected || protocolFailure) {
6862
+ message.retryable = false;
6863
+ }
6328
6864
  if (sent) {
6329
6865
  if (streamLost && receivedMessageCount === 0) {
6330
6866
  retryDecision = message.replayEligible ? "replay_exempt_stream_lost" : "stream_lost_no_evidence";
@@ -6343,9 +6879,10 @@ function streamResponsesWS(model, context, options) {
6343
6879
  options?.signal?.removeEventListener("abort", abort);
6344
6880
  state.busy = false;
6345
6881
  const cancelSource = cleanupCancelSource ?? (options?.signal?.aborted ? "user" : timedOut ? "internal_timeout" : state.abort.signal.aborted ? "owner_disposal" : "none");
6346
- const retain = finished && !fallback && !receiveCleanupFailed && !!options?.transportOwner && reducer.message.stopReason !== "error" && !timedOut && state.connection !== void 0 && !state.abort.signal.aborted;
6882
+ const retain = finished && !fallback && !receiveCleanupFailed && !!options?.transportOwner && reducer.message.stopReason !== "error" && !timedOut && state.connection?.state() === "open" && !state.abort.signal.aborted && owners.get(owner) === state && state.requestGeneration === requestGeneration && state.connectionGeneration === connectionGeneration;
6347
6883
  if (!retain) disposeState(owner, state);
6348
6884
  else if (state.connection) {
6885
+ state.anchor = candidateAnchor;
6349
6886
  armConnectionIdleRecycle(state, state.connection, connectionGeneration, budgets.connectionIdleTimeoutMs);
6350
6887
  }
6351
6888
  const cleanupOutcome = receiveCleanupFailed ? "cleanup_failed" : retain ? "connection_reused" : finished ? "connection_closed" : "request_abandoned";
@@ -6747,7 +7284,7 @@ function FNV1A64(byte) {
6747
7284
  Accumulator = Accumulator ^ Bytes[byte];
6748
7285
  Accumulator = Accumulator * Prime % Size;
6749
7286
  }
6750
- function Hash(value) {
7287
+ function Hash2(value) {
6751
7288
  Accumulator = BigInt("14695981039346656037");
6752
7289
  Visit(value);
6753
7290
  return Accumulator;
@@ -6788,7 +7325,7 @@ function FromArray(schema, references, value) {
6788
7325
  if (schema.uniqueItems === true && !(function() {
6789
7326
  const set = /* @__PURE__ */ new Set();
6790
7327
  for (const element of value) {
6791
- const hashed = Hash(element);
7328
+ const hashed = Hash2(element);
6792
7329
  if (set.has(hashed)) {
6793
7330
  return false;
6794
7331
  } else {
@@ -7308,7 +7845,7 @@ function* FromArray2(schema, references, path, value) {
7308
7845
  if (schema.uniqueItems === true && !(function() {
7309
7846
  const set = /* @__PURE__ */ new Set();
7310
7847
  for (const element of value) {
7311
- const hashed = Hash(element);
7848
+ const hashed = Hash2(element);
7312
7849
  if (set.has(hashed)) {
7313
7850
  return false;
7314
7851
  } else {
@@ -9787,7 +10324,7 @@ __export(value_exports, {
9787
10324
  Encode: () => Encode,
9788
10325
  Equal: () => Equal,
9789
10326
  Errors: () => Errors,
9790
- Hash: () => Hash,
10327
+ Hash: () => Hash2,
9791
10328
  Mutate: () => Mutate,
9792
10329
  Parse: () => Parse,
9793
10330
  Patch: () => Patch,
@@ -9893,7 +10430,7 @@ export {
9893
10430
  modelSupportsToolPurpose,
9894
10431
  sortToolModelCandidatesByCapability,
9895
10432
  Deref,
9896
- Hash,
10433
+ Hash2 as Hash,
9897
10434
  Errors,
9898
10435
  TransformDecodeCheckError,
9899
10436
  TransformDecode,