@vibedeckx/linux-x64 0.3.5 → 0.3.7

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.
Files changed (2) hide show
  1. package/dist/bin.js +1614 -1060
  2. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -16572,44 +16572,44 @@ var require_base64 = __commonJS({
16572
16572
  s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;
16573
16573
  var i;
16574
16574
  base643.encode = function encode3(buffer, start, end) {
16575
- var parts = null, chunk = [];
16575
+ var parts = null, chunk2 = [];
16576
16576
  var i2 = 0, j = 0, t;
16577
16577
  while (start < end) {
16578
16578
  var b2 = buffer[start++];
16579
16579
  switch (j) {
16580
16580
  case 0:
16581
- chunk[i2++] = b64[b2 >> 2];
16581
+ chunk2[i2++] = b64[b2 >> 2];
16582
16582
  t = (b2 & 3) << 4;
16583
16583
  j = 1;
16584
16584
  break;
16585
16585
  case 1:
16586
- chunk[i2++] = b64[t | b2 >> 4];
16586
+ chunk2[i2++] = b64[t | b2 >> 4];
16587
16587
  t = (b2 & 15) << 2;
16588
16588
  j = 2;
16589
16589
  break;
16590
16590
  case 2:
16591
- chunk[i2++] = b64[t | b2 >> 6];
16592
- chunk[i2++] = b64[b2 & 63];
16591
+ chunk2[i2++] = b64[t | b2 >> 6];
16592
+ chunk2[i2++] = b64[b2 & 63];
16593
16593
  j = 0;
16594
16594
  break;
16595
16595
  }
16596
16596
  if (i2 > 8191) {
16597
- (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));
16597
+ (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk2));
16598
16598
  i2 = 0;
16599
16599
  }
16600
16600
  }
16601
16601
  if (j) {
16602
- chunk[i2++] = b64[t];
16603
- chunk[i2++] = 61;
16602
+ chunk2[i2++] = b64[t];
16603
+ chunk2[i2++] = 61;
16604
16604
  if (j === 1)
16605
- chunk[i2++] = 61;
16605
+ chunk2[i2++] = 61;
16606
16606
  }
16607
16607
  if (parts) {
16608
16608
  if (i2)
16609
- parts.push(String.fromCharCode.apply(String, chunk.slice(0, i2)));
16609
+ parts.push(String.fromCharCode.apply(String, chunk2.slice(0, i2)));
16610
16610
  return parts.join("");
16611
16611
  }
16612
- return String.fromCharCode.apply(String, chunk.slice(0, i2));
16612
+ return String.fromCharCode.apply(String, chunk2.slice(0, i2));
16613
16613
  };
16614
16614
  var invalidEncoding = "invalid encoding";
16615
16615
  base643.decode = function decode3(string4, buffer, offset) {
@@ -25600,15 +25600,15 @@ function sendWithHttp(request, url2, headers, compression, userAgent, agent, dat
25600
25600
  const req = request(options, (res) => {
25601
25601
  const responseData = [];
25602
25602
  let responseSize = 0;
25603
- res.on("data", (chunk) => {
25604
- responseSize += chunk.length;
25603
+ res.on("data", (chunk2) => {
25604
+ responseSize += chunk2.length;
25605
25605
  if (responseSize > MAX_RESPONSE_BODY_SIZE) {
25606
25606
  const sizeError = new Error(`OTLP export response body exceeded size limit of ${MAX_RESPONSE_BODY_SIZE} bytes`);
25607
25607
  resolve3({ status: "failure", error: sizeError });
25608
25608
  res.destroy();
25609
25609
  return;
25610
25610
  }
25611
- responseData.push(chunk);
25611
+ responseData.push(chunk2);
25612
25612
  });
25613
25613
  res.on("end", () => {
25614
25614
  if (res.statusCode && res.statusCode <= 299) {
@@ -29501,7 +29501,7 @@ ${callerStack}`;
29501
29501
  var _a26, _b18;
29502
29502
  return (_b18 = (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.getAuthContext()) !== null && _b18 !== void 0 ? _b18 : null;
29503
29503
  }
29504
- _write(chunk, encoding, cb) {
29504
+ _write(chunk2, encoding, cb) {
29505
29505
  var _a26;
29506
29506
  const context2 = {
29507
29507
  callback: cb
@@ -29510,7 +29510,7 @@ ${callerStack}`;
29510
29510
  if (!Number.isNaN(flags)) {
29511
29511
  context2.flags = flags;
29512
29512
  }
29513
- (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.sendMessageWithContext(context2, chunk);
29513
+ (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.sendMessageWithContext(context2, chunk2);
29514
29514
  }
29515
29515
  _final(cb) {
29516
29516
  var _a26;
@@ -29541,7 +29541,7 @@ ${callerStack}`;
29541
29541
  var _a26;
29542
29542
  (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.startRead();
29543
29543
  }
29544
- _write(chunk, encoding, cb) {
29544
+ _write(chunk2, encoding, cb) {
29545
29545
  var _a26;
29546
29546
  const context2 = {
29547
29547
  callback: cb
@@ -29550,7 +29550,7 @@ ${callerStack}`;
29550
29550
  if (!Number.isNaN(flags)) {
29551
29551
  context2.flags = flags;
29552
29552
  }
29553
- (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.sendMessageWithContext(context2, chunk);
29553
+ (_a26 = this.call) === null || _a26 === void 0 ? void 0 : _a26.sendMessageWithContext(context2, chunk2);
29554
29554
  }
29555
29555
  _final(cb) {
29556
29556
  var _a26;
@@ -40112,9 +40112,9 @@ var require_compression_filter = __commonJS({
40112
40112
  let totalLength = 0;
40113
40113
  const messageParts = [];
40114
40114
  const decompresser = zlib2.createInflate();
40115
- decompresser.on("data", (chunk) => {
40116
- messageParts.push(chunk);
40117
- totalLength += chunk.byteLength;
40115
+ decompresser.on("data", (chunk2) => {
40116
+ messageParts.push(chunk2);
40117
+ totalLength += chunk2.byteLength;
40118
40118
  if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
40119
40119
  decompresser.destroy();
40120
40120
  reject({
@@ -40152,9 +40152,9 @@ var require_compression_filter = __commonJS({
40152
40152
  let totalLength = 0;
40153
40153
  const messageParts = [];
40154
40154
  const decompresser = zlib2.createGunzip();
40155
- decompresser.on("data", (chunk) => {
40156
- messageParts.push(chunk);
40157
- totalLength += chunk.byteLength;
40155
+ decompresser.on("data", (chunk2) => {
40156
+ messageParts.push(chunk2);
40157
+ totalLength += chunk2.byteLength;
40158
40158
  if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) {
40159
40159
  decompresser.destroy();
40160
40160
  reject({
@@ -44598,8 +44598,8 @@ var require_server_call = __commonJS({
44598
44598
  getMetricsRecorder() {
44599
44599
  return this.call.getMetricsRecorder();
44600
44600
  }
44601
- _write(chunk, encoding, callback) {
44602
- this.call.sendMessage(chunk, callback);
44601
+ _write(chunk2, encoding, callback) {
44602
+ this.call.sendMessage(chunk2, callback);
44603
44603
  }
44604
44604
  _final(callback) {
44605
44605
  var _a26;
@@ -44656,8 +44656,8 @@ var require_server_call = __commonJS({
44656
44656
  _read(size) {
44657
44657
  this.call.startRead();
44658
44658
  }
44659
- _write(chunk, encoding, callback) {
44660
- this.call.sendMessage(chunk, callback);
44659
+ _write(chunk2, encoding, callback) {
44660
+ this.call.sendMessage(chunk2, callback);
44661
44661
  }
44662
44662
  _final(callback) {
44663
44663
  var _a26;
@@ -45810,9 +45810,9 @@ var require_server_interceptors = __commonJS({
45810
45810
  return new Promise((resolve3, reject) => {
45811
45811
  let totalLength = 0;
45812
45812
  const messageParts = [];
45813
- decompresser.on("data", (chunk) => {
45814
- messageParts.push(chunk);
45815
- totalLength += chunk.byteLength;
45813
+ decompresser.on("data", (chunk2) => {
45814
+ messageParts.push(chunk2);
45815
+ totalLength += chunk2.byteLength;
45816
45816
  if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) {
45817
45817
  decompresser.destroy();
45818
45818
  reject({
@@ -50761,8 +50761,8 @@ var require_util4 = __commonJS({
50761
50761
  const { request } = url2.protocol === "http:" ? http : https;
50762
50762
  const req = request(url2, reqOpts, (res) => {
50763
50763
  let rawData = "";
50764
- res.on("data", (chunk) => {
50765
- rawData += chunk;
50764
+ res.on("data", (chunk2) => {
50765
+ rawData += chunk2;
50766
50766
  });
50767
50767
  res.on("end", () => {
50768
50768
  const statusCode = res.statusCode || 0;
@@ -74262,8 +74262,8 @@ var require_content_type_parser = __commonJS({
74262
74262
  payload.on("end", onEnd);
74263
74263
  payload.on("error", onEnd);
74264
74264
  payload.resume();
74265
- function onData(chunk) {
74266
- receivedLength += asString ? Buffer.byteLength(chunk) : chunk.length;
74265
+ function onData(chunk2) {
74266
+ receivedLength += asString ? Buffer.byteLength(chunk2) : chunk2.length;
74267
74267
  const { receivedEncodedLength = 0 } = payload;
74268
74268
  if (receivedLength > limit || receivedEncodedLength > limit) {
74269
74269
  payload.removeListener("data", onData);
@@ -74273,9 +74273,9 @@ var require_content_type_parser = __commonJS({
74273
74273
  return;
74274
74274
  }
74275
74275
  if (asString) {
74276
- body += chunk;
74276
+ body += chunk2;
74277
74277
  } else {
74278
- body.push(chunk);
74278
+ body.push(chunk2);
74279
74279
  }
74280
74280
  }
74281
74281
  function onEnd(err) {
@@ -78513,8 +78513,8 @@ var require_core = __commonJS({
78513
78513
  return this;
78514
78514
  }
78515
78515
  case "object": {
78516
- const cacheKey = schemaKeyRef;
78517
- this._cache.delete(cacheKey);
78516
+ const cacheKey2 = schemaKeyRef;
78517
+ this._cache.delete(cacheKey2);
78518
78518
  let id = schemaKeyRef[this.opts.schemaId];
78519
78519
  if (id) {
78520
78520
  id = (0, resolve_1.normalizeId)(id);
@@ -93993,10 +93993,10 @@ var require_request2 = __commonJS({
93993
93993
  const payload = this._lightMyRequest.payload;
93994
93994
  let more = true;
93995
93995
  let pushed = false;
93996
- let chunk;
93997
- while (more && (chunk = payload.read())) {
93996
+ let chunk2;
93997
+ while (more && (chunk2 = payload.read())) {
93998
93998
  pushed = true;
93999
- more = this.push(chunk);
93999
+ more = this.push(chunk2);
94000
94000
  }
94001
94001
  if (more && !pushed) {
94002
94002
  this._lightMyRequest.payload.once("readable", this._read.bind(this));
@@ -95275,7 +95275,7 @@ var require_light_my_request = __commonJS({
95275
95275
  return next();
95276
95276
  }
95277
95277
  const chunks = [];
95278
- payload.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
95278
+ payload.on("data", (chunk2) => chunks.push(Buffer.from(chunk2)));
95279
95279
  payload.on("end", () => {
95280
95280
  const payload2 = Buffer.concat(chunks);
95281
95281
  req.headers["content-length"] = req.headers["content-length"] || "" + payload2.length;
@@ -99527,7 +99527,7 @@ var require_commonjs5 = __commonJS({
99527
99527
  */
99528
99528
  set aborted(_3) {
99529
99529
  }
99530
- write(chunk, encoding, cb) {
99530
+ write(chunk2, encoding, cb) {
99531
99531
  if (this[ABORTED2])
99532
99532
  return false;
99533
99533
  if (this[EOF])
@@ -99543,12 +99543,12 @@ var require_commonjs5 = __commonJS({
99543
99543
  if (!encoding)
99544
99544
  encoding = "utf8";
99545
99545
  const fn = this[ASYNC] ? defer : nodefer;
99546
- if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
99547
- if (isArrayBufferView(chunk)) {
99548
- chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
99549
- } else if (isArrayBufferLike(chunk)) {
99550
- chunk = Buffer.from(chunk);
99551
- } else if (typeof chunk !== "string") {
99546
+ if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk2)) {
99547
+ if (isArrayBufferView(chunk2)) {
99548
+ chunk2 = Buffer.from(chunk2.buffer, chunk2.byteOffset, chunk2.byteLength);
99549
+ } else if (isArrayBufferLike(chunk2)) {
99550
+ chunk2 = Buffer.from(chunk2);
99551
+ } else if (typeof chunk2 !== "string") {
99552
99552
  throw new Error("Non-contiguous data written to non-objectMode stream");
99553
99553
  }
99554
99554
  }
@@ -99556,35 +99556,35 @@ var require_commonjs5 = __commonJS({
99556
99556
  if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
99557
99557
  this[FLUSH](true);
99558
99558
  if (this[FLOWING])
99559
- this.emit("data", chunk);
99559
+ this.emit("data", chunk2);
99560
99560
  else
99561
- this[BUFFERPUSH](chunk);
99561
+ this[BUFFERPUSH](chunk2);
99562
99562
  if (this[BUFFERLENGTH] !== 0)
99563
99563
  this.emit("readable");
99564
99564
  if (cb)
99565
99565
  fn(cb);
99566
99566
  return this[FLOWING];
99567
99567
  }
99568
- if (!chunk.length) {
99568
+ if (!chunk2.length) {
99569
99569
  if (this[BUFFERLENGTH] !== 0)
99570
99570
  this.emit("readable");
99571
99571
  if (cb)
99572
99572
  fn(cb);
99573
99573
  return this[FLOWING];
99574
99574
  }
99575
- if (typeof chunk === "string" && // unless it is a string already ready for us to use
99575
+ if (typeof chunk2 === "string" && // unless it is a string already ready for us to use
99576
99576
  !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)) {
99577
- chunk = Buffer.from(chunk, encoding);
99577
+ chunk2 = Buffer.from(chunk2, encoding);
99578
99578
  }
99579
- if (Buffer.isBuffer(chunk) && this[ENCODING]) {
99580
- chunk = this[DECODER].write(chunk);
99579
+ if (Buffer.isBuffer(chunk2) && this[ENCODING]) {
99580
+ chunk2 = this[DECODER].write(chunk2);
99581
99581
  }
99582
99582
  if (this[FLOWING] && this[BUFFERLENGTH] !== 0)
99583
99583
  this[FLUSH](true);
99584
99584
  if (this[FLOWING])
99585
- this.emit("data", chunk);
99585
+ this.emit("data", chunk2);
99586
99586
  else
99587
- this[BUFFERPUSH](chunk);
99587
+ this[BUFFERPUSH](chunk2);
99588
99588
  if (this[BUFFERLENGTH] !== 0)
99589
99589
  this.emit("readable");
99590
99590
  if (cb)
@@ -99623,39 +99623,39 @@ var require_commonjs5 = __commonJS({
99623
99623
  this[MAYBE_EMIT_END]();
99624
99624
  return ret;
99625
99625
  }
99626
- [READ](n, chunk) {
99626
+ [READ](n, chunk2) {
99627
99627
  if (this[OBJECTMODE])
99628
99628
  this[BUFFERSHIFT]();
99629
99629
  else {
99630
- const c = chunk;
99630
+ const c = chunk2;
99631
99631
  if (n === c.length || n === null)
99632
99632
  this[BUFFERSHIFT]();
99633
99633
  else if (typeof c === "string") {
99634
99634
  this[BUFFER][0] = c.slice(n);
99635
- chunk = c.slice(0, n);
99635
+ chunk2 = c.slice(0, n);
99636
99636
  this[BUFFERLENGTH] -= n;
99637
99637
  } else {
99638
99638
  this[BUFFER][0] = c.subarray(n);
99639
- chunk = c.subarray(0, n);
99639
+ chunk2 = c.subarray(0, n);
99640
99640
  this[BUFFERLENGTH] -= n;
99641
99641
  }
99642
99642
  }
99643
- this.emit("data", chunk);
99643
+ this.emit("data", chunk2);
99644
99644
  if (!this[BUFFER].length && !this[EOF])
99645
99645
  this.emit("drain");
99646
- return chunk;
99646
+ return chunk2;
99647
99647
  }
99648
- end(chunk, encoding, cb) {
99649
- if (typeof chunk === "function") {
99650
- cb = chunk;
99651
- chunk = void 0;
99648
+ end(chunk2, encoding, cb) {
99649
+ if (typeof chunk2 === "function") {
99650
+ cb = chunk2;
99651
+ chunk2 = void 0;
99652
99652
  }
99653
99653
  if (typeof encoding === "function") {
99654
99654
  cb = encoding;
99655
99655
  encoding = "utf8";
99656
99656
  }
99657
- if (chunk !== void 0)
99658
- this.write(chunk, encoding);
99657
+ if (chunk2 !== void 0)
99658
+ this.write(chunk2, encoding);
99659
99659
  if (cb)
99660
99660
  this.once("end", cb);
99661
99661
  this[EOF] = true;
@@ -99720,12 +99720,12 @@ var require_commonjs5 = __commonJS({
99720
99720
  get paused() {
99721
99721
  return this[PAUSED];
99722
99722
  }
99723
- [BUFFERPUSH](chunk) {
99723
+ [BUFFERPUSH](chunk2) {
99724
99724
  if (this[OBJECTMODE])
99725
99725
  this[BUFFERLENGTH] += 1;
99726
99726
  else
99727
- this[BUFFERLENGTH] += chunk.length;
99728
- this[BUFFER].push(chunk);
99727
+ this[BUFFERLENGTH] += chunk2.length;
99728
+ this[BUFFER].push(chunk2);
99729
99729
  }
99730
99730
  [BUFFERSHIFT]() {
99731
99731
  if (this[OBJECTMODE])
@@ -99740,8 +99740,8 @@ var require_commonjs5 = __commonJS({
99740
99740
  if (!noDrain && !this[BUFFER].length && !this[EOF])
99741
99741
  this.emit("drain");
99742
99742
  }
99743
- [FLUSHCHUNK](chunk) {
99744
- this.emit("data", chunk);
99743
+ [FLUSHCHUNK](chunk2) {
99744
+ this.emit("data", chunk2);
99745
99745
  return this[FLOWING];
99746
99746
  }
99747
99747
  /**
@@ -106259,14 +106259,14 @@ var require_permessage_deflate = __commonJS({
106259
106259
  }
106260
106260
  };
106261
106261
  module.exports = PerMessageDeflate;
106262
- function deflateOnData(chunk) {
106263
- this[kBuffers].push(chunk);
106264
- this[kTotalLength] += chunk.length;
106262
+ function deflateOnData(chunk2) {
106263
+ this[kBuffers].push(chunk2);
106264
+ this[kTotalLength] += chunk2.length;
106265
106265
  }
106266
- function inflateOnData(chunk) {
106267
- this[kTotalLength] += chunk.length;
106266
+ function inflateOnData(chunk2) {
106267
+ this[kTotalLength] += chunk2.length;
106268
106268
  if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
106269
- this[kBuffers].push(chunk);
106269
+ this[kBuffers].push(chunk2);
106270
106270
  return;
106271
106271
  }
106272
106272
  this[kError] = new RangeError("Max payload size exceeded");
@@ -106560,10 +106560,10 @@ var require_receiver = __commonJS({
106560
106560
  * @param {Function} cb Callback
106561
106561
  * @private
106562
106562
  */
106563
- _write(chunk, encoding, cb) {
106563
+ _write(chunk2, encoding, cb) {
106564
106564
  if (this._opcode === 8 && this._state == GET_INFO) return cb();
106565
- this._bufferedBytes += chunk.length;
106566
- this._buffers.push(chunk);
106565
+ this._bufferedBytes += chunk2.length;
106566
+ this._buffers.push(chunk2);
106567
106567
  this.startLoop(cb);
106568
106568
  }
106569
106569
  /**
@@ -107959,7 +107959,7 @@ var require_websocket = __commonJS({
107959
107959
  var http = __require("http");
107960
107960
  var net2 = __require("net");
107961
107961
  var tls = __require("tls");
107962
- var { randomBytes: randomBytes3, createHash: createHash8 } = __require("crypto");
107962
+ var { randomBytes: randomBytes3, createHash: createHash9 } = __require("crypto");
107963
107963
  var { Duplex, Readable: Readable4 } = __require("stream");
107964
107964
  var { URL: URL2 } = __require("url");
107965
107965
  var PerMessageDeflate = require_permessage_deflate();
@@ -108619,7 +108619,7 @@ var require_websocket = __commonJS({
108619
108619
  abortHandshake(websocket, socket, "Invalid Upgrade header");
108620
108620
  return;
108621
108621
  }
108622
- const digest = createHash8("sha1").update(key + GUID).digest("base64");
108622
+ const digest = createHash9("sha1").update(key + GUID).digest("base64");
108623
108623
  if (res.headers["sec-websocket-accept"] !== digest) {
108624
108624
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
108625
108625
  return;
@@ -108800,8 +108800,8 @@ var require_websocket = __commonJS({
108800
108800
  this.removeListener("end", socketOnEnd);
108801
108801
  websocket._readyState = WebSocket2.CLOSING;
108802
108802
  if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && this._readableState.length !== 0) {
108803
- const chunk = this.read(this._readableState.length);
108804
- websocket._receiver.write(chunk);
108803
+ const chunk2 = this.read(this._readableState.length);
108804
+ websocket._receiver.write(chunk2);
108805
108805
  }
108806
108806
  websocket._receiver.end();
108807
108807
  this[kWebSocket] = void 0;
@@ -108813,8 +108813,8 @@ var require_websocket = __commonJS({
108813
108813
  websocket._receiver.on("finish", receiverOnFinish);
108814
108814
  }
108815
108815
  }
108816
- function socketOnData(chunk) {
108817
- if (!this[kWebSocket]._receiver.write(chunk)) {
108816
+ function socketOnData(chunk2) {
108817
+ if (!this[kWebSocket]._receiver.write(chunk2)) {
108818
108818
  this.pause();
108819
108819
  }
108820
108820
  }
@@ -108917,14 +108917,14 @@ var require_stream = __commonJS({
108917
108917
  duplex._read = function() {
108918
108918
  if (ws.isPaused) ws.resume();
108919
108919
  };
108920
- duplex._write = function(chunk, encoding, callback) {
108920
+ duplex._write = function(chunk2, encoding, callback) {
108921
108921
  if (ws.readyState === ws.CONNECTING) {
108922
108922
  ws.once("open", function open4() {
108923
- duplex._write(chunk, encoding, callback);
108923
+ duplex._write(chunk2, encoding, callback);
108924
108924
  });
108925
108925
  return;
108926
108926
  }
108927
- ws.send(chunk, callback);
108927
+ ws.send(chunk2, callback);
108928
108928
  };
108929
108929
  duplex.on("end", duplexOnEnd);
108930
108930
  duplex.on("error", duplexOnError);
@@ -108986,7 +108986,7 @@ var require_websocket_server = __commonJS({
108986
108986
  var EventEmitter3 = __require("events");
108987
108987
  var http = __require("http");
108988
108988
  var { Duplex } = __require("stream");
108989
- var { createHash: createHash8 } = __require("crypto");
108989
+ var { createHash: createHash9 } = __require("crypto");
108990
108990
  var extension = require_extension();
108991
108991
  var PerMessageDeflate = require_permessage_deflate();
108992
108992
  var subprotocol = require_subprotocol();
@@ -109287,7 +109287,7 @@ var require_websocket_server = __commonJS({
109287
109287
  );
109288
109288
  }
109289
109289
  if (this._state > RUNNING) return abortHandshake(socket, 503);
109290
- const digest = createHash8("sha1").update(key + GUID).digest("base64");
109290
+ const digest = createHash9("sha1").update(key + GUID).digest("base64");
109291
109291
  const headers = [
109292
109292
  "HTTP/1.1 101 Switching Protocols",
109293
109293
  "Upgrade: websocket",
@@ -109879,8 +109879,8 @@ var require_stream_writable = __commonJS({
109879
109879
  var Buffer3 = __require("buffer").Buffer;
109880
109880
  var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {
109881
109881
  };
109882
- function _uint8ArrayToBuffer(chunk) {
109883
- return Buffer3.from(chunk);
109882
+ function _uint8ArrayToBuffer(chunk2) {
109883
+ return Buffer3.from(chunk2);
109884
109884
  }
109885
109885
  function _isUint8Array(obj) {
109886
109886
  return Buffer3.isBuffer(obj) || obj instanceof OurUint8Array;
@@ -109993,12 +109993,12 @@ var require_stream_writable = __commonJS({
109993
109993
  errorOrDestroy(stream, er);
109994
109994
  process.nextTick(cb, er);
109995
109995
  }
109996
- function validChunk(stream, state, chunk, cb) {
109996
+ function validChunk(stream, state, chunk2, cb) {
109997
109997
  var er;
109998
- if (chunk === null) {
109998
+ if (chunk2 === null) {
109999
109999
  er = new ERR_STREAM_NULL_VALUES();
110000
- } else if (typeof chunk !== "string" && !state.objectMode) {
110001
- er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk);
110000
+ } else if (typeof chunk2 !== "string" && !state.objectMode) {
110001
+ er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer"], chunk2);
110002
110002
  }
110003
110003
  if (er) {
110004
110004
  errorOrDestroy(stream, er);
@@ -110007,12 +110007,12 @@ var require_stream_writable = __commonJS({
110007
110007
  }
110008
110008
  return true;
110009
110009
  }
110010
- Writable2.prototype.write = function(chunk, encoding, cb) {
110010
+ Writable2.prototype.write = function(chunk2, encoding, cb) {
110011
110011
  var state = this._writableState;
110012
110012
  var ret = false;
110013
- var isBuf = !state.objectMode && _isUint8Array(chunk);
110014
- if (isBuf && !Buffer3.isBuffer(chunk)) {
110015
- chunk = _uint8ArrayToBuffer(chunk);
110013
+ var isBuf = !state.objectMode && _isUint8Array(chunk2);
110014
+ if (isBuf && !Buffer3.isBuffer(chunk2)) {
110015
+ chunk2 = _uint8ArrayToBuffer(chunk2);
110016
110016
  }
110017
110017
  if (typeof encoding === "function") {
110018
110018
  cb = encoding;
@@ -110022,9 +110022,9 @@ var require_stream_writable = __commonJS({
110022
110022
  else if (!encoding) encoding = state.defaultEncoding;
110023
110023
  if (typeof cb !== "function") cb = nop;
110024
110024
  if (state.ending) writeAfterEnd(this, cb);
110025
- else if (isBuf || validChunk(this, state, chunk, cb)) {
110025
+ else if (isBuf || validChunk(this, state, chunk2, cb)) {
110026
110026
  state.pendingcb++;
110027
- ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
110027
+ ret = writeOrBuffer(this, state, isBuf, chunk2, encoding, cb);
110028
110028
  }
110029
110029
  return ret;
110030
110030
  };
@@ -110053,11 +110053,11 @@ var require_stream_writable = __commonJS({
110053
110053
  return this._writableState && this._writableState.getBuffer();
110054
110054
  }
110055
110055
  });
110056
- function decodeChunk(state, chunk, encoding) {
110057
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === "string") {
110058
- chunk = Buffer3.from(chunk, encoding);
110056
+ function decodeChunk(state, chunk2, encoding) {
110057
+ if (!state.objectMode && state.decodeStrings !== false && typeof chunk2 === "string") {
110058
+ chunk2 = Buffer3.from(chunk2, encoding);
110059
110059
  }
110060
- return chunk;
110060
+ return chunk2;
110061
110061
  }
110062
110062
  Object.defineProperty(Writable2.prototype, "writableHighWaterMark", {
110063
110063
  // making it explicit this property is not enumerable
@@ -110068,23 +110068,23 @@ var require_stream_writable = __commonJS({
110068
110068
  return this._writableState.highWaterMark;
110069
110069
  }
110070
110070
  });
110071
- function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
110071
+ function writeOrBuffer(stream, state, isBuf, chunk2, encoding, cb) {
110072
110072
  if (!isBuf) {
110073
- var newChunk = decodeChunk(state, chunk, encoding);
110074
- if (chunk !== newChunk) {
110073
+ var newChunk = decodeChunk(state, chunk2, encoding);
110074
+ if (chunk2 !== newChunk) {
110075
110075
  isBuf = true;
110076
110076
  encoding = "buffer";
110077
- chunk = newChunk;
110077
+ chunk2 = newChunk;
110078
110078
  }
110079
110079
  }
110080
- var len = state.objectMode ? 1 : chunk.length;
110080
+ var len = state.objectMode ? 1 : chunk2.length;
110081
110081
  state.length += len;
110082
110082
  var ret = state.length < state.highWaterMark;
110083
110083
  if (!ret) state.needDrain = true;
110084
110084
  if (state.writing || state.corked) {
110085
110085
  var last = state.lastBufferedRequest;
110086
110086
  state.lastBufferedRequest = {
110087
- chunk,
110087
+ chunk: chunk2,
110088
110088
  encoding,
110089
110089
  isBuf,
110090
110090
  callback: cb,
@@ -110097,18 +110097,18 @@ var require_stream_writable = __commonJS({
110097
110097
  }
110098
110098
  state.bufferedRequestCount += 1;
110099
110099
  } else {
110100
- doWrite(stream, state, false, len, chunk, encoding, cb);
110100
+ doWrite(stream, state, false, len, chunk2, encoding, cb);
110101
110101
  }
110102
110102
  return ret;
110103
110103
  }
110104
- function doWrite(stream, state, writev, len, chunk, encoding, cb) {
110104
+ function doWrite(stream, state, writev, len, chunk2, encoding, cb) {
110105
110105
  state.writelen = len;
110106
110106
  state.writecb = cb;
110107
110107
  state.writing = true;
110108
110108
  state.sync = true;
110109
110109
  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED("write"));
110110
- else if (writev) stream._writev(chunk, state.onwrite);
110111
- else stream._write(chunk, encoding, state.onwrite);
110110
+ else if (writev) stream._writev(chunk2, state.onwrite);
110111
+ else stream._write(chunk2, encoding, state.onwrite);
110112
110112
  state.sync = false;
110113
110113
  }
110114
110114
  function onwriteError(stream, state, sync, er, cb) {
@@ -110191,11 +110191,11 @@ var require_stream_writable = __commonJS({
110191
110191
  state.bufferedRequestCount = 0;
110192
110192
  } else {
110193
110193
  while (entry) {
110194
- var chunk = entry.chunk;
110194
+ var chunk2 = entry.chunk;
110195
110195
  var encoding = entry.encoding;
110196
110196
  var cb = entry.callback;
110197
- var len = state.objectMode ? 1 : chunk.length;
110198
- doWrite(stream, state, false, len, chunk, encoding, cb);
110197
+ var len = state.objectMode ? 1 : chunk2.length;
110198
+ doWrite(stream, state, false, len, chunk2, encoding, cb);
110199
110199
  entry = entry.next;
110200
110200
  state.bufferedRequestCount--;
110201
110201
  if (state.writing) {
@@ -110207,21 +110207,21 @@ var require_stream_writable = __commonJS({
110207
110207
  state.bufferedRequest = entry;
110208
110208
  state.bufferProcessing = false;
110209
110209
  }
110210
- Writable2.prototype._write = function(chunk, encoding, cb) {
110210
+ Writable2.prototype._write = function(chunk2, encoding, cb) {
110211
110211
  cb(new ERR_METHOD_NOT_IMPLEMENTED("_write()"));
110212
110212
  };
110213
110213
  Writable2.prototype._writev = null;
110214
- Writable2.prototype.end = function(chunk, encoding, cb) {
110214
+ Writable2.prototype.end = function(chunk2, encoding, cb) {
110215
110215
  var state = this._writableState;
110216
- if (typeof chunk === "function") {
110217
- cb = chunk;
110218
- chunk = null;
110216
+ if (typeof chunk2 === "function") {
110217
+ cb = chunk2;
110218
+ chunk2 = null;
110219
110219
  encoding = null;
110220
110220
  } else if (typeof encoding === "function") {
110221
110221
  cb = encoding;
110222
110222
  encoding = null;
110223
110223
  }
110224
- if (chunk !== null && chunk !== void 0) this.write(chunk, encoding);
110224
+ if (chunk2 !== null && chunk2 !== void 0) this.write(chunk2, encoding);
110225
110225
  if (state.corked) {
110226
110226
  state.corked = 1;
110227
110227
  this.uncork();
@@ -111067,8 +111067,8 @@ var require_stream_readable = __commonJS({
111067
111067
  var Buffer3 = __require("buffer").Buffer;
111068
111068
  var OurUint8Array = (typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : typeof self !== "undefined" ? self : {}).Uint8Array || function() {
111069
111069
  };
111070
- function _uint8ArrayToBuffer(chunk) {
111071
- return Buffer3.from(chunk);
111070
+ function _uint8ArrayToBuffer(chunk2) {
111071
+ return Buffer3.from(chunk2);
111072
111072
  }
111073
111073
  function _isUint8Array(obj) {
111074
111074
  return Buffer3.isBuffer(obj) || obj instanceof OurUint8Array;
@@ -111172,14 +111172,14 @@ var require_stream_readable = __commonJS({
111172
111172
  Readable4.prototype._destroy = function(err, cb) {
111173
111173
  cb(err);
111174
111174
  };
111175
- Readable4.prototype.push = function(chunk, encoding) {
111175
+ Readable4.prototype.push = function(chunk2, encoding) {
111176
111176
  var state = this._readableState;
111177
111177
  var skipChunkCheck;
111178
111178
  if (!state.objectMode) {
111179
- if (typeof chunk === "string") {
111179
+ if (typeof chunk2 === "string") {
111180
111180
  encoding = encoding || state.defaultEncoding;
111181
111181
  if (encoding !== state.encoding) {
111182
- chunk = Buffer3.from(chunk, encoding);
111182
+ chunk2 = Buffer3.from(chunk2, encoding);
111183
111183
  encoding = "";
111184
111184
  }
111185
111185
  skipChunkCheck = true;
@@ -111187,29 +111187,29 @@ var require_stream_readable = __commonJS({
111187
111187
  } else {
111188
111188
  skipChunkCheck = true;
111189
111189
  }
111190
- return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
111190
+ return readableAddChunk(this, chunk2, encoding, false, skipChunkCheck);
111191
111191
  };
111192
- Readable4.prototype.unshift = function(chunk) {
111193
- return readableAddChunk(this, chunk, null, true, false);
111192
+ Readable4.prototype.unshift = function(chunk2) {
111193
+ return readableAddChunk(this, chunk2, null, true, false);
111194
111194
  };
111195
- function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
111196
- debug("readableAddChunk", chunk);
111195
+ function readableAddChunk(stream, chunk2, encoding, addToFront, skipChunkCheck) {
111196
+ debug("readableAddChunk", chunk2);
111197
111197
  var state = stream._readableState;
111198
- if (chunk === null) {
111198
+ if (chunk2 === null) {
111199
111199
  state.reading = false;
111200
111200
  onEofChunk(stream, state);
111201
111201
  } else {
111202
111202
  var er;
111203
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
111203
+ if (!skipChunkCheck) er = chunkInvalid(state, chunk2);
111204
111204
  if (er) {
111205
111205
  errorOrDestroy(stream, er);
111206
- } else if (state.objectMode || chunk && chunk.length > 0) {
111207
- if (typeof chunk !== "string" && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer3.prototype) {
111208
- chunk = _uint8ArrayToBuffer(chunk);
111206
+ } else if (state.objectMode || chunk2 && chunk2.length > 0) {
111207
+ if (typeof chunk2 !== "string" && !state.objectMode && Object.getPrototypeOf(chunk2) !== Buffer3.prototype) {
111208
+ chunk2 = _uint8ArrayToBuffer(chunk2);
111209
111209
  }
111210
111210
  if (addToFront) {
111211
111211
  if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
111212
- else addChunk(stream, state, chunk, true);
111212
+ else addChunk(stream, state, chunk2, true);
111213
111213
  } else if (state.ended) {
111214
111214
  errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
111215
111215
  } else if (state.destroyed) {
@@ -111217,11 +111217,11 @@ var require_stream_readable = __commonJS({
111217
111217
  } else {
111218
111218
  state.reading = false;
111219
111219
  if (state.decoder && !encoding) {
111220
- chunk = state.decoder.write(chunk);
111221
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);
111220
+ chunk2 = state.decoder.write(chunk2);
111221
+ if (state.objectMode || chunk2.length !== 0) addChunk(stream, state, chunk2, false);
111222
111222
  else maybeReadMore(stream, state);
111223
111223
  } else {
111224
- addChunk(stream, state, chunk, false);
111224
+ addChunk(stream, state, chunk2, false);
111225
111225
  }
111226
111226
  }
111227
111227
  } else if (!addToFront) {
@@ -111231,22 +111231,22 @@ var require_stream_readable = __commonJS({
111231
111231
  }
111232
111232
  return !state.ended && (state.length < state.highWaterMark || state.length === 0);
111233
111233
  }
111234
- function addChunk(stream, state, chunk, addToFront) {
111234
+ function addChunk(stream, state, chunk2, addToFront) {
111235
111235
  if (state.flowing && state.length === 0 && !state.sync) {
111236
111236
  state.awaitDrain = 0;
111237
- stream.emit("data", chunk);
111237
+ stream.emit("data", chunk2);
111238
111238
  } else {
111239
- state.length += state.objectMode ? 1 : chunk.length;
111240
- if (addToFront) state.buffer.unshift(chunk);
111241
- else state.buffer.push(chunk);
111239
+ state.length += state.objectMode ? 1 : chunk2.length;
111240
+ if (addToFront) state.buffer.unshift(chunk2);
111241
+ else state.buffer.push(chunk2);
111242
111242
  if (state.needReadable) emitReadable(stream);
111243
111243
  }
111244
111244
  maybeReadMore(stream, state);
111245
111245
  }
111246
- function chunkInvalid(state, chunk) {
111246
+ function chunkInvalid(state, chunk2) {
111247
111247
  var er;
111248
- if (!_isUint8Array(chunk) && typeof chunk !== "string" && chunk !== void 0 && !state.objectMode) {
111249
- er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk);
111248
+ if (!_isUint8Array(chunk2) && typeof chunk2 !== "string" && chunk2 !== void 0 && !state.objectMode) {
111249
+ er = new ERR_INVALID_ARG_TYPE("chunk", ["string", "Buffer", "Uint8Array"], chunk2);
111250
111250
  }
111251
111251
  return er;
111252
111252
  }
@@ -111355,10 +111355,10 @@ var require_stream_readable = __commonJS({
111355
111355
  debug("onEofChunk");
111356
111356
  if (state.ended) return;
111357
111357
  if (state.decoder) {
111358
- var chunk = state.decoder.end();
111359
- if (chunk && chunk.length) {
111360
- state.buffer.push(chunk);
111361
- state.length += state.objectMode ? 1 : chunk.length;
111358
+ var chunk2 = state.decoder.end();
111359
+ if (chunk2 && chunk2.length) {
111360
+ state.buffer.push(chunk2);
111361
+ state.length += state.objectMode ? 1 : chunk2.length;
111362
111362
  }
111363
111363
  }
111364
111364
  state.ended = true;
@@ -111462,9 +111462,9 @@ var require_stream_readable = __commonJS({
111462
111462
  if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
111463
111463
  }
111464
111464
  src.on("data", ondata);
111465
- function ondata(chunk) {
111465
+ function ondata(chunk2) {
111466
111466
  debug("ondata");
111467
- var ret = dest.write(chunk);
111467
+ var ret = dest.write(chunk2);
111468
111468
  debug("dest.write", ret);
111469
111469
  if (ret === false) {
111470
111470
  if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
@@ -111645,17 +111645,17 @@ var require_stream_readable = __commonJS({
111645
111645
  stream.on("end", function() {
111646
111646
  debug("wrapped end");
111647
111647
  if (state.decoder && !state.ended) {
111648
- var chunk = state.decoder.end();
111649
- if (chunk && chunk.length) _this.push(chunk);
111648
+ var chunk2 = state.decoder.end();
111649
+ if (chunk2 && chunk2.length) _this.push(chunk2);
111650
111650
  }
111651
111651
  _this.push(null);
111652
111652
  });
111653
- stream.on("data", function(chunk) {
111653
+ stream.on("data", function(chunk2) {
111654
111654
  debug("wrapped data");
111655
- if (state.decoder) chunk = state.decoder.write(chunk);
111656
- if (state.objectMode && (chunk === null || chunk === void 0)) return;
111657
- else if (!state.objectMode && (!chunk || !chunk.length)) return;
111658
- var ret = _this.push(chunk);
111655
+ if (state.decoder) chunk2 = state.decoder.write(chunk2);
111656
+ if (state.objectMode && (chunk2 === null || chunk2 === void 0)) return;
111657
+ else if (!state.objectMode && (!chunk2 || !chunk2.length)) return;
111658
+ var ret = _this.push(chunk2);
111659
111659
  if (!ret) {
111660
111660
  paused = true;
111661
111661
  stream.pause();
@@ -111844,17 +111844,17 @@ var require_stream_transform = __commonJS({
111844
111844
  done(this, null, null);
111845
111845
  }
111846
111846
  }
111847
- Transform.prototype.push = function(chunk, encoding) {
111847
+ Transform.prototype.push = function(chunk2, encoding) {
111848
111848
  this._transformState.needTransform = false;
111849
- return Duplex.prototype.push.call(this, chunk, encoding);
111849
+ return Duplex.prototype.push.call(this, chunk2, encoding);
111850
111850
  };
111851
- Transform.prototype._transform = function(chunk, encoding, cb) {
111851
+ Transform.prototype._transform = function(chunk2, encoding, cb) {
111852
111852
  cb(new ERR_METHOD_NOT_IMPLEMENTED("_transform()"));
111853
111853
  };
111854
- Transform.prototype._write = function(chunk, encoding, cb) {
111854
+ Transform.prototype._write = function(chunk2, encoding, cb) {
111855
111855
  var ts = this._transformState;
111856
111856
  ts.writecb = cb;
111857
- ts.writechunk = chunk;
111857
+ ts.writechunk = chunk2;
111858
111858
  ts.writeencoding = encoding;
111859
111859
  if (!ts.transforming) {
111860
111860
  var rs = this._readableState;
@@ -111897,8 +111897,8 @@ var require_stream_passthrough = __commonJS({
111897
111897
  if (!(this instanceof PassThrough)) return new PassThrough(options);
111898
111898
  Transform.call(this, options);
111899
111899
  }
111900
- PassThrough.prototype._transform = function(chunk, encoding, cb) {
111901
- cb(null, chunk);
111900
+ PassThrough.prototype._transform = function(chunk2, encoding, cb) {
111901
+ cb(null, chunk2);
111902
111902
  };
111903
111903
  }
111904
111904
  });
@@ -112441,13 +112441,13 @@ var require_websocket2 = __commonJS({
112441
112441
  clientStream.removeListener("data", onData);
112442
112442
  resolve3(ws);
112443
112443
  });
112444
- const onData = (chunk) => {
112445
- if (chunk.toString().includes("HTTP/1.1 101 Switching Protocols")) {
112444
+ const onData = (chunk2) => {
112445
+ if (chunk2.toString().includes("HTTP/1.1 101 Switching Protocols")) {
112446
112446
  ws._isServer = false;
112447
112447
  ws.setSocket(clientStream, head, { maxPayload: 0 });
112448
112448
  } else {
112449
112449
  clientStream.removeListener("data", onData);
112450
- const statusCode = Number(statusCodeReg.exec(chunk.toString())[1]);
112450
+ const statusCode = Number(statusCodeReg.exec(chunk2.toString())[1]);
112451
112451
  reject(new Error("Unexpected server response: " + statusCode));
112452
112452
  }
112453
112453
  };
@@ -112623,15 +112623,15 @@ var require_sbmh = __commonJS({
112623
112623
  this.matches = 0;
112624
112624
  this._bufpos = 0;
112625
112625
  };
112626
- SBMH.prototype.push = function(chunk, pos) {
112627
- if (!Buffer.isBuffer(chunk)) {
112628
- chunk = Buffer.from(chunk, "binary");
112626
+ SBMH.prototype.push = function(chunk2, pos) {
112627
+ if (!Buffer.isBuffer(chunk2)) {
112628
+ chunk2 = Buffer.from(chunk2, "binary");
112629
112629
  }
112630
- const chlen = chunk.length;
112630
+ const chlen = chunk2.length;
112631
112631
  this._bufpos = pos || 0;
112632
112632
  let r;
112633
112633
  while (r !== chlen && this.matches < this.maxMatches) {
112634
- r = this._sbmh_feed(chunk);
112634
+ r = this._sbmh_feed(chunk2);
112635
112635
  }
112636
112636
  return r;
112637
112637
  };
@@ -114067,8 +114067,8 @@ var require_multipart = __commonJS({
114067
114067
  checkFinished();
114068
114068
  });
114069
114069
  }
114070
- Multipart.prototype.write = function(chunk, cb) {
114071
- const r = this.parser.write(chunk);
114070
+ Multipart.prototype.write = function(chunk2, cb) {
114071
+ const r = this.parser.write(chunk2);
114072
114072
  if (r && !this._pause) {
114073
114073
  cb();
114074
114074
  } else {
@@ -114565,8 +114565,8 @@ var require_main = __commonJS({
114565
114565
  }
114566
114566
  throw new Error("Unsupported Content-Type.");
114567
114567
  };
114568
- Busboy.prototype._write = function(chunk, encoding, cb) {
114569
- this._parser.write(chunk, cb);
114568
+ Busboy.prototype._write = function(chunk2, encoding, cb) {
114569
+ this._parser.write(chunk2, cb);
114570
114570
  };
114571
114571
  module.exports = Busboy;
114572
114572
  module.exports.default = Busboy;
@@ -115308,8 +115308,8 @@ var require_multipart2 = __commonJS({
115308
115308
  }
115309
115309
  const fileChunks = [];
115310
115310
  let err;
115311
- for await (const chunk of this.file) {
115312
- fileChunks.push(chunk);
115311
+ for await (const chunk2 of this.file) {
115312
+ fileChunks.push(chunk2);
115313
115313
  if (throwFileSizeLimit && this.file.truncated) {
115314
115314
  err = new RequestFileTooLargeError();
115315
115315
  err.part = this;
@@ -118335,13 +118335,13 @@ var require_request3 = __commonJS({
118335
118335
  channels.create.publish({ request: this });
118336
118336
  }
118337
118337
  }
118338
- onBodySent(chunk) {
118338
+ onBodySent(chunk2) {
118339
118339
  if (channels.bodyChunkSent.hasSubscribers) {
118340
- channels.bodyChunkSent.publish({ request: this, chunk });
118340
+ channels.bodyChunkSent.publish({ request: this, chunk: chunk2 });
118341
118341
  }
118342
118342
  if (this[kHandler].onBodySent) {
118343
118343
  try {
118344
- return this[kHandler].onBodySent(chunk);
118344
+ return this[kHandler].onBodySent(chunk2);
118345
118345
  } catch (err) {
118346
118346
  this.abort(err);
118347
118347
  }
@@ -118384,14 +118384,14 @@ var require_request3 = __commonJS({
118384
118384
  this.abort(err);
118385
118385
  }
118386
118386
  }
118387
- onData(chunk) {
118387
+ onData(chunk2) {
118388
118388
  assert2(!this.aborted);
118389
118389
  assert2(!this.completed);
118390
118390
  if (channels.bodyChunkReceived.hasSubscribers) {
118391
- channels.bodyChunkReceived.publish({ request: this, chunk });
118391
+ channels.bodyChunkReceived.publish({ request: this, chunk: chunk2 });
118392
118392
  }
118393
118393
  try {
118394
- return this[kHandler].onData(chunk);
118394
+ return this[kHandler].onData(chunk2);
118395
118395
  } catch (err) {
118396
118396
  this.abort(err);
118397
118397
  return false;
@@ -121490,17 +121490,17 @@ var require_util8 = __commonJS({
121490
121490
  const bytes = [];
121491
121491
  let byteLength = 0;
121492
121492
  do {
121493
- const { done, value: chunk } = await reader.read();
121493
+ const { done, value: chunk2 } = await reader.read();
121494
121494
  if (done) {
121495
121495
  successSteps(Buffer.concat(bytes, byteLength));
121496
121496
  return;
121497
121497
  }
121498
- if (!isUint8Array(chunk)) {
121498
+ if (!isUint8Array(chunk2)) {
121499
121499
  failureSteps(new TypeError("Received non-Uint8Array chunk"));
121500
121500
  return;
121501
121501
  }
121502
- bytes.push(chunk);
121503
- byteLength += chunk.length;
121502
+ bytes.push(chunk2);
121503
+ byteLength += chunk2.length;
121504
121504
  } while (true);
121505
121505
  } catch (e) {
121506
121506
  failureSteps(e);
@@ -121606,18 +121606,18 @@ var require_util8 = __commonJS({
121606
121606
  super();
121607
121607
  this.#zlibOptions = zlibOptions;
121608
121608
  }
121609
- _transform(chunk, encoding, callback) {
121609
+ _transform(chunk2, encoding, callback) {
121610
121610
  if (!this._inflateStream) {
121611
- if (chunk.length === 0) {
121611
+ if (chunk2.length === 0) {
121612
121612
  callback();
121613
121613
  return;
121614
121614
  }
121615
- this._inflateStream = (chunk[0] & 15) === 8 ? zlib2.createInflate(this.#zlibOptions) : zlib2.createInflateRaw(this.#zlibOptions);
121615
+ this._inflateStream = (chunk2[0] & 15) === 8 ? zlib2.createInflate(this.#zlibOptions) : zlib2.createInflateRaw(this.#zlibOptions);
121616
121616
  this._inflateStream.on("data", this.push.bind(this));
121617
121617
  this._inflateStream.on("end", () => this.push(null));
121618
121618
  this._inflateStream.on("error", (err) => this.destroy(err));
121619
121619
  }
121620
- this._inflateStream.write(chunk, encoding, callback);
121620
+ this._inflateStream.write(chunk2, encoding, callback);
121621
121621
  }
121622
121622
  _final(callback) {
121623
121623
  if (this._inflateStream) {
@@ -122352,29 +122352,29 @@ Content-Disposition: form-data`;
122352
122352
  let hasUnknownSizeValue = false;
122353
122353
  for (const [name25, value] of object3) {
122354
122354
  if (typeof value === "string") {
122355
- const chunk2 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name25))}"\r
122355
+ const chunk3 = textEncoder.encode(prefix + `; name="${formdataEscape(normalizeLinefeeds(name25))}"\r
122356
122356
  \r
122357
122357
  ${normalizeLinefeeds(value)}\r
122358
122358
  `);
122359
- blobParts.push(chunk2);
122360
- length += chunk2.byteLength;
122359
+ blobParts.push(chunk3);
122360
+ length += chunk3.byteLength;
122361
122361
  } else {
122362
- const chunk2 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name25))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
122362
+ const chunk3 = textEncoder.encode(`${prefix}; name="${formdataEscape(normalizeLinefeeds(name25))}"` + (value.name ? `; filename="${formdataEscape(value.name)}"` : "") + `\r
122363
122363
  Content-Type: ${value.type || "application/octet-stream"}\r
122364
122364
  \r
122365
122365
  `);
122366
- blobParts.push(chunk2, value, rn);
122366
+ blobParts.push(chunk3, value, rn);
122367
122367
  if (typeof value.size === "number") {
122368
- length += chunk2.byteLength + value.size + rn.byteLength;
122368
+ length += chunk3.byteLength + value.size + rn.byteLength;
122369
122369
  } else {
122370
122370
  hasUnknownSizeValue = true;
122371
122371
  }
122372
122372
  }
122373
122373
  }
122374
- const chunk = textEncoder.encode(`--${boundary}--\r
122374
+ const chunk2 = textEncoder.encode(`--${boundary}--\r
122375
122375
  `);
122376
- blobParts.push(chunk);
122377
- length += chunk.byteLength;
122376
+ blobParts.push(chunk2);
122377
+ length += chunk2.byteLength;
122378
122378
  if (hasUnknownSizeValue) {
122379
122379
  length = null;
122380
122380
  }
@@ -122801,41 +122801,41 @@ var require_client_h1 = __commonJS({
122801
122801
  }
122802
122802
  readMore() {
122803
122803
  while (!this.paused && this.ptr) {
122804
- const chunk = this.socket.read();
122805
- if (chunk === null) {
122804
+ const chunk2 = this.socket.read();
122805
+ if (chunk2 === null) {
122806
122806
  break;
122807
122807
  }
122808
- this.execute(chunk);
122808
+ this.execute(chunk2);
122809
122809
  }
122810
122810
  }
122811
122811
  /**
122812
122812
  * @param {Buffer} chunk
122813
122813
  */
122814
- execute(chunk) {
122814
+ execute(chunk2) {
122815
122815
  assert2(currentParser === null);
122816
122816
  assert2(this.ptr != null);
122817
122817
  assert2(!this.paused);
122818
122818
  const { socket, llhttp } = this;
122819
- if (chunk.length > currentBufferSize) {
122819
+ if (chunk2.length > currentBufferSize) {
122820
122820
  if (currentBufferPtr) {
122821
122821
  llhttp.free(currentBufferPtr);
122822
122822
  }
122823
- currentBufferSize = Math.ceil(chunk.length / 4096) * 4096;
122823
+ currentBufferSize = Math.ceil(chunk2.length / 4096) * 4096;
122824
122824
  currentBufferPtr = llhttp.malloc(currentBufferSize);
122825
122825
  }
122826
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk);
122826
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(chunk2);
122827
122827
  try {
122828
122828
  let ret;
122829
122829
  try {
122830
- currentBufferRef = chunk;
122830
+ currentBufferRef = chunk2;
122831
122831
  currentParser = this;
122832
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk.length);
122832
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, chunk2.length);
122833
122833
  } finally {
122834
122834
  currentParser = null;
122835
122835
  currentBufferRef = null;
122836
122836
  }
122837
122837
  if (ret !== constants3.ERROR.OK) {
122838
- const data = chunk.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
122838
+ const data = chunk2.subarray(llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr);
122839
122839
  if (ret === constants3.ERROR.PAUSED_UPGRADE) {
122840
122840
  this.onUpgrade(data);
122841
122841
  } else if (ret === constants3.ERROR.PAUSED) {
@@ -123434,12 +123434,12 @@ upgrade: ${upgrade}\r
123434
123434
  assert2(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
123435
123435
  let finished = false;
123436
123436
  const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
123437
- const onData = function(chunk) {
123437
+ const onData = function(chunk2) {
123438
123438
  if (finished) {
123439
123439
  return;
123440
123440
  }
123441
123441
  try {
123442
- if (!writer.write(chunk) && this.pause) {
123442
+ if (!writer.write(chunk2) && this.pause) {
123443
123443
  this.pause();
123444
123444
  }
123445
123445
  } catch (err) {
@@ -123574,11 +123574,11 @@ upgrade: ${upgrade}\r
123574
123574
  socket.on("close", onDrain).on("drain", onDrain);
123575
123575
  const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header });
123576
123576
  try {
123577
- for await (const chunk of body) {
123577
+ for await (const chunk2 of body) {
123578
123578
  if (socket[kError]) {
123579
123579
  throw socket[kError];
123580
123580
  }
123581
- if (!writer.write(chunk)) {
123581
+ if (!writer.write(chunk2)) {
123582
123582
  await waitForDrain();
123583
123583
  }
123584
123584
  }
@@ -123616,7 +123616,7 @@ upgrade: ${upgrade}\r
123616
123616
  * @param {Buffer} chunk
123617
123617
  * @returns
123618
123618
  */
123619
- write(chunk) {
123619
+ write(chunk2) {
123620
123620
  const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this;
123621
123621
  if (socket[kError]) {
123622
123622
  throw socket[kError];
@@ -123624,7 +123624,7 @@ upgrade: ${upgrade}\r
123624
123624
  if (socket.destroyed) {
123625
123625
  return false;
123626
123626
  }
123627
- const len = Buffer.byteLength(chunk);
123627
+ const len = Buffer.byteLength(chunk2);
123628
123628
  if (!len) {
123629
123629
  return true;
123630
123630
  }
@@ -123654,9 +123654,9 @@ ${len.toString(16)}\r
123654
123654
  `, "latin1");
123655
123655
  }
123656
123656
  this.bytesWritten += len;
123657
- const ret = socket.write(chunk);
123657
+ const ret = socket.write(chunk2);
123658
123658
  socket.uncork();
123659
- request.onBodySent(chunk);
123659
+ request.onBodySent(chunk2);
123660
123660
  if (!ret) {
123661
123661
  if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
123662
123662
  if (socket[kParser].timeout.refresh) {
@@ -124207,8 +124207,8 @@ var require_client_h2 = __commonJS({
124207
124207
  stream.pause();
124208
124208
  }
124209
124209
  });
124210
- stream.on("data", (chunk) => {
124211
- if (request.onData(chunk) === false) {
124210
+ stream.on("data", (chunk2) => {
124211
+ if (request.onData(chunk2) === false) {
124212
124212
  stream.pause();
124213
124213
  }
124214
124214
  });
@@ -124374,8 +124374,8 @@ var require_client_h2 = __commonJS({
124374
124374
  }
124375
124375
  );
124376
124376
  util2.addListener(pipe2, "data", onPipeData);
124377
- function onPipeData(chunk) {
124378
- request.onBodySent(chunk);
124377
+ function onPipeData(chunk2) {
124378
+ request.onBodySent(chunk2);
124379
124379
  }
124380
124380
  }
124381
124381
  async function writeBlob(abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {
@@ -124419,12 +124419,12 @@ var require_client_h2 = __commonJS({
124419
124419
  });
124420
124420
  h2stream.on("close", onDrain).on("drain", onDrain);
124421
124421
  try {
124422
- for await (const chunk of body) {
124422
+ for await (const chunk2 of body) {
124423
124423
  if (socket[kError]) {
124424
124424
  throw socket[kError];
124425
124425
  }
124426
- const res = h2stream.write(chunk);
124427
- request.onBodySent(chunk);
124426
+ const res = h2stream.write(chunk2);
124427
+ request.onBodySent(chunk2);
124428
124428
  if (!res) {
124429
124429
  await waitForDrain();
124430
124430
  }
@@ -126300,12 +126300,12 @@ var require_retry_handler = __commonJS({
126300
126300
  });
126301
126301
  }
126302
126302
  }
126303
- onResponseData(controller, chunk) {
126303
+ onResponseData(controller, chunk2) {
126304
126304
  if (this.error) {
126305
126305
  return;
126306
126306
  }
126307
- this.start += chunk.length;
126308
- this.handler.onResponseData?.(controller, chunk);
126307
+ this.start += chunk2.length;
126308
+ this.handler.onResponseData?.(controller, chunk2);
126309
126309
  }
126310
126310
  onResponseEnd(controller, trailers) {
126311
126311
  if (this.error && this.retryOpts.throwOnError) {
@@ -126560,15 +126560,15 @@ var require_readable2 = __commonJS({
126560
126560
  * @param {Buffer|null} chunk
126561
126561
  * @returns {boolean}
126562
126562
  */
126563
- push(chunk) {
126564
- if (chunk) {
126565
- this[kBytesRead] += chunk.length;
126563
+ push(chunk2) {
126564
+ if (chunk2) {
126565
+ this[kBytesRead] += chunk2.length;
126566
126566
  if (this[kConsume]) {
126567
- consumePush(this[kConsume], chunk);
126568
- return this[kReading] ? super.push(chunk) : true;
126567
+ consumePush(this[kConsume], chunk2);
126568
+ return this[kReading] ? super.push(chunk2) : true;
126569
126569
  }
126570
126570
  }
126571
- return super.push(chunk);
126571
+ return super.push(chunk2);
126572
126572
  }
126573
126573
  /**
126574
126574
  * Consumes and returns the body as a string.
@@ -126759,8 +126759,8 @@ var require_readable2 = __commonJS({
126759
126759
  consumePush(consume2, state.buffer[n]);
126760
126760
  }
126761
126761
  } else {
126762
- for (const chunk of state.buffer) {
126763
- consumePush(consume2, chunk);
126762
+ for (const chunk2 of state.buffer) {
126763
+ consumePush(consume2, chunk2);
126764
126764
  }
126765
126765
  }
126766
126766
  if (state.endEmitted) {
@@ -126797,9 +126797,9 @@ var require_readable2 = __commonJS({
126797
126797
  const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer);
126798
126798
  let offset = 0;
126799
126799
  for (let i = 0; i < chunks.length; ++i) {
126800
- const chunk = chunks[i];
126801
- buffer.set(chunk, offset);
126802
- offset += chunk.length;
126800
+ const chunk2 = chunks[i];
126801
+ buffer.set(chunk2, offset);
126802
+ offset += chunk2.length;
126803
126803
  }
126804
126804
  return buffer;
126805
126805
  }
@@ -126822,9 +126822,9 @@ var require_readable2 = __commonJS({
126822
126822
  stream.destroy(err);
126823
126823
  }
126824
126824
  }
126825
- function consumePush(consume2, chunk) {
126826
- consume2.length += chunk.length;
126827
- consume2.body.push(chunk);
126825
+ function consumePush(consume2, chunk2) {
126826
+ consume2.length += chunk2.length;
126827
+ consume2.body.push(chunk2);
126828
126828
  }
126829
126829
  function consumeFinish(consume2, err) {
126830
126830
  if (consume2.body === null) {
@@ -126969,8 +126969,8 @@ var require_api_request = __commonJS({
126969
126969
  }
126970
126970
  }
126971
126971
  }
126972
- onData(chunk) {
126973
- return this.res.push(chunk);
126972
+ onData(chunk2) {
126973
+ return this.res.push(chunk2);
126974
126974
  }
126975
126975
  onComplete(trailers) {
126976
126976
  util2.parseHeaders(trailers, this.trailers);
@@ -127185,9 +127185,9 @@ var require_api_stream = __commonJS({
127185
127185
  const needDrain = res.writableNeedDrain !== void 0 ? res.writableNeedDrain : res._writableState?.needDrain;
127186
127186
  return needDrain !== true;
127187
127187
  }
127188
- onData(chunk) {
127188
+ onData(chunk2) {
127189
127189
  const { res } = this;
127190
- return res ? res.write(chunk) : true;
127190
+ return res ? res.write(chunk2) : true;
127191
127191
  }
127192
127192
  onComplete(trailers) {
127193
127193
  const { res } = this;
@@ -127328,9 +127328,9 @@ var require_api_pipeline = __commonJS({
127328
127328
  body.resume();
127329
127329
  }
127330
127330
  },
127331
- write: (chunk, encoding, callback) => {
127331
+ write: (chunk2, encoding, callback) => {
127332
127332
  const { req } = this;
127333
- if (req.push(chunk, encoding) || req._readableState.destroyed) {
127333
+ if (req.push(chunk2, encoding) || req._readableState.destroyed) {
127334
127334
  callback();
127335
127335
  } else {
127336
127336
  req[kResume] = callback;
@@ -127395,9 +127395,9 @@ var require_api_pipeline = __commonJS({
127395
127395
  if (!body || typeof body.on !== "function") {
127396
127396
  throw new InvalidReturnValueError("expected Readable");
127397
127397
  }
127398
- body.on("data", (chunk) => {
127398
+ body.on("data", (chunk2) => {
127399
127399
  const { ret, body: body2 } = this;
127400
- if (!ret.push(chunk) && body2.pause) {
127400
+ if (!ret.push(chunk2) && body2.pause) {
127401
127401
  body2.pause();
127402
127402
  }
127403
127403
  }).on("error", (err) => {
@@ -127414,9 +127414,9 @@ var require_api_pipeline = __commonJS({
127414
127414
  });
127415
127415
  this.body = body;
127416
127416
  }
127417
- onData(chunk) {
127417
+ onData(chunk2) {
127418
127418
  const { res } = this;
127419
- return res.push(chunk);
127419
+ return res.push(chunk2);
127420
127420
  }
127421
127421
  onComplete(trailers) {
127422
127422
  const { res } = this;
@@ -128569,8 +128569,8 @@ var require_pending_interceptors_formatter = __commonJS({
128569
128569
  module.exports = class PendingInterceptorsFormatter {
128570
128570
  constructor({ disableColors } = {}) {
128571
128571
  this.transform = new Transform({
128572
- transform(chunk, _enc, cb) {
128573
- cb(null, chunk);
128572
+ transform(chunk2, _enc, cb) {
128573
+ cb(null, chunk2);
128574
128574
  }
128575
128575
  });
128576
128576
  this.logger = new Console({
@@ -128797,8 +128797,8 @@ var require_snapshot_utils = __commonJS({
128797
128797
  match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
128798
128798
  };
128799
128799
  }
128800
- var crypto5 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
128801
- var hashId = crypto5?.hash ? (value) => crypto5.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
128800
+ var crypto6 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
128801
+ var hashId = crypto6?.hash ? (value) => crypto6.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
128802
128802
  function isUndiciHeaders(headers) {
128803
128803
  return Array.isArray(headers) && (headers.length & 1) === 0;
128804
128804
  }
@@ -129364,9 +129364,9 @@ var require_snapshot_agent = __commonJS({
129364
129364
  responseData.headers = headers;
129365
129365
  return handler.onResponseStart(controller, statusCode, headers, statusMessage);
129366
129366
  },
129367
- onResponseData(controller, chunk) {
129368
- responseData.body.push(chunk);
129369
- return handler.onResponseData(controller, chunk);
129367
+ onResponseData(controller, chunk2) {
129368
+ responseData.body.push(chunk2);
129369
+ return handler.onResponseData(controller, chunk2);
129370
129370
  },
129371
129371
  onResponseEnd(controller, trailers) {
129372
129372
  responseData.trailers = trailers;
@@ -129741,10 +129741,10 @@ var require_redirect_handler = __commonJS({
129741
129741
  this.opts.origin = origin;
129742
129742
  this.opts.query = null;
129743
129743
  }
129744
- onResponseData(controller, chunk) {
129744
+ onResponseData(controller, chunk2) {
129745
129745
  if (this.location) {
129746
129746
  } else {
129747
- this.handler.onResponseData?.(controller, chunk);
129747
+ this.handler.onResponseData?.(controller, chunk2);
129748
129748
  }
129749
129749
  }
129750
129750
  onResponseEnd(controller, trailers) {
@@ -129854,11 +129854,11 @@ var require_response_error = __commonJS({
129854
129854
  this.#decoder = new TextDecoder("utf-8");
129855
129855
  }
129856
129856
  }
129857
- onResponseData(controller, chunk) {
129857
+ onResponseData(controller, chunk2) {
129858
129858
  if (this.#statusCode < 400) {
129859
- return super.onResponseData(controller, chunk);
129859
+ return super.onResponseData(controller, chunk2);
129860
129860
  }
129861
- this.#body += this.#decoder?.decode(chunk, { stream: true }) ?? "";
129861
+ this.#body += this.#decoder?.decode(chunk2, { stream: true }) ?? "";
129862
129862
  }
129863
129863
  onResponseEnd(controller, trailers) {
129864
129864
  if (this.#statusCode >= 400) {
@@ -129971,8 +129971,8 @@ var require_dump = __commonJS({
129971
129971
  err = this.#controller?.reason ?? err;
129972
129972
  super.onResponseError(controller, err);
129973
129973
  }
129974
- onResponseData(controller, chunk) {
129975
- this.#size = this.#size + chunk.length;
129974
+ onResponseData(controller, chunk2) {
129975
+ this.#size = this.#size + chunk2.length;
129976
129976
  if (this.#size >= this.#maxSize) {
129977
129977
  this.#dumped = true;
129978
129978
  if (this.aborted === true) {
@@ -130610,15 +130610,15 @@ var require_cache = __commonJS({
130610
130610
  }
130611
130611
  }
130612
130612
  }
130613
- function makeDeduplicationKey(cacheKey, excludeHeaders) {
130614
- let key = `${cacheKey.origin}:${cacheKey.method}:${cacheKey.path}`;
130615
- if (cacheKey.headers) {
130616
- const sortedHeaders = Object.keys(cacheKey.headers).sort();
130613
+ function makeDeduplicationKey(cacheKey2, excludeHeaders) {
130614
+ let key = `${cacheKey2.origin}:${cacheKey2.method}:${cacheKey2.path}`;
130615
+ if (cacheKey2.headers) {
130616
+ const sortedHeaders = Object.keys(cacheKey2.headers).sort();
130617
130617
  for (const header of sortedHeaders) {
130618
130618
  if (excludeHeaders?.has(header.toLowerCase())) {
130619
130619
  continue;
130620
130620
  }
130621
- const value = cacheKey.headers[header];
130621
+ const value = cacheKey2.headers[header];
130622
130622
  key += `:${header}=${Array.isArray(value) ? value.join(",") : value}`;
130623
130623
  }
130624
130624
  }
@@ -131196,11 +131196,11 @@ var require_cache_handler = __commonJS({
131196
131196
  * @param {import('../../types/cache-interceptor.d.ts').default.CacheKey} cacheKey
131197
131197
  * @param {import('../../types/dispatcher.d.ts').default.DispatchHandler} handler
131198
131198
  */
131199
- constructor({ store, type, cacheByDefault }, cacheKey, handler) {
131199
+ constructor({ store, type, cacheByDefault }, cacheKey2, handler) {
131200
131200
  this.#store = store;
131201
131201
  this.#cacheType = type;
131202
131202
  this.#cacheByDefault = cacheByDefault;
131203
- this.#cacheKey = cacheKey;
131203
+ this.#cacheKey = cacheKey2;
131204
131204
  this.#handler = handler;
131205
131205
  }
131206
131206
  onRequestStart(controller, context2) {
@@ -131292,9 +131292,9 @@ var require_cache_handler = __commonJS({
131292
131292
  if (typeof cachedValue.body.values === "function") {
131293
131293
  const bodyIterator = cachedValue.body.values();
131294
131294
  const streamCachedBody = () => {
131295
- for (const chunk of bodyIterator) {
131296
- const full = this.#writeStream.write(chunk) === false;
131297
- this.#handler.onResponseData?.(controller, chunk);
131295
+ for (const chunk2 of bodyIterator) {
131296
+ const full = this.#writeStream.write(chunk2) === false;
131297
+ this.#handler.onResponseData?.(controller, chunk2);
131298
131298
  if (full) {
131299
131299
  break;
131300
131300
  }
@@ -131312,9 +131312,9 @@ var require_cache_handler = __commonJS({
131312
131312
  });
131313
131313
  streamCachedBody();
131314
131314
  } else if (typeof cachedValue.body.on === "function") {
131315
- cachedValue.body.on("data", (chunk) => {
131316
- this.#writeStream.write(chunk);
131317
- this.#handler.onResponseData?.(controller, chunk);
131315
+ cachedValue.body.on("data", (chunk2) => {
131316
+ this.#writeStream.write(chunk2);
131317
+ this.#handler.onResponseData?.(controller, chunk2);
131318
131318
  }).on("end", () => {
131319
131319
  this.#writeStream.end();
131320
131320
  }).on("error", () => {
@@ -131357,11 +131357,11 @@ var require_cache_handler = __commonJS({
131357
131357
  downstreamOnHeaders();
131358
131358
  }
131359
131359
  }
131360
- onResponseData(controller, chunk) {
131361
- if (this.#writeStream?.write(chunk) === false) {
131360
+ onResponseData(controller, chunk2) {
131361
+ if (this.#writeStream?.write(chunk2) === false) {
131362
131362
  controller.pause();
131363
131363
  }
131364
- this.#handler.onResponseData?.(controller, chunk);
131364
+ this.#handler.onResponseData?.(controller, chunk2);
131365
131365
  }
131366
131366
  onResponseEnd(controller, trailers) {
131367
131367
  this.#writeStream?.end();
@@ -131602,15 +131602,15 @@ var require_memory_cache_store = __commonJS({
131602
131602
  const store = this;
131603
131603
  const entry = { ...key, ...val, body: [], size: 0 };
131604
131604
  return new Writable2({
131605
- write(chunk, encoding, callback) {
131606
- if (typeof chunk === "string") {
131607
- chunk = Buffer.from(chunk, encoding);
131605
+ write(chunk2, encoding, callback) {
131606
+ if (typeof chunk2 === "string") {
131607
+ chunk2 = Buffer.from(chunk2, encoding);
131608
131608
  }
131609
- entry.size += chunk.byteLength;
131609
+ entry.size += chunk2.byteLength;
131610
131610
  if (entry.size >= store.#maxEntrySize) {
131611
131611
  this.destroy();
131612
131612
  } else {
131613
- entry.body.push(chunk);
131613
+ entry.body.push(chunk2);
131614
131614
  }
131615
131615
  callback(null);
131616
131616
  },
@@ -131740,11 +131740,11 @@ var require_cache_revalidation_handler = __commonJS({
131740
131740
  statusMessage
131741
131741
  );
131742
131742
  }
131743
- onResponseData(controller, chunk) {
131743
+ onResponseData(controller, chunk2) {
131744
131744
  if (this.#successful) {
131745
131745
  return;
131746
131746
  }
131747
- return this.#handler.onResponseData?.(controller, chunk);
131747
+ return this.#handler.onResponseData?.(controller, chunk2);
131748
131748
  }
131749
131749
  onResponseEnd(controller, trailers) {
131750
131750
  if (this.#successful) {
@@ -131834,7 +131834,7 @@ var require_cache2 = __commonJS({
131834
131834
  const staleWhileRevalidateExpiry = result.staleAt + staleWhileRevalidate * 1e3;
131835
131835
  return now3 <= staleWhileRevalidateExpiry;
131836
131836
  }
131837
- function handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl) {
131837
+ function handleUncachedResponse(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl) {
131838
131838
  if (reqCacheControl?.["only-if-cached"]) {
131839
131839
  let aborted2 = false;
131840
131840
  try {
@@ -131862,7 +131862,7 @@ var require_cache2 = __commonJS({
131862
131862
  }
131863
131863
  return true;
131864
131864
  }
131865
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
131865
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
131866
131866
  }
131867
131867
  function sendCachedValue(handler, opts, result, age, context2, isStale2) {
131868
131868
  const stream = util2.isStream(result.body) ? result.body : Readable4.from(result.body ?? []);
@@ -131913,18 +131913,18 @@ var require_cache2 = __commonJS({
131913
131913
  if (opts.method === "HEAD") {
131914
131914
  stream.destroy();
131915
131915
  } else {
131916
- stream.on("data", function(chunk) {
131917
- handler.onResponseData?.(controller, chunk);
131916
+ stream.on("data", function(chunk2) {
131917
+ handler.onResponseData?.(controller, chunk2);
131918
131918
  });
131919
131919
  }
131920
131920
  }
131921
- function handleResult2(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl, result) {
131921
+ function handleResult2(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl, result) {
131922
131922
  if (!result) {
131923
- return handleUncachedResponse(dispatch, globalOpts, cacheKey, handler, opts, reqCacheControl);
131923
+ return handleUncachedResponse(dispatch, globalOpts, cacheKey2, handler, opts, reqCacheControl);
131924
131924
  }
131925
131925
  const now3 = Date.now();
131926
131926
  if (now3 > result.deleteAt) {
131927
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
131927
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
131928
131928
  }
131929
131929
  const age = Math.round((now3 - result.cachedAt) / 1e3);
131930
131930
  if (reqCacheControl?.["max-age"] && age >= reqCacheControl["max-age"]) {
@@ -131934,7 +131934,7 @@ var require_cache2 = __commonJS({
131934
131934
  const revalidate = needsRevalidation(result, reqCacheControl, opts);
131935
131935
  if (stale || revalidate) {
131936
131936
  if (util2.isStream(opts.body) && util2.bodyLength(opts.body) !== 0) {
131937
- return dispatch(opts, new CacheHandler(globalOpts, cacheKey, handler));
131937
+ return dispatch(opts, new CacheHandler(globalOpts, cacheKey2, handler));
131938
131938
  }
131939
131939
  if (!revalidate && withinStaleWhileRevalidateWindow(result)) {
131940
131940
  sendCachedValue(handler, opts, result, age, null, true);
@@ -131958,7 +131958,7 @@ var require_cache2 = __commonJS({
131958
131958
  ...opts,
131959
131959
  headers: headers2
131960
131960
  },
131961
- new CacheHandler(globalOpts, cacheKey, {
131961
+ new CacheHandler(globalOpts, cacheKey2, {
131962
131962
  // Silent handler that just updates the cache
131963
131963
  onRequestStart() {
131964
131964
  },
@@ -132009,7 +132009,7 @@ var require_cache2 = __commonJS({
132009
132009
  result.body.on("error", nop).destroy();
132010
132010
  }
132011
132011
  },
132012
- new CacheHandler(globalOpts, cacheKey, handler),
132012
+ new CacheHandler(globalOpts, cacheKey2, handler),
132013
132013
  withinStaleIfErrorThreshold
132014
132014
  )
132015
132015
  );
@@ -132078,13 +132078,13 @@ var require_cache2 = __commonJS({
132078
132078
  if (reqCacheControl?.["no-store"]) {
132079
132079
  return dispatch(opts2, handler);
132080
132080
  }
132081
- const cacheKey = makeCacheKey(opts2);
132082
- const result = store.get(cacheKey);
132081
+ const cacheKey2 = makeCacheKey(opts2);
132082
+ const result = store.get(cacheKey2);
132083
132083
  if (result && typeof result.then === "function") {
132084
132084
  return result.then((result2) => handleResult2(
132085
132085
  dispatch,
132086
132086
  globalOpts,
132087
- cacheKey,
132087
+ cacheKey2,
132088
132088
  handler,
132089
132089
  opts2,
132090
132090
  reqCacheControl,
@@ -132094,7 +132094,7 @@ var require_cache2 = __commonJS({
132094
132094
  return handleResult2(
132095
132095
  dispatch,
132096
132096
  globalOpts,
132097
- cacheKey,
132097
+ cacheKey2,
132098
132098
  handler,
132099
132099
  opts2,
132100
132100
  reqCacheControl,
@@ -132189,9 +132189,9 @@ var require_decompress = __commonJS({
132189
132189
  */
132190
132190
  #setupDecompressorEvents(decompressor, controller) {
132191
132191
  decompressor.on("readable", () => {
132192
- let chunk;
132193
- while ((chunk = decompressor.read()) !== null) {
132194
- const result = super.onResponseData(controller, chunk);
132192
+ let chunk2;
132193
+ while ((chunk2 = decompressor.read()) !== null) {
132194
+ const result = super.onResponseData(controller, chunk2);
132195
132195
  if (result === false) {
132196
132196
  break;
132197
132197
  }
@@ -132267,12 +132267,12 @@ var require_decompress = __commonJS({
132267
132267
  * @param {Buffer} chunk
132268
132268
  * @returns {void}
132269
132269
  */
132270
- onResponseData(controller, chunk) {
132270
+ onResponseData(controller, chunk2) {
132271
132271
  if (this.#decompressors.length > 0) {
132272
- this.#decompressors[0].write(chunk);
132272
+ this.#decompressors[0].write(chunk2);
132273
132273
  return;
132274
132274
  }
132275
- super.onResponseData(controller, chunk);
132275
+ super.onResponseData(controller, chunk2);
132276
132276
  }
132277
132277
  /**
132278
132278
  * @param {Controller} controller
@@ -132410,9 +132410,9 @@ var require_deduplication_handler = __commonJS({
132410
132410
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
132411
132411
  * @param {Buffer} chunk
132412
132412
  */
132413
- onResponseData(controller, chunk) {
132414
- this.#chunks.push(Buffer.from(chunk));
132415
- this.#primaryHandler.onResponseData?.(controller, chunk);
132413
+ onResponseData(controller, chunk2) {
132414
+ this.#chunks.push(Buffer.from(chunk2));
132415
+ this.#primaryHandler.onResponseData?.(controller, chunk2);
132416
132416
  }
132417
132417
  /**
132418
132418
  * @param {import('../../types/dispatcher.d.ts').default.DispatchController} controller
@@ -132568,8 +132568,8 @@ var require_deduplicate = __commonJS({
132568
132568
  }
132569
132569
  }
132570
132570
  }
132571
- const cacheKey = makeCacheKey(opts2);
132572
- const dedupeKey = makeDeduplicationKey(cacheKey, excludeHeaderNamesSet);
132571
+ const cacheKey2 = makeCacheKey(opts2);
132572
+ const dedupeKey = makeDeduplicationKey(cacheKey2, excludeHeaderNamesSet);
132573
132573
  const pendingHandler = pendingRequests.get(dedupeKey);
132574
132574
  if (pendingHandler) {
132575
132575
  pendingHandler.addWaitingHandler(handler);
@@ -132845,10 +132845,10 @@ var require_sqlite_cache_store = __commonJS({
132845
132845
  const store = this;
132846
132846
  return new Writable2({
132847
132847
  decodeStrings: true,
132848
- write(chunk, encoding, callback) {
132849
- size += chunk.byteLength;
132848
+ write(chunk2, encoding, callback) {
132849
+ size += chunk2.byteLength;
132850
132850
  if (size < store.#maxEntrySize) {
132851
- body.push(chunk);
132851
+ body.push(chunk2);
132852
132852
  } else {
132853
132853
  this.destroy();
132854
132854
  }
@@ -134600,10 +134600,10 @@ var require_subresource_integrity = __commonJS({
134600
134600
  var assert2 = __require("node:assert");
134601
134601
  var { runtimeFeatures } = require_runtime_features();
134602
134602
  var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
134603
- var crypto5;
134603
+ var crypto6;
134604
134604
  if (runtimeFeatures.has("crypto")) {
134605
- crypto5 = __require("node:crypto");
134606
- const cryptoHashes = crypto5.getHashes();
134605
+ crypto6 = __require("node:crypto");
134606
+ const cryptoHashes = crypto6.getHashes();
134607
134607
  if (cryptoHashes.length === 0) {
134608
134608
  validSRIHashAlgorithmTokenSet.clear();
134609
134609
  }
@@ -134693,7 +134693,7 @@ var require_subresource_integrity = __commonJS({
134693
134693
  return result;
134694
134694
  }
134695
134695
  var applyAlgorithmToBytes = (algorithm, bytes) => {
134696
- return crypto5.hash(algorithm, bytes, "base64");
134696
+ return crypto6.hash(algorithm, bytes, "base64");
134697
134697
  };
134698
134698
  function caseSensitiveMatch(actualValue, expectedValue) {
134699
134699
  let actualValueLength = actualValue.length;
@@ -135773,11 +135773,11 @@ var require_fetch2 = __commonJS({
135773
135773
  });
135774
135774
  return true;
135775
135775
  },
135776
- onData(chunk) {
135776
+ onData(chunk2) {
135777
135777
  if (fetchParams.controller.dump) {
135778
135778
  return;
135779
135779
  }
135780
- const bytes = chunk;
135780
+ const bytes = chunk2;
135781
135781
  timingInfo.encodedBodySize += bytes.byteLength;
135782
135782
  return this.body.push(bytes);
135783
135783
  },
@@ -137614,7 +137614,7 @@ var require_connection = __commonJS({
137614
137614
  var { WebsocketFrameSend } = require_frame();
137615
137615
  var assert2 = __require("node:assert");
137616
137616
  var { runtimeFeatures } = require_runtime_features();
137617
- var crypto5 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
137617
+ var crypto6 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
137618
137618
  var warningEmitted = false;
137619
137619
  function establishWebSocketConnection(url2, protocols, client, handler, options) {
137620
137620
  const requestURL = url2;
@@ -137634,7 +137634,7 @@ var require_connection = __commonJS({
137634
137634
  const headersList = getHeadersList(new Headers4(options.headers));
137635
137635
  request.headersList = headersList;
137636
137636
  }
137637
- const keyValue = crypto5.randomBytes(16).toString("base64");
137637
+ const keyValue = crypto6.randomBytes(16).toString("base64");
137638
137638
  request.headersList.append("sec-websocket-key", keyValue, true);
137639
137639
  request.headersList.append("sec-websocket-version", "13", true);
137640
137640
  for (const protocol of protocols) {
@@ -137674,7 +137674,7 @@ var require_connection = __commonJS({
137674
137674
  return;
137675
137675
  }
137676
137676
  const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
137677
- const digest = crypto5.hash("sha1", keyValue + uid, "base64");
137677
+ const digest = crypto6.hash("sha1", keyValue + uid, "base64");
137678
137678
  if (secWSAccept !== digest) {
137679
137679
  failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
137680
137680
  return;
@@ -137774,7 +137774,7 @@ var require_permessage_deflate2 = __commonJS({
137774
137774
  this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover");
137775
137775
  this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits");
137776
137776
  }
137777
- decompress(chunk, fin, callback) {
137777
+ decompress(chunk2, fin, callback) {
137778
137778
  if (!this.#inflate) {
137779
137779
  let windowBits = Z_DEFAULT_WINDOWBITS;
137780
137780
  if (this.#options.serverMaxWindowBits) {
@@ -137796,7 +137796,7 @@ var require_permessage_deflate2 = __commonJS({
137796
137796
  callback(err);
137797
137797
  });
137798
137798
  }
137799
- this.#inflate.write(chunk);
137799
+ this.#inflate.write(chunk2);
137800
137800
  if (fin) {
137801
137801
  this.#inflate.write(tail);
137802
137802
  }
@@ -137855,9 +137855,9 @@ var require_receiver2 = __commonJS({
137855
137855
  * @param {Buffer} chunk
137856
137856
  * @param {() => void} callback
137857
137857
  */
137858
- _write(chunk, _3, callback) {
137859
- this.#buffers.push(chunk);
137860
- this.#byteOffset += chunk.length;
137858
+ _write(chunk2, _3, callback) {
137859
+ this.#buffers.push(chunk2);
137860
+ this.#byteOffset += chunk2.length;
137861
137861
  this.#loop = true;
137862
137862
  this.run(callback);
137863
137863
  }
@@ -138257,8 +138257,8 @@ var require_websocket3 = __commonJS({
138257
138257
  onMessage: (opcode, data) => this.#onMessage(opcode, data),
138258
138258
  onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
138259
138259
  onParserDrain: () => this.#onParserDrain(),
138260
- onSocketData: (chunk) => {
138261
- if (!this.#parser.write(chunk)) {
138260
+ onSocketData: (chunk2) => {
138261
+ if (!this.#parser.write(chunk2)) {
138262
138262
  this.#handler.socket.pause();
138263
138263
  }
138264
138264
  },
@@ -138810,8 +138810,8 @@ var require_websocketstream = __commonJS({
138810
138810
  onMessage: (opcode, data) => this.#onMessage(opcode, data),
138811
138811
  onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message),
138812
138812
  onParserDrain: () => this.#handler.socket.resume(),
138813
- onSocketData: (chunk) => {
138814
- if (!this.#parser.write(chunk)) {
138813
+ onSocketData: (chunk2) => {
138814
+ if (!this.#parser.write(chunk2)) {
138815
138815
  this.#handler.socket.pause();
138816
138816
  }
138817
138817
  },
@@ -138906,18 +138906,18 @@ var require_websocketstream = __commonJS({
138906
138906
  const reason = closeInfo.reason;
138907
138907
  closeWebSocketConnection(this.#handler, code, reason, true);
138908
138908
  }
138909
- #write(chunk) {
138910
- chunk = webidl.converters.WebSocketStreamWrite(chunk);
138909
+ #write(chunk2) {
138910
+ chunk2 = webidl.converters.WebSocketStreamWrite(chunk2);
138911
138911
  const promise2 = createDeferredPromise();
138912
138912
  let data = null;
138913
138913
  let opcode = null;
138914
- if (webidl.is.BufferSource(chunk)) {
138915
- data = new Uint8Array(ArrayBuffer.isView(chunk) ? new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength) : chunk.slice());
138914
+ if (webidl.is.BufferSource(chunk2)) {
138915
+ data = new Uint8Array(ArrayBuffer.isView(chunk2) ? new Uint8Array(chunk2.buffer, chunk2.byteOffset, chunk2.byteLength) : chunk2.slice());
138916
138916
  opcode = opcodes.BINARY;
138917
138917
  } else {
138918
138918
  let string4;
138919
138919
  try {
138920
- string4 = webidl.converters.DOMString(chunk);
138920
+ string4 = webidl.converters.DOMString(chunk2);
138921
138921
  } catch (e) {
138922
138922
  promise2.reject(e);
138923
138923
  return promise2.promise;
@@ -138948,15 +138948,15 @@ var require_websocketstream = __commonJS({
138948
138948
  this.#readableStreamController = controller;
138949
138949
  },
138950
138950
  pull(controller) {
138951
- let chunk;
138952
- while (controller.desiredSize > 0 && (chunk = response.socket.read()) !== null) {
138953
- controller.enqueue(chunk);
138951
+ let chunk2;
138952
+ while (controller.desiredSize > 0 && (chunk2 = response.socket.read()) !== null) {
138953
+ controller.enqueue(chunk2);
138954
138954
  }
138955
138955
  },
138956
138956
  cancel: (reason) => this.#cancel(reason)
138957
138957
  });
138958
138958
  const writable = new WritableStream({
138959
- write: (chunk) => this.#write(chunk),
138959
+ write: (chunk2) => this.#write(chunk2),
138960
138960
  close: () => closeWebSocketConnection(this.#handler, null, null),
138961
138961
  abort: (reason) => this.#closeUsingReason(reason)
138962
138962
  });
@@ -138974,18 +138974,18 @@ var require_websocketstream = __commonJS({
138974
138974
  if (this.#handler.readyState !== states.OPEN) {
138975
138975
  return;
138976
138976
  }
138977
- let chunk;
138977
+ let chunk2;
138978
138978
  if (type === opcodes.TEXT) {
138979
138979
  try {
138980
- chunk = utf8Decode(data);
138980
+ chunk2 = utf8Decode(data);
138981
138981
  } catch {
138982
138982
  failWebsocketConnection(this.#handler, "Received invalid UTF-8 in text frame.");
138983
138983
  return;
138984
138984
  }
138985
138985
  } else if (type === opcodes.BINARY) {
138986
- chunk = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
138986
+ chunk2 = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
138987
138987
  }
138988
- this.#readableStreamController.enqueue(chunk);
138988
+ this.#readableStreamController.enqueue(chunk2);
138989
138989
  }
138990
138990
  /** @type {import('../websocket').Handler['onSocketClose']} */
138991
138991
  #onSocketClose() {
@@ -139159,15 +139159,15 @@ var require_eventsource_stream = __commonJS({
139159
139159
  * @param {Function} callback
139160
139160
  * @returns {void}
139161
139161
  */
139162
- _transform(chunk, _encoding, callback) {
139163
- if (chunk.length === 0) {
139162
+ _transform(chunk2, _encoding, callback) {
139163
+ if (chunk2.length === 0) {
139164
139164
  callback();
139165
139165
  return;
139166
139166
  }
139167
139167
  if (this.buffer) {
139168
- this.buffer = Buffer.concat([this.buffer, chunk]);
139168
+ this.buffer = Buffer.concat([this.buffer, chunk2]);
139169
139169
  } else {
139170
- this.buffer = chunk;
139170
+ this.buffer = chunk2;
139171
139171
  }
139172
139172
  if (this.checkBOM) {
139173
139173
  switch (this.buffer.length) {
@@ -139878,9 +139878,9 @@ var require_helpers = __commonJS({
139878
139878
  async function toBuffer(stream) {
139879
139879
  let length = 0;
139880
139880
  const chunks = [];
139881
- for await (const chunk of stream) {
139882
- length += chunk.length;
139883
- chunks.push(chunk);
139881
+ for await (const chunk2 of stream) {
139882
+ length += chunk2.length;
139883
+ chunks.push(chunk2);
139884
139884
  }
139885
139885
  return Buffer.concat(chunks, length);
139886
139886
  }
@@ -145878,8 +145878,8 @@ function getFromCache(kid) {
145878
145878
  function getCacheValues() {
145879
145879
  return Object.values(cache);
145880
145880
  }
145881
- function setInCache(cacheKey, jwk, shouldExpire = true) {
145882
- cache[cacheKey] = jwk;
145881
+ function setInCache(cacheKey2, jwk, shouldExpire = true) {
145882
+ cache[cacheKey2] = jwk;
145883
145883
  lastUpdatedAt = shouldExpire ? Date.now() : -1;
145884
145884
  }
145885
145885
  function loadClerkJwkFromPem(params) {
@@ -152317,16 +152317,16 @@ var require_split2 = __commonJS({
152317
152317
  var { StringDecoder } = __require("string_decoder");
152318
152318
  var kLast = /* @__PURE__ */ Symbol("last");
152319
152319
  var kDecoder = /* @__PURE__ */ Symbol("decoder");
152320
- function transform2(chunk, enc, cb) {
152320
+ function transform2(chunk2, enc, cb) {
152321
152321
  let list;
152322
152322
  if (this.overflow) {
152323
- const buf = this[kDecoder].write(chunk);
152323
+ const buf = this[kDecoder].write(chunk2);
152324
152324
  list = buf.split(this.matcher);
152325
152325
  if (list.length === 1) return cb();
152326
152326
  list.shift();
152327
152327
  this.overflow = false;
152328
152328
  } else {
152329
- this[kLast] += this[kDecoder].write(chunk);
152329
+ this[kLast] += this[kDecoder].write(chunk2);
152330
152330
  list = this[kLast].split(this.matcher);
152331
152331
  }
152332
152332
  this[kLast] = list.pop();
@@ -154326,8 +154326,8 @@ var require_pino_pretty = __commonJS({
154326
154326
  const stream = new Transform({
154327
154327
  objectMode: true,
154328
154328
  autoDestroy: true,
154329
- transform(chunk, enc, cb) {
154330
- const line = pretty3(chunk);
154329
+ transform(chunk2, enc, cb) {
154330
+ const line = pretty3(chunk2);
154331
154331
  cb(null, line);
154332
154332
  }
154333
154333
  });
@@ -184842,7 +184842,7 @@ var SqliteDialect = class {
184842
184842
  // src/storage/sqlite.ts
184843
184843
  import { mkdir } from "fs/promises";
184844
184844
  import path4 from "path";
184845
- import crypto4 from "crypto";
184845
+ import crypto5 from "crypto";
184846
184846
 
184847
184847
  // src/storage/dialect.ts
184848
184848
  var fromDbBool = (v2) => v2 === 1 || v2 === true;
@@ -202550,6 +202550,164 @@ var createProjectChatRepos = (kdb) => ({
202550
202550
  }
202551
202551
  });
202552
202552
 
202553
+ // src/storage/repositories/workspace-registry.ts
202554
+ import crypto4 from "crypto";
202555
+ var mapWorkspace = (row) => ({
202556
+ id: row.id,
202557
+ project_id: row.project_id,
202558
+ branch: row.branch,
202559
+ status: row.status,
202560
+ error: row.error,
202561
+ created_at: row.created_at,
202562
+ updated_at: row.updated_at
202563
+ });
202564
+ var mapCheckout = (row) => ({
202565
+ id: row.id,
202566
+ workspace_id: row.workspace_id,
202567
+ target_id: row.target_id,
202568
+ worktree_path: row.worktree_path,
202569
+ expected_branch: row.expected_branch,
202570
+ status: row.status,
202571
+ error: row.error,
202572
+ created_at: row.created_at,
202573
+ updated_at: row.updated_at
202574
+ });
202575
+ async function recomputeWorkspace(db, workspaceId, h) {
202576
+ const rows = await db.selectFrom("workspace_checkouts").select(["status", "error"]).where("workspace_id", "=", workspaceId).execute();
202577
+ if (rows.length === 0) return;
202578
+ const statuses = new Set(rows.map((row) => row.status));
202579
+ const status = statuses.has("ready") ? "ready" : statuses.has("creating") ? "creating" : statuses.has("deleting") ? "deleting" : "error";
202580
+ const error48 = status === "error" ? rows.map((row) => row.error).find((value) => Boolean(value)) ?? "Checkout failed" : null;
202581
+ await db.updateTable("workspaces").set({ status, error: error48, updated_at: h.nowMs() }).where("id", "=", workspaceId).execute();
202582
+ }
202583
+ async function upsertCheckout(trx, h, opts) {
202584
+ const now3 = h.nowMs();
202585
+ let workspaceRow = await trx.selectFrom("workspaces").selectAll().where("project_id", "=", opts.projectId).where("branch", "=", opts.branch).executeTakeFirst();
202586
+ if (!workspaceRow) {
202587
+ const workspaceId = crypto4.randomUUID();
202588
+ await trx.insertInto("workspaces").values({
202589
+ id: workspaceId,
202590
+ project_id: opts.projectId,
202591
+ branch: opts.branch,
202592
+ status: opts.status,
202593
+ error: null,
202594
+ created_at: now3,
202595
+ updated_at: now3
202596
+ }).execute();
202597
+ workspaceRow = await trx.selectFrom("workspaces").selectAll().where("id", "=", workspaceId).executeTakeFirstOrThrow();
202598
+ }
202599
+ const checkoutId = crypto4.randomUUID();
202600
+ await trx.insertInto("workspace_checkouts").values({
202601
+ id: checkoutId,
202602
+ workspace_id: workspaceRow.id,
202603
+ target_id: opts.targetId,
202604
+ worktree_path: opts.worktreePath,
202605
+ expected_branch: opts.expectedBranch,
202606
+ status: opts.status,
202607
+ error: null,
202608
+ created_at: now3,
202609
+ updated_at: now3
202610
+ }).onConflict((oc) => oc.columns(["workspace_id", "target_id"]).doUpdateSet({
202611
+ worktree_path: opts.worktreePath,
202612
+ expected_branch: opts.expectedBranch,
202613
+ status: opts.status,
202614
+ error: null,
202615
+ updated_at: now3
202616
+ })).execute();
202617
+ await recomputeWorkspace(trx, workspaceRow.id, h);
202618
+ const [workspace, checkout] = await Promise.all([
202619
+ trx.selectFrom("workspaces").selectAll().where("id", "=", workspaceRow.id).executeTakeFirstOrThrow(),
202620
+ trx.selectFrom("workspace_checkouts").selectAll().where("workspace_id", "=", workspaceRow.id).where("target_id", "=", opts.targetId).executeTakeFirstOrThrow()
202621
+ ]);
202622
+ return { workspace: mapWorkspace(workspace), checkout: mapCheckout(checkout) };
202623
+ }
202624
+ var createWorkspaceRegistryRepo = (kdb, h) => ({
202625
+ workspaceRegistry: {
202626
+ beginCheckout: (opts) => kdb.transaction().execute((trx) => upsertCheckout(trx, h, { ...opts, status: "creating" })),
202627
+ registerReadyCheckout: (opts) => kdb.transaction().execute((trx) => upsertCheckout(trx, h, { ...opts, status: "ready" })),
202628
+ setCheckoutStatus: async (workspaceId, targetId, status, error48 = null) => {
202629
+ await kdb.transaction().execute(async (trx) => {
202630
+ await trx.updateTable("workspace_checkouts").set({ status, error: error48, updated_at: h.nowMs() }).where("workspace_id", "=", workspaceId).where("target_id", "=", targetId).execute();
202631
+ await recomputeWorkspace(trx, workspaceId, h);
202632
+ });
202633
+ },
202634
+ setCheckoutStatusIfCurrent: async (workspaceId, targetId, expected, status, error48 = null) => kdb.transaction().execute(async (trx) => {
202635
+ const result = await trx.updateTable("workspace_checkouts").set({ status, error: error48, updated_at: h.nowMs() }).where("workspace_id", "=", workspaceId).where("target_id", "=", targetId).where("status", "=", expected.status).where("updated_at", "=", expected.updatedAt).executeTakeFirst();
202636
+ const changed = result.numUpdatedRows > 0n;
202637
+ if (changed) await recomputeWorkspace(trx, workspaceId, h);
202638
+ return changed;
202639
+ }),
202640
+ listByProject: async (projectId, targetId) => {
202641
+ let query = kdb.selectFrom("workspaces as workspace").innerJoin("workspace_checkouts as checkout", "checkout.workspace_id", "workspace.id").selectAll("workspace").select([
202642
+ "checkout.id as checkout_id",
202643
+ "checkout.workspace_id as checkout_workspace_id",
202644
+ "checkout.target_id as checkout_target_id",
202645
+ "checkout.worktree_path as checkout_worktree_path",
202646
+ "checkout.expected_branch as checkout_expected_branch",
202647
+ "checkout.status as checkout_status",
202648
+ "checkout.error as checkout_error",
202649
+ "checkout.created_at as checkout_created_at",
202650
+ "checkout.updated_at as checkout_updated_at"
202651
+ ]).where("workspace.project_id", "=", projectId);
202652
+ if (targetId) query = query.where("checkout.target_id", "=", targetId);
202653
+ const rows = await query.orderBy("workspace.created_at", "asc").execute();
202654
+ return rows.map((row) => ({
202655
+ workspace: mapWorkspace(row),
202656
+ checkout: {
202657
+ id: row.checkout_id,
202658
+ workspace_id: row.checkout_workspace_id,
202659
+ target_id: row.checkout_target_id,
202660
+ worktree_path: row.checkout_worktree_path,
202661
+ expected_branch: row.checkout_expected_branch,
202662
+ status: row.checkout_status,
202663
+ error: row.checkout_error,
202664
+ created_at: row.checkout_created_at,
202665
+ updated_at: row.checkout_updated_at
202666
+ }
202667
+ }));
202668
+ },
202669
+ getByProjectBranch: async (projectId, branch, targetId) => {
202670
+ const rows = await kdb.selectFrom("workspaces as workspace").innerJoin("workspace_checkouts as checkout", "checkout.workspace_id", "workspace.id").selectAll("workspace").select([
202671
+ "checkout.id as checkout_id",
202672
+ "checkout.workspace_id as checkout_workspace_id",
202673
+ "checkout.target_id as checkout_target_id",
202674
+ "checkout.worktree_path as checkout_worktree_path",
202675
+ "checkout.expected_branch as checkout_expected_branch",
202676
+ "checkout.status as checkout_status",
202677
+ "checkout.error as checkout_error",
202678
+ "checkout.created_at as checkout_created_at",
202679
+ "checkout.updated_at as checkout_updated_at"
202680
+ ]).where("workspace.project_id", "=", projectId).where("workspace.branch", "=", branch).where("checkout.target_id", "=", targetId).executeTakeFirst();
202681
+ if (!rows) return void 0;
202682
+ return {
202683
+ workspace: mapWorkspace(rows),
202684
+ checkout: {
202685
+ id: rows.checkout_id,
202686
+ workspace_id: rows.checkout_workspace_id,
202687
+ target_id: rows.checkout_target_id,
202688
+ worktree_path: rows.checkout_worktree_path,
202689
+ expected_branch: rows.checkout_expected_branch,
202690
+ status: rows.checkout_status,
202691
+ error: rows.checkout_error,
202692
+ created_at: rows.checkout_created_at,
202693
+ updated_at: rows.checkout_updated_at
202694
+ }
202695
+ };
202696
+ },
202697
+ removeCheckout: async (workspaceId, targetId) => {
202698
+ await kdb.transaction().execute(async (trx) => {
202699
+ await trx.deleteFrom("workspace_checkouts").where("workspace_id", "=", workspaceId).where("target_id", "=", targetId).execute();
202700
+ const remaining = await trx.selectFrom("workspace_checkouts").select("id").where("workspace_id", "=", workspaceId).limit(1).executeTakeFirst();
202701
+ if (!remaining) {
202702
+ await trx.deleteFrom("workspaces").where("id", "=", workspaceId).execute();
202703
+ } else {
202704
+ await recomputeWorkspace(trx, workspaceId, h);
202705
+ }
202706
+ });
202707
+ }
202708
+ }
202709
+ });
202710
+
202553
202711
  // src/storage/sqlite.ts
202554
202712
  var createDatabase = (dbPath) => {
202555
202713
  const db = new Database(dbPath);
@@ -202569,6 +202727,37 @@ var createDatabase = (dbPath) => {
202569
202727
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
202570
202728
  );
202571
202729
 
202730
+ CREATE TABLE IF NOT EXISTS workspaces (
202731
+ id TEXT PRIMARY KEY,
202732
+ project_id TEXT NOT NULL,
202733
+ branch TEXT NOT NULL DEFAULT '',
202734
+ status TEXT NOT NULL CHECK (status IN ('creating', 'ready', 'deleting', 'error')),
202735
+ error TEXT,
202736
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
202737
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
202738
+ UNIQUE(project_id, branch),
202739
+ FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
202740
+ );
202741
+
202742
+ CREATE TABLE IF NOT EXISTS workspace_checkouts (
202743
+ id TEXT PRIMARY KEY,
202744
+ workspace_id TEXT NOT NULL,
202745
+ target_id TEXT NOT NULL,
202746
+ worktree_path TEXT NOT NULL,
202747
+ expected_branch TEXT NOT NULL,
202748
+ status TEXT NOT NULL CHECK (status IN ('creating', 'ready', 'deleting', 'error')),
202749
+ error TEXT,
202750
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
202751
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
202752
+ UNIQUE(workspace_id, target_id),
202753
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE
202754
+ );
202755
+
202756
+ CREATE INDEX IF NOT EXISTS idx_workspaces_project_status
202757
+ ON workspaces(project_id, status, branch);
202758
+ CREATE INDEX IF NOT EXISTS idx_workspace_checkouts_workspace_status
202759
+ ON workspace_checkouts(workspace_id, status, target_id);
202760
+
202572
202761
  CREATE TABLE IF NOT EXISTS project_chat_threads (
202573
202762
  id TEXT PRIMARY KEY,
202574
202763
  project_id TEXT NOT NULL,
@@ -202873,6 +203062,34 @@ var createDatabase = (dbPath) => {
202873
203062
 
202874
203063
  CREATE INDEX IF NOT EXISTS idx_cross_remote_audit_target ON cross_remote_audit(target_remote_id, seq);
202875
203064
  `);
203065
+ const workspaceCheckoutsTable = db.prepare(
203066
+ "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'workspace_checkouts'"
203067
+ ).get();
203068
+ if (/UNIQUE\s*\(\s*target_id\s*,\s*worktree_path\s*\)/i.test(workspaceCheckoutsTable?.sql ?? "")) {
203069
+ db.transaction(() => db.exec(`
203070
+ ALTER TABLE workspace_checkouts RENAME TO workspace_checkouts_global_path_unique;
203071
+ CREATE TABLE workspace_checkouts (
203072
+ id TEXT PRIMARY KEY,
203073
+ workspace_id TEXT NOT NULL,
203074
+ target_id TEXT NOT NULL,
203075
+ worktree_path TEXT NOT NULL,
203076
+ expected_branch TEXT NOT NULL,
203077
+ status TEXT NOT NULL CHECK (status IN ('creating', 'ready', 'deleting', 'error')),
203078
+ error TEXT,
203079
+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
203080
+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%d %H:%M:%f', 'now')),
203081
+ UNIQUE(workspace_id, target_id),
203082
+ FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE
203083
+ );
203084
+ INSERT INTO workspace_checkouts
203085
+ (id, workspace_id, target_id, worktree_path, expected_branch, status, error, created_at, updated_at)
203086
+ SELECT id, workspace_id, target_id, worktree_path, expected_branch, status, error, created_at, updated_at
203087
+ FROM workspace_checkouts_global_path_unique;
203088
+ DROP TABLE workspace_checkouts_global_path_unique;
203089
+ CREATE INDEX idx_workspace_checkouts_workspace_status
203090
+ ON workspace_checkouts(workspace_id, status, target_id);
203091
+ `))();
203092
+ }
202876
203093
  const instructionDeliveryCols = db.prepare("PRAGMA table_info(agent_instruction_deliveries)").all();
202877
203094
  if (!instructionDeliveryCols.some((c) => c.name === "owner_token")) {
202878
203095
  db.exec("ALTER TABLE agent_instruction_deliveries ADD COLUMN owner_token TEXT");
@@ -203209,7 +203426,7 @@ var createDatabase = (dbPath) => {
203209
203426
  } catch {
203210
203427
  name25 = row.remote_url;
203211
203428
  }
203212
- const id = crypto4.randomUUID();
203429
+ const id = crypto5.randomUUID();
203213
203430
  db.prepare(
203214
203431
  `INSERT INTO remote_servers (id, name, url, api_key, created_at, updated_at) VALUES (?, ?, ?, ?, datetime('now'), datetime('now'))`
203215
203432
  ).run(id, name25, row.remote_url, row.remote_api_key);
@@ -203227,7 +203444,7 @@ var createDatabase = (dbPath) => {
203227
203444
  if (!existingLink && proj.remote_path) {
203228
203445
  db.prepare(
203229
203446
  `INSERT INTO project_remotes (id, project_id, remote_server_id, remote_path, sort_order, sync_up_config, sync_down_config) VALUES (?, ?, ?, ?, 0, ?, ?)`
203230
- ).run(crypto4.randomUUID(), proj.id, server.id, proj.remote_path, proj.sync_up_config, proj.sync_down_config);
203447
+ ).run(crypto5.randomUUID(), proj.id, server.id, proj.remote_path, proj.sync_up_config, proj.sync_down_config);
203231
203448
  }
203232
203449
  if (proj.agent_mode === "remote") {
203233
203450
  db.prepare(`UPDATE projects SET agent_mode = ? WHERE id = ?`).run(server.id, proj.id);
@@ -203896,6 +204113,7 @@ var createSqliteStorage = async (dbPath) => {
203896
204113
  const h = sqliteHelpers;
203897
204114
  return {
203898
204115
  ...createCoreRepos(kdb, h),
204116
+ ...createWorkspaceRegistryRepo(kdb, h),
203899
204117
  ...createRemoteServerRepos(kdb, h),
203900
204118
  ...createExecutorRepos(kdb, h),
203901
204119
  ...createScheduledRepos(kdb, h),
@@ -206163,16 +206381,88 @@ function resolveWorktreePath(projectPath, branch) {
206163
206381
  function getWorktreeBaseForProject(projectPath) {
206164
206382
  return path6.join(WORKTREE_BASE_DIR, getProjectIdentifier(projectPath));
206165
206383
  }
206166
- function getWorktreeBranches(projectPath) {
206167
- const entries = parseGitWorktreeList(projectPath);
206168
- const worktrees = [{ branch: null }];
206384
+ function conventionalWorktreePath(projectPath, branch) {
206385
+ return path6.join(getWorktreeBaseForProject(projectPath), branch.replace(/\//g, "-"));
206386
+ }
206387
+ function reconcileWorktreeBranches(projectPath, entries, sessionBranches = [], registry2 = []) {
206388
+ const registryByPath = /* @__PURE__ */ new Map();
206389
+ for (const anchor of registry2) registryByPath.set(path6.resolve(anchor.worktreePath), anchor);
206390
+ const stableBranchByPath = /* @__PURE__ */ new Map();
206391
+ for (const branch of sessionBranches) {
206392
+ if (!branch) continue;
206393
+ stableBranchByPath.set(path6.resolve(conventionalWorktreePath(projectPath, branch)), branch);
206394
+ }
206395
+ const rootEntry = entries[0];
206396
+ const rootAnchor = rootEntry ? registryByPath.get(path6.resolve(rootEntry.path)) : void 0;
206397
+ const worktrees = [rootAnchor && rootEntry?.branch !== rootAnchor.expectedBranch ? { branch: null, currentBranch: rootEntry?.branch ?? null } : { branch: null }];
206169
206398
  for (let i = 1; i < entries.length; i++) {
206170
- if (entries[i].branch) {
206171
- worktrees.push({ branch: entries[i].branch });
206399
+ const entry = entries[i];
206400
+ const anchor = registryByPath.get(path6.resolve(entry.path));
206401
+ const stableBranch = anchor?.branch || stableBranchByPath.get(path6.resolve(entry.path));
206402
+ if (stableBranch) {
206403
+ const expectedBranch = anchor?.expectedBranch ?? stableBranch;
206404
+ worktrees.push(entry.branch === expectedBranch ? { branch: stableBranch } : { branch: stableBranch, currentBranch: entry.branch });
206405
+ } else if (entry.branch) {
206406
+ worktrees.push({ branch: entry.branch });
206172
206407
  }
206173
206408
  }
206174
206409
  return worktrees;
206175
206410
  }
206411
+ async function getRegisteredWorktreeBranches(storage, projectId, projectPath) {
206412
+ const entries = parseGitWorktreeList(projectPath);
206413
+ const sessions = await storage.agentSessions.getByProjectId(projectId);
206414
+ const sessionBranches = sessions.map((session) => session.branch);
206415
+ const sessionBranchByPath = /* @__PURE__ */ new Map();
206416
+ for (const branch of sessionBranches) {
206417
+ if (branch) sessionBranchByPath.set(path6.resolve(conventionalWorktreePath(projectPath, branch)), branch);
206418
+ }
206419
+ let registered = await storage.workspaceRegistry.listByProject(projectId, "local");
206420
+ const livePaths = new Set(entries.map((entry) => path6.resolve(entry.path)));
206421
+ for (const row of registered) {
206422
+ if (livePaths.has(path6.resolve(row.checkout.worktree_path))) continue;
206423
+ if (row.checkout.status === "deleting") {
206424
+ await storage.workspaceRegistry.removeCheckout(row.workspace.id, "local");
206425
+ } else if (row.checkout.status !== "error" || row.checkout.error !== "Worktree is missing") {
206426
+ await storage.workspaceRegistry.setCheckoutStatusIfCurrent(
206427
+ row.workspace.id,
206428
+ "local",
206429
+ { status: row.checkout.status, updatedAt: row.checkout.updated_at },
206430
+ "error",
206431
+ "Worktree is missing"
206432
+ );
206433
+ }
206434
+ }
206435
+ registered = await storage.workspaceRegistry.listByProject(projectId, "local");
206436
+ const registeredPaths = new Set(registered.map((row) => path6.resolve(row.checkout.worktree_path)));
206437
+ for (let index = 0; index < entries.length; index++) {
206438
+ const entry = entries[index];
206439
+ const resolvedPath = path6.resolve(entry.path);
206440
+ const existing = registered.find((row) => path6.resolve(row.checkout.worktree_path) === resolvedPath);
206441
+ if (existing) {
206442
+ if (existing.checkout.status === "creating" || existing.checkout.status === "error") {
206443
+ await storage.workspaceRegistry.setCheckoutStatus(existing.workspace.id, "local", "ready");
206444
+ }
206445
+ continue;
206446
+ }
206447
+ if (registeredPaths.has(resolvedPath) || entry.branch === null) continue;
206448
+ const stableBranch = index === 0 ? "" : sessionBranchByPath.get(resolvedPath) ?? entry.branch;
206449
+ await storage.workspaceRegistry.registerReadyCheckout({
206450
+ projectId,
206451
+ branch: stableBranch,
206452
+ targetId: "local",
206453
+ worktreePath: entry.path,
206454
+ expectedBranch: index === 0 ? entry.branch : stableBranch
206455
+ });
206456
+ registeredPaths.add(resolvedPath);
206457
+ }
206458
+ registered = await storage.workspaceRegistry.listByProject(projectId, "local");
206459
+ const anchors = registered.map((row) => ({
206460
+ branch: row.workspace.branch,
206461
+ worktreePath: row.checkout.worktree_path,
206462
+ expectedBranch: row.checkout.expected_branch
206463
+ }));
206464
+ return reconcileWorktreeBranches(projectPath, entries, sessionBranches, anchors);
206465
+ }
206176
206466
 
206177
206467
  // ../../node_modules/.pnpm/@ai-sdk+provider@3.0.8/node_modules/@ai-sdk/provider/dist/index.mjs
206178
206468
  var marker = "vercel.ai.error";
@@ -210412,7 +210702,7 @@ function createParser(callbacks) {
210412
210702
  const { onEvent = noop2, onError = noop2, onRetry = noop2, onComment } = callbacks;
210413
210703
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
210414
210704
  function feed(newChunk) {
210415
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
210705
+ const chunk2 = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk2}`);
210416
210706
  for (const line of complete)
210417
210707
  parseLine(line);
210418
210708
  incompleteLine = incomplete, isFirstChunk = false;
@@ -210480,19 +210770,19 @@ function createParser(callbacks) {
210480
210770
  }
210481
210771
  return { feed, reset };
210482
210772
  }
210483
- function splitLines(chunk) {
210773
+ function splitLines(chunk2) {
210484
210774
  const lines = [];
210485
210775
  let incompleteLine = "", searchIndex = 0;
210486
- for (; searchIndex < chunk.length; ) {
210487
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
210776
+ for (; searchIndex < chunk2.length; ) {
210777
+ const crIndex = chunk2.indexOf("\r", searchIndex), lfIndex = chunk2.indexOf(`
210488
210778
  `, searchIndex);
210489
210779
  let lineEnd = -1;
210490
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
210491
- incompleteLine = chunk.slice(searchIndex);
210780
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk2.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
210781
+ incompleteLine = chunk2.slice(searchIndex);
210492
210782
  break;
210493
210783
  } else {
210494
- const line = chunk.slice(searchIndex, lineEnd);
210495
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
210784
+ const line = chunk2.slice(searchIndex, lineEnd);
210785
+ lines.push(line), searchIndex = lineEnd + 1, chunk2[searchIndex - 1] === "\r" && chunk2[searchIndex] === `
210496
210786
  ` && searchIndex++;
210497
210787
  }
210498
210788
  }
@@ -210516,8 +210806,8 @@ var EventSourceParserStream = class extends TransformStream {
210516
210806
  onComment
210517
210807
  });
210518
210808
  },
210519
- transform(chunk) {
210520
- parser.feed(chunk);
210809
+ transform(chunk2) {
210810
+ parser.feed(chunk2);
210521
210811
  }
210522
210812
  });
210523
210813
  }
@@ -210692,9 +210982,9 @@ async function readResponseWithSizeLimit({
210692
210982
  }
210693
210983
  const result = new Uint8Array(totalBytes);
210694
210984
  let offset = 0;
210695
- for (const chunk of chunks) {
210696
- result.set(chunk, offset);
210697
- offset += chunk.length;
210985
+ for (const chunk2 of chunks) {
210986
+ result.set(chunk2, offset);
210987
+ offset += chunk2.length;
210698
210988
  }
210699
210989
  return result;
210700
210990
  }
@@ -213196,9 +213486,9 @@ var GatewayLanguageModel = class {
213196
213486
  controller.enqueue({ type: "stream-start", warnings });
213197
213487
  }
213198
213488
  },
213199
- transform(chunk, controller) {
213200
- if (chunk.success) {
213201
- const streamPart = chunk.value;
213489
+ transform(chunk2, controller) {
213490
+ if (chunk2.success) {
213491
+ const streamPart = chunk2.value;
213202
213492
  if (streamPart.type === "raw" && !options.includeRawChunks) {
213203
213493
  return;
213204
213494
  }
@@ -213208,7 +213498,7 @@ var GatewayLanguageModel = class {
213208
213498
  controller.enqueue(streamPart);
213209
213499
  } else {
213210
213500
  controller.error(
213211
- chunk.error
213501
+ chunk2.error
213212
213502
  );
213213
213503
  }
213214
213504
  }
@@ -214415,17 +214705,17 @@ function asLanguageModelV3(model) {
214415
214705
  function convertV2StreamToV3(stream) {
214416
214706
  return stream.pipeThrough(
214417
214707
  new TransformStream({
214418
- transform(chunk, controller) {
214419
- switch (chunk.type) {
214708
+ transform(chunk2, controller) {
214709
+ switch (chunk2.type) {
214420
214710
  case "finish":
214421
214711
  controller.enqueue({
214422
- ...chunk,
214423
- finishReason: convertV2FinishReasonToV3(chunk.finishReason),
214424
- usage: convertV2UsageToV3(chunk.usage)
214712
+ ...chunk2,
214713
+ finishReason: convertV2FinishReasonToV3(chunk2.finishReason),
214714
+ usage: convertV2UsageToV3(chunk2.usage)
214425
214715
  });
214426
214716
  break;
214427
214717
  default:
214428
- controller.enqueue(chunk);
214718
+ controller.enqueue(chunk2);
214429
214719
  break;
214430
214720
  }
214431
214721
  }
@@ -218371,8 +218661,8 @@ var uiMessageChunkSchema = lazySchema(
218371
218661
  ])
218372
218662
  )
218373
218663
  );
218374
- function isDataUIMessageChunk(chunk) {
218375
- return chunk.type.startsWith("data-");
218664
+ function isDataUIMessageChunk(chunk2) {
218665
+ return chunk2.type.startsWith("data-");
218376
218666
  }
218377
218667
  function isStaticToolUIPart(part) {
218378
218668
  return part.type.startsWith("tool-");
@@ -218413,7 +218703,7 @@ function processUIMessageStream({
218413
218703
  }) {
218414
218704
  return stream.pipeThrough(
218415
218705
  new TransformStream({
218416
- async transform(chunk, controller) {
218706
+ async transform(chunk2, controller) {
218417
218707
  await runUpdateMessageJob(async ({ state, write }) => {
218418
218708
  var _a212, _b18, _c, _d;
218419
218709
  function getToolInvocation(toolCallId) {
@@ -218521,45 +218811,45 @@ function processUIMessageStream({
218521
218811
  state.message.metadata = mergedMetadata;
218522
218812
  }
218523
218813
  }
218524
- switch (chunk.type) {
218814
+ switch (chunk2.type) {
218525
218815
  case "text-start": {
218526
218816
  const textPart = {
218527
218817
  type: "text",
218528
218818
  text: "",
218529
- providerMetadata: chunk.providerMetadata,
218819
+ providerMetadata: chunk2.providerMetadata,
218530
218820
  state: "streaming"
218531
218821
  };
218532
- state.activeTextParts[chunk.id] = textPart;
218822
+ state.activeTextParts[chunk2.id] = textPart;
218533
218823
  state.message.parts.push(textPart);
218534
218824
  write();
218535
218825
  break;
218536
218826
  }
218537
218827
  case "text-delta": {
218538
- const textPart = state.activeTextParts[chunk.id];
218828
+ const textPart = state.activeTextParts[chunk2.id];
218539
218829
  if (textPart == null) {
218540
218830
  throw new UIMessageStreamError({
218541
218831
  chunkType: "text-delta",
218542
- chunkId: chunk.id,
218543
- message: `Received text-delta for missing text part with ID "${chunk.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`
218832
+ chunkId: chunk2.id,
218833
+ message: `Received text-delta for missing text part with ID "${chunk2.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`
218544
218834
  });
218545
218835
  }
218546
- textPart.text += chunk.delta;
218547
- textPart.providerMetadata = (_a212 = chunk.providerMetadata) != null ? _a212 : textPart.providerMetadata;
218836
+ textPart.text += chunk2.delta;
218837
+ textPart.providerMetadata = (_a212 = chunk2.providerMetadata) != null ? _a212 : textPart.providerMetadata;
218548
218838
  write();
218549
218839
  break;
218550
218840
  }
218551
218841
  case "text-end": {
218552
- const textPart = state.activeTextParts[chunk.id];
218842
+ const textPart = state.activeTextParts[chunk2.id];
218553
218843
  if (textPart == null) {
218554
218844
  throw new UIMessageStreamError({
218555
218845
  chunkType: "text-end",
218556
- chunkId: chunk.id,
218557
- message: `Received text-end for missing text part with ID "${chunk.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`
218846
+ chunkId: chunk2.id,
218847
+ message: `Received text-end for missing text part with ID "${chunk2.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`
218558
218848
  });
218559
218849
  }
218560
218850
  textPart.state = "done";
218561
- textPart.providerMetadata = (_b18 = chunk.providerMetadata) != null ? _b18 : textPart.providerMetadata;
218562
- delete state.activeTextParts[chunk.id];
218851
+ textPart.providerMetadata = (_b18 = chunk2.providerMetadata) != null ? _b18 : textPart.providerMetadata;
218852
+ delete state.activeTextParts[chunk2.id];
218563
218853
  write();
218564
218854
  break;
218565
218855
  }
@@ -218567,48 +218857,48 @@ function processUIMessageStream({
218567
218857
  const reasoningPart = {
218568
218858
  type: "reasoning",
218569
218859
  text: "",
218570
- providerMetadata: chunk.providerMetadata,
218860
+ providerMetadata: chunk2.providerMetadata,
218571
218861
  state: "streaming"
218572
218862
  };
218573
- state.activeReasoningParts[chunk.id] = reasoningPart;
218863
+ state.activeReasoningParts[chunk2.id] = reasoningPart;
218574
218864
  state.message.parts.push(reasoningPart);
218575
218865
  write();
218576
218866
  break;
218577
218867
  }
218578
218868
  case "reasoning-delta": {
218579
- const reasoningPart = state.activeReasoningParts[chunk.id];
218869
+ const reasoningPart = state.activeReasoningParts[chunk2.id];
218580
218870
  if (reasoningPart == null) {
218581
218871
  throw new UIMessageStreamError({
218582
218872
  chunkType: "reasoning-delta",
218583
- chunkId: chunk.id,
218584
- message: `Received reasoning-delta for missing reasoning part with ID "${chunk.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`
218873
+ chunkId: chunk2.id,
218874
+ message: `Received reasoning-delta for missing reasoning part with ID "${chunk2.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`
218585
218875
  });
218586
218876
  }
218587
- reasoningPart.text += chunk.delta;
218588
- reasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
218877
+ reasoningPart.text += chunk2.delta;
218878
+ reasoningPart.providerMetadata = (_c = chunk2.providerMetadata) != null ? _c : reasoningPart.providerMetadata;
218589
218879
  write();
218590
218880
  break;
218591
218881
  }
218592
218882
  case "reasoning-end": {
218593
- const reasoningPart = state.activeReasoningParts[chunk.id];
218883
+ const reasoningPart = state.activeReasoningParts[chunk2.id];
218594
218884
  if (reasoningPart == null) {
218595
218885
  throw new UIMessageStreamError({
218596
218886
  chunkType: "reasoning-end",
218597
- chunkId: chunk.id,
218598
- message: `Received reasoning-end for missing reasoning part with ID "${chunk.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`
218887
+ chunkId: chunk2.id,
218888
+ message: `Received reasoning-end for missing reasoning part with ID "${chunk2.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`
218599
218889
  });
218600
218890
  }
218601
- reasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
218891
+ reasoningPart.providerMetadata = (_d = chunk2.providerMetadata) != null ? _d : reasoningPart.providerMetadata;
218602
218892
  reasoningPart.state = "done";
218603
- delete state.activeReasoningParts[chunk.id];
218893
+ delete state.activeReasoningParts[chunk2.id];
218604
218894
  write();
218605
218895
  break;
218606
218896
  }
218607
218897
  case "file": {
218608
218898
  state.message.parts.push({
218609
218899
  type: "file",
218610
- mediaType: chunk.mediaType,
218611
- url: chunk.url
218900
+ mediaType: chunk2.mediaType,
218901
+ url: chunk2.url
218612
218902
  });
218613
218903
  write();
218614
218904
  break;
@@ -218616,10 +218906,10 @@ function processUIMessageStream({
218616
218906
  case "source-url": {
218617
218907
  state.message.parts.push({
218618
218908
  type: "source-url",
218619
- sourceId: chunk.sourceId,
218620
- url: chunk.url,
218621
- title: chunk.title,
218622
- providerMetadata: chunk.providerMetadata
218909
+ sourceId: chunk2.sourceId,
218910
+ url: chunk2.url,
218911
+ title: chunk2.title,
218912
+ providerMetadata: chunk2.providerMetadata
218623
218913
  });
218624
218914
  write();
218625
218915
  break;
@@ -218627,64 +218917,64 @@ function processUIMessageStream({
218627
218917
  case "source-document": {
218628
218918
  state.message.parts.push({
218629
218919
  type: "source-document",
218630
- sourceId: chunk.sourceId,
218631
- mediaType: chunk.mediaType,
218632
- title: chunk.title,
218633
- filename: chunk.filename,
218634
- providerMetadata: chunk.providerMetadata
218920
+ sourceId: chunk2.sourceId,
218921
+ mediaType: chunk2.mediaType,
218922
+ title: chunk2.title,
218923
+ filename: chunk2.filename,
218924
+ providerMetadata: chunk2.providerMetadata
218635
218925
  });
218636
218926
  write();
218637
218927
  break;
218638
218928
  }
218639
218929
  case "tool-input-start": {
218640
218930
  const toolInvocations = state.message.parts.filter(isStaticToolUIPart);
218641
- state.partialToolCalls[chunk.toolCallId] = {
218931
+ state.partialToolCalls[chunk2.toolCallId] = {
218642
218932
  text: "",
218643
- toolName: chunk.toolName,
218933
+ toolName: chunk2.toolName,
218644
218934
  index: toolInvocations.length,
218645
- dynamic: chunk.dynamic,
218646
- title: chunk.title
218935
+ dynamic: chunk2.dynamic,
218936
+ title: chunk2.title
218647
218937
  };
218648
- if (chunk.dynamic) {
218938
+ if (chunk2.dynamic) {
218649
218939
  updateDynamicToolPart({
218650
- toolCallId: chunk.toolCallId,
218651
- toolName: chunk.toolName,
218940
+ toolCallId: chunk2.toolCallId,
218941
+ toolName: chunk2.toolName,
218652
218942
  state: "input-streaming",
218653
218943
  input: void 0,
218654
- providerExecuted: chunk.providerExecuted,
218655
- title: chunk.title,
218656
- providerMetadata: chunk.providerMetadata
218944
+ providerExecuted: chunk2.providerExecuted,
218945
+ title: chunk2.title,
218946
+ providerMetadata: chunk2.providerMetadata
218657
218947
  });
218658
218948
  } else {
218659
218949
  updateToolPart({
218660
- toolCallId: chunk.toolCallId,
218661
- toolName: chunk.toolName,
218950
+ toolCallId: chunk2.toolCallId,
218951
+ toolName: chunk2.toolName,
218662
218952
  state: "input-streaming",
218663
218953
  input: void 0,
218664
- providerExecuted: chunk.providerExecuted,
218665
- title: chunk.title,
218666
- providerMetadata: chunk.providerMetadata
218954
+ providerExecuted: chunk2.providerExecuted,
218955
+ title: chunk2.title,
218956
+ providerMetadata: chunk2.providerMetadata
218667
218957
  });
218668
218958
  }
218669
218959
  write();
218670
218960
  break;
218671
218961
  }
218672
218962
  case "tool-input-delta": {
218673
- const partialToolCall = state.partialToolCalls[chunk.toolCallId];
218963
+ const partialToolCall = state.partialToolCalls[chunk2.toolCallId];
218674
218964
  if (partialToolCall == null) {
218675
218965
  throw new UIMessageStreamError({
218676
218966
  chunkType: "tool-input-delta",
218677
- chunkId: chunk.toolCallId,
218678
- message: `Received tool-input-delta for missing tool call with ID "${chunk.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`
218967
+ chunkId: chunk2.toolCallId,
218968
+ message: `Received tool-input-delta for missing tool call with ID "${chunk2.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`
218679
218969
  });
218680
218970
  }
218681
- partialToolCall.text += chunk.inputTextDelta;
218971
+ partialToolCall.text += chunk2.inputTextDelta;
218682
218972
  const { value: partialArgs } = await parsePartialJson(
218683
218973
  partialToolCall.text
218684
218974
  );
218685
218975
  if (partialToolCall.dynamic) {
218686
218976
  updateDynamicToolPart({
218687
- toolCallId: chunk.toolCallId,
218977
+ toolCallId: chunk2.toolCallId,
218688
218978
  toolName: partialToolCall.toolName,
218689
218979
  state: "input-streaming",
218690
218980
  input: partialArgs,
@@ -218692,7 +218982,7 @@ function processUIMessageStream({
218692
218982
  });
218693
218983
  } else {
218694
218984
  updateToolPart({
218695
- toolCallId: chunk.toolCallId,
218985
+ toolCallId: chunk2.toolCallId,
218696
218986
  toolName: partialToolCall.toolName,
218697
218987
  state: "input-streaming",
218698
218988
  input: partialArgs,
@@ -218703,96 +218993,96 @@ function processUIMessageStream({
218703
218993
  break;
218704
218994
  }
218705
218995
  case "tool-input-available": {
218706
- if (chunk.dynamic) {
218996
+ if (chunk2.dynamic) {
218707
218997
  updateDynamicToolPart({
218708
- toolCallId: chunk.toolCallId,
218709
- toolName: chunk.toolName,
218998
+ toolCallId: chunk2.toolCallId,
218999
+ toolName: chunk2.toolName,
218710
219000
  state: "input-available",
218711
- input: chunk.input,
218712
- providerExecuted: chunk.providerExecuted,
218713
- providerMetadata: chunk.providerMetadata,
218714
- title: chunk.title
219001
+ input: chunk2.input,
219002
+ providerExecuted: chunk2.providerExecuted,
219003
+ providerMetadata: chunk2.providerMetadata,
219004
+ title: chunk2.title
218715
219005
  });
218716
219006
  } else {
218717
219007
  updateToolPart({
218718
- toolCallId: chunk.toolCallId,
218719
- toolName: chunk.toolName,
219008
+ toolCallId: chunk2.toolCallId,
219009
+ toolName: chunk2.toolName,
218720
219010
  state: "input-available",
218721
- input: chunk.input,
218722
- providerExecuted: chunk.providerExecuted,
218723
- providerMetadata: chunk.providerMetadata,
218724
- title: chunk.title
219011
+ input: chunk2.input,
219012
+ providerExecuted: chunk2.providerExecuted,
219013
+ providerMetadata: chunk2.providerMetadata,
219014
+ title: chunk2.title
218725
219015
  });
218726
219016
  }
218727
219017
  write();
218728
- if (onToolCall && !chunk.providerExecuted) {
219018
+ if (onToolCall && !chunk2.providerExecuted) {
218729
219019
  await onToolCall({
218730
- toolCall: chunk
219020
+ toolCall: chunk2
218731
219021
  });
218732
219022
  }
218733
219023
  break;
218734
219024
  }
218735
219025
  case "tool-input-error": {
218736
- if (chunk.dynamic) {
219026
+ if (chunk2.dynamic) {
218737
219027
  updateDynamicToolPart({
218738
- toolCallId: chunk.toolCallId,
218739
- toolName: chunk.toolName,
219028
+ toolCallId: chunk2.toolCallId,
219029
+ toolName: chunk2.toolName,
218740
219030
  state: "output-error",
218741
- input: chunk.input,
218742
- errorText: chunk.errorText,
218743
- providerExecuted: chunk.providerExecuted,
218744
- providerMetadata: chunk.providerMetadata
219031
+ input: chunk2.input,
219032
+ errorText: chunk2.errorText,
219033
+ providerExecuted: chunk2.providerExecuted,
219034
+ providerMetadata: chunk2.providerMetadata
218745
219035
  });
218746
219036
  } else {
218747
219037
  updateToolPart({
218748
- toolCallId: chunk.toolCallId,
218749
- toolName: chunk.toolName,
219038
+ toolCallId: chunk2.toolCallId,
219039
+ toolName: chunk2.toolName,
218750
219040
  state: "output-error",
218751
219041
  input: void 0,
218752
- rawInput: chunk.input,
218753
- errorText: chunk.errorText,
218754
- providerExecuted: chunk.providerExecuted,
218755
- providerMetadata: chunk.providerMetadata
219042
+ rawInput: chunk2.input,
219043
+ errorText: chunk2.errorText,
219044
+ providerExecuted: chunk2.providerExecuted,
219045
+ providerMetadata: chunk2.providerMetadata
218756
219046
  });
218757
219047
  }
218758
219048
  write();
218759
219049
  break;
218760
219050
  }
218761
219051
  case "tool-approval-request": {
218762
- const toolInvocation = getToolInvocation(chunk.toolCallId);
219052
+ const toolInvocation = getToolInvocation(chunk2.toolCallId);
218763
219053
  toolInvocation.state = "approval-requested";
218764
- toolInvocation.approval = { id: chunk.approvalId };
219054
+ toolInvocation.approval = { id: chunk2.approvalId };
218765
219055
  write();
218766
219056
  break;
218767
219057
  }
218768
219058
  case "tool-output-denied": {
218769
- const toolInvocation = getToolInvocation(chunk.toolCallId);
219059
+ const toolInvocation = getToolInvocation(chunk2.toolCallId);
218770
219060
  toolInvocation.state = "output-denied";
218771
219061
  write();
218772
219062
  break;
218773
219063
  }
218774
219064
  case "tool-output-available": {
218775
- const toolInvocation = getToolInvocation(chunk.toolCallId);
219065
+ const toolInvocation = getToolInvocation(chunk2.toolCallId);
218776
219066
  if (toolInvocation.type === "dynamic-tool") {
218777
219067
  updateDynamicToolPart({
218778
- toolCallId: chunk.toolCallId,
219068
+ toolCallId: chunk2.toolCallId,
218779
219069
  toolName: toolInvocation.toolName,
218780
219070
  state: "output-available",
218781
219071
  input: toolInvocation.input,
218782
- output: chunk.output,
218783
- preliminary: chunk.preliminary,
218784
- providerExecuted: chunk.providerExecuted,
219072
+ output: chunk2.output,
219073
+ preliminary: chunk2.preliminary,
219074
+ providerExecuted: chunk2.providerExecuted,
218785
219075
  title: toolInvocation.title
218786
219076
  });
218787
219077
  } else {
218788
219078
  updateToolPart({
218789
- toolCallId: chunk.toolCallId,
219079
+ toolCallId: chunk2.toolCallId,
218790
219080
  toolName: getStaticToolName(toolInvocation),
218791
219081
  state: "output-available",
218792
219082
  input: toolInvocation.input,
218793
- output: chunk.output,
218794
- providerExecuted: chunk.providerExecuted,
218795
- preliminary: chunk.preliminary,
219083
+ output: chunk2.output,
219084
+ providerExecuted: chunk2.providerExecuted,
219085
+ preliminary: chunk2.preliminary,
218796
219086
  title: toolInvocation.title
218797
219087
  });
218798
219088
  }
@@ -218800,26 +219090,26 @@ function processUIMessageStream({
218800
219090
  break;
218801
219091
  }
218802
219092
  case "tool-output-error": {
218803
- const toolInvocation = getToolInvocation(chunk.toolCallId);
219093
+ const toolInvocation = getToolInvocation(chunk2.toolCallId);
218804
219094
  if (toolInvocation.type === "dynamic-tool") {
218805
219095
  updateDynamicToolPart({
218806
- toolCallId: chunk.toolCallId,
219096
+ toolCallId: chunk2.toolCallId,
218807
219097
  toolName: toolInvocation.toolName,
218808
219098
  state: "output-error",
218809
219099
  input: toolInvocation.input,
218810
- errorText: chunk.errorText,
218811
- providerExecuted: chunk.providerExecuted,
219100
+ errorText: chunk2.errorText,
219101
+ providerExecuted: chunk2.providerExecuted,
218812
219102
  title: toolInvocation.title
218813
219103
  });
218814
219104
  } else {
218815
219105
  updateToolPart({
218816
- toolCallId: chunk.toolCallId,
219106
+ toolCallId: chunk2.toolCallId,
218817
219107
  toolName: getStaticToolName(toolInvocation),
218818
219108
  state: "output-error",
218819
219109
  input: toolInvocation.input,
218820
219110
  rawInput: toolInvocation.rawInput,
218821
- errorText: chunk.errorText,
218822
- providerExecuted: chunk.providerExecuted,
219111
+ errorText: chunk2.errorText,
219112
+ providerExecuted: chunk2.providerExecuted,
218823
219113
  title: toolInvocation.title
218824
219114
  });
218825
219115
  }
@@ -218836,54 +219126,54 @@ function processUIMessageStream({
218836
219126
  break;
218837
219127
  }
218838
219128
  case "start": {
218839
- if (chunk.messageId != null) {
218840
- state.message.id = chunk.messageId;
219129
+ if (chunk2.messageId != null) {
219130
+ state.message.id = chunk2.messageId;
218841
219131
  }
218842
- await updateMessageMetadata(chunk.messageMetadata);
218843
- if (chunk.messageId != null || chunk.messageMetadata != null) {
219132
+ await updateMessageMetadata(chunk2.messageMetadata);
219133
+ if (chunk2.messageId != null || chunk2.messageMetadata != null) {
218844
219134
  write();
218845
219135
  }
218846
219136
  break;
218847
219137
  }
218848
219138
  case "finish": {
218849
- if (chunk.finishReason != null) {
218850
- state.finishReason = chunk.finishReason;
219139
+ if (chunk2.finishReason != null) {
219140
+ state.finishReason = chunk2.finishReason;
218851
219141
  }
218852
- await updateMessageMetadata(chunk.messageMetadata);
218853
- if (chunk.messageMetadata != null) {
219142
+ await updateMessageMetadata(chunk2.messageMetadata);
219143
+ if (chunk2.messageMetadata != null) {
218854
219144
  write();
218855
219145
  }
218856
219146
  break;
218857
219147
  }
218858
219148
  case "message-metadata": {
218859
- await updateMessageMetadata(chunk.messageMetadata);
218860
- if (chunk.messageMetadata != null) {
219149
+ await updateMessageMetadata(chunk2.messageMetadata);
219150
+ if (chunk2.messageMetadata != null) {
218861
219151
  write();
218862
219152
  }
218863
219153
  break;
218864
219154
  }
218865
219155
  case "error": {
218866
- onError == null ? void 0 : onError(new Error(chunk.errorText));
219156
+ onError == null ? void 0 : onError(new Error(chunk2.errorText));
218867
219157
  break;
218868
219158
  }
218869
219159
  default: {
218870
- if (isDataUIMessageChunk(chunk)) {
218871
- if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {
219160
+ if (isDataUIMessageChunk(chunk2)) {
219161
+ if ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk2.type]) != null) {
218872
219162
  const partIdx = state.message.parts.findIndex(
218873
- (p2) => "id" in p2 && "data" in p2 && p2.id === chunk.id && p2.type === chunk.type
219163
+ (p2) => "id" in p2 && "data" in p2 && p2.id === chunk2.id && p2.type === chunk2.type
218874
219164
  );
218875
219165
  const actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;
218876
219166
  await validateTypes({
218877
- value: chunk.data,
218878
- schema: dataPartSchemas[chunk.type],
219167
+ value: chunk2.data,
219168
+ schema: dataPartSchemas[chunk2.type],
218879
219169
  context: {
218880
219170
  field: `message.parts[${actualPartIdx}].data`,
218881
- entityName: chunk.type,
218882
- entityId: chunk.id
219171
+ entityName: chunk2.type,
219172
+ entityId: chunk2.id
218883
219173
  }
218884
219174
  });
218885
219175
  }
218886
- const dataChunk = chunk;
219176
+ const dataChunk = chunk2;
218887
219177
  if (dataChunk.transient) {
218888
219178
  onData == null ? void 0 : onData(dataChunk);
218889
219179
  break;
@@ -218901,7 +219191,7 @@ function processUIMessageStream({
218901
219191
  }
218902
219192
  }
218903
219193
  }
218904
- controller.enqueue(chunk);
219194
+ controller.enqueue(chunk2);
218905
219195
  });
218906
219196
  }
218907
219197
  })
@@ -218924,17 +219214,17 @@ function handleUIMessageStreamFinish({
218924
219214
  let isAborted2 = false;
218925
219215
  const idInjectedStream = stream.pipeThrough(
218926
219216
  new TransformStream({
218927
- transform(chunk, controller) {
218928
- if (chunk.type === "start") {
218929
- const startChunk = chunk;
219217
+ transform(chunk2, controller) {
219218
+ if (chunk2.type === "start") {
219219
+ const startChunk = chunk2;
218930
219220
  if (startChunk.messageId == null && messageId != null) {
218931
219221
  startChunk.messageId = messageId;
218932
219222
  }
218933
219223
  }
218934
- if (chunk.type === "abort") {
219224
+ if (chunk2.type === "abort") {
218935
219225
  isAborted2 = true;
218936
219226
  }
218937
- controller.enqueue(chunk);
219227
+ controller.enqueue(chunk2);
218938
219228
  }
218939
219229
  })
218940
219230
  );
@@ -218992,11 +219282,11 @@ function handleUIMessageStreamFinish({
218992
219282
  onError
218993
219283
  }).pipeThrough(
218994
219284
  new TransformStream({
218995
- async transform(chunk, controller) {
218996
- if (chunk.type === "finish-step") {
219285
+ async transform(chunk2, controller) {
219286
+ if (chunk2.type === "finish-step") {
218997
219287
  await callOnStepFinish();
218998
219288
  }
218999
- controller.enqueue(chunk);
219289
+ controller.enqueue(chunk2);
219000
219290
  },
219001
219291
  // @ts-expect-error cancel is still new and missing from types https://developer.mozilla.org/en-US/docs/Web/API/TransformStream#browser_compatibility
219002
219292
  async cancel() {
@@ -219237,8 +219527,8 @@ function runToolsTransformation({
219237
219527
  }
219238
219528
  }
219239
219529
  const forwardStream = new TransformStream({
219240
- async transform(chunk, controller) {
219241
- const chunkType = chunk.type;
219530
+ async transform(chunk2, controller) {
219531
+ const chunkType = chunk2.type;
219242
219532
  switch (chunkType) {
219243
219533
  case "stream-start":
219244
219534
  case "text-start":
@@ -219254,15 +219544,15 @@ function runToolsTransformation({
219254
219544
  case "response-metadata":
219255
219545
  case "error":
219256
219546
  case "raw": {
219257
- controller.enqueue(chunk);
219547
+ controller.enqueue(chunk2);
219258
219548
  break;
219259
219549
  }
219260
219550
  case "file": {
219261
219551
  controller.enqueue({
219262
219552
  type: "file",
219263
219553
  file: new DefaultGeneratedFileWithType({
219264
- data: chunk.data,
219265
- mediaType: chunk.mediaType
219554
+ data: chunk2.data,
219555
+ mediaType: chunk2.mediaType
219266
219556
  })
219267
219557
  });
219268
219558
  break;
@@ -219270,28 +219560,28 @@ function runToolsTransformation({
219270
219560
  case "finish": {
219271
219561
  finishChunk = {
219272
219562
  type: "finish",
219273
- finishReason: chunk.finishReason.unified,
219274
- rawFinishReason: chunk.finishReason.raw,
219275
- usage: asLanguageModelUsage(chunk.usage),
219276
- providerMetadata: chunk.providerMetadata
219563
+ finishReason: chunk2.finishReason.unified,
219564
+ rawFinishReason: chunk2.finishReason.raw,
219565
+ usage: asLanguageModelUsage(chunk2.usage),
219566
+ providerMetadata: chunk2.providerMetadata
219277
219567
  };
219278
219568
  break;
219279
219569
  }
219280
219570
  case "tool-approval-request": {
219281
- const toolCall = toolCallsByToolCallId.get(chunk.toolCallId);
219571
+ const toolCall = toolCallsByToolCallId.get(chunk2.toolCallId);
219282
219572
  if (toolCall == null) {
219283
219573
  toolResultsStreamController.enqueue({
219284
219574
  type: "error",
219285
219575
  error: new ToolCallNotFoundForApprovalError({
219286
- toolCallId: chunk.toolCallId,
219287
- approvalId: chunk.approvalId
219576
+ toolCallId: chunk2.toolCallId,
219577
+ approvalId: chunk2.approvalId
219288
219578
  })
219289
219579
  });
219290
219580
  break;
219291
219581
  }
219292
219582
  controller.enqueue({
219293
219583
  type: "tool-approval-request",
219294
- approvalId: chunk.approvalId,
219584
+ approvalId: chunk2.approvalId,
219295
219585
  toolCall
219296
219586
  });
219297
219587
  break;
@@ -219299,7 +219589,7 @@ function runToolsTransformation({
219299
219589
  case "tool-call": {
219300
219590
  try {
219301
219591
  const toolCall = await parseToolCall({
219302
- toolCall: chunk,
219592
+ toolCall: chunk2,
219303
219593
  tools,
219304
219594
  repairToolCall,
219305
219595
  system,
@@ -219382,26 +219672,26 @@ function runToolsTransformation({
219382
219672
  break;
219383
219673
  }
219384
219674
  case "tool-result": {
219385
- const toolName = chunk.toolName;
219386
- if (chunk.isError) {
219675
+ const toolName = chunk2.toolName;
219676
+ if (chunk2.isError) {
219387
219677
  toolResultsStreamController.enqueue({
219388
219678
  type: "tool-error",
219389
- toolCallId: chunk.toolCallId,
219679
+ toolCallId: chunk2.toolCallId,
219390
219680
  toolName,
219391
- input: toolInputs.get(chunk.toolCallId),
219681
+ input: toolInputs.get(chunk2.toolCallId),
219392
219682
  providerExecuted: true,
219393
- error: chunk.result,
219394
- dynamic: chunk.dynamic
219683
+ error: chunk2.result,
219684
+ dynamic: chunk2.dynamic
219395
219685
  });
219396
219686
  } else {
219397
219687
  controller.enqueue({
219398
219688
  type: "tool-result",
219399
- toolCallId: chunk.toolCallId,
219689
+ toolCallId: chunk2.toolCallId,
219400
219690
  toolName,
219401
- input: toolInputs.get(chunk.toolCallId),
219402
- output: chunk.result,
219691
+ input: toolInputs.get(chunk2.toolCallId),
219692
+ output: chunk2.result,
219403
219693
  providerExecuted: true,
219404
- dynamic: chunk.dynamic
219694
+ dynamic: chunk2.dynamic
219405
219695
  });
219406
219696
  }
219407
219697
  break;
@@ -219422,8 +219712,8 @@ function runToolsTransformation({
219422
219712
  return Promise.all([
219423
219713
  generatorStream.pipeThrough(forwardStream).pipeTo(
219424
219714
  new WritableStream({
219425
- write(chunk) {
219426
- controller.enqueue(chunk);
219715
+ write(chunk2) {
219716
+ controller.enqueue(chunk2);
219427
219717
  },
219428
219718
  close() {
219429
219719
  }
@@ -219431,8 +219721,8 @@ function runToolsTransformation({
219431
219721
  ),
219432
219722
  toolResultsStream.pipeTo(
219433
219723
  new WritableStream({
219434
- write(chunk) {
219435
- controller.enqueue(chunk);
219724
+ write(chunk2) {
219725
+ controller.enqueue(chunk2);
219436
219726
  },
219437
219727
  close() {
219438
219728
  controller.close();
@@ -219561,35 +219851,35 @@ function createOutputTransformStream(output) {
219561
219851
  textChunk = "";
219562
219852
  }
219563
219853
  return new TransformStream({
219564
- async transform(chunk, controller) {
219854
+ async transform(chunk2, controller) {
219565
219855
  var _a212;
219566
- if (chunk.type === "finish-step" && textChunk.length > 0) {
219856
+ if (chunk2.type === "finish-step" && textChunk.length > 0) {
219567
219857
  publishTextChunk({ controller });
219568
219858
  }
219569
- if (chunk.type !== "text-delta" && chunk.type !== "text-start" && chunk.type !== "text-end") {
219570
- controller.enqueue({ part: chunk, partialOutput: void 0 });
219859
+ if (chunk2.type !== "text-delta" && chunk2.type !== "text-start" && chunk2.type !== "text-end") {
219860
+ controller.enqueue({ part: chunk2, partialOutput: void 0 });
219571
219861
  return;
219572
219862
  }
219573
219863
  if (firstTextChunkId == null) {
219574
- firstTextChunkId = chunk.id;
219575
- } else if (chunk.id !== firstTextChunkId) {
219576
- controller.enqueue({ part: chunk, partialOutput: void 0 });
219864
+ firstTextChunkId = chunk2.id;
219865
+ } else if (chunk2.id !== firstTextChunkId) {
219866
+ controller.enqueue({ part: chunk2, partialOutput: void 0 });
219577
219867
  return;
219578
219868
  }
219579
- if (chunk.type === "text-start") {
219580
- controller.enqueue({ part: chunk, partialOutput: void 0 });
219869
+ if (chunk2.type === "text-start") {
219870
+ controller.enqueue({ part: chunk2, partialOutput: void 0 });
219581
219871
  return;
219582
219872
  }
219583
- if (chunk.type === "text-end") {
219873
+ if (chunk2.type === "text-end") {
219584
219874
  if (textChunk.length > 0) {
219585
219875
  publishTextChunk({ controller });
219586
219876
  }
219587
- controller.enqueue({ part: chunk, partialOutput: void 0 });
219877
+ controller.enqueue({ part: chunk2, partialOutput: void 0 });
219588
219878
  return;
219589
219879
  }
219590
- text2 += chunk.text;
219591
- textChunk += chunk.text;
219592
- textProviderMetadata = (_a212 = chunk.providerMetadata) != null ? _a212 : textProviderMetadata;
219880
+ text2 += chunk2.text;
219881
+ textChunk += chunk2.text;
219882
+ textProviderMetadata = (_a212 = chunk2.providerMetadata) != null ? _a212 : textProviderMetadata;
219593
219883
  const result = await output.parsePartialOutput({ text: text2 });
219594
219884
  if (result !== void 0) {
219595
219885
  const currentJson = JSON.stringify(result.partial);
@@ -219665,10 +219955,10 @@ var DefaultStreamTextResult = class {
219665
219955
  let activeTextContent = {};
219666
219956
  let activeReasoningContent = {};
219667
219957
  const eventProcessor = new TransformStream({
219668
- async transform(chunk, controller) {
219958
+ async transform(chunk2, controller) {
219669
219959
  var _a212, _b18, _c, _d;
219670
- controller.enqueue(chunk);
219671
- const { part } = chunk;
219960
+ controller.enqueue(chunk2);
219961
+ const { part } = chunk2;
219672
219962
  if (part.type === "text-delta" || part.type === "reasoning-delta" || part.type === "source" || part.type === "tool-call" || part.type === "tool-result" || part.type === "tool-input-start" || part.type === "tool-input-delta" || part.type === "raw") {
219673
219963
  await (onChunk == null ? void 0 : onChunk({ chunk: part }));
219674
219964
  }
@@ -220316,11 +220606,11 @@ var DefaultStreamTextResult = class {
220316
220606
  self2.addStream(
220317
220607
  streamWithToolResults.pipeThrough(
220318
220608
  new TransformStream({
220319
- async transform(chunk, controller) {
220609
+ async transform(chunk2, controller) {
220320
220610
  var _a222, _b24, _c2, _d2, _e2;
220321
220611
  resetChunkTimeout();
220322
- if (chunk.type === "stream-start") {
220323
- warnings = chunk.warnings;
220612
+ if (chunk2.type === "stream-start") {
220613
+ warnings = chunk2.warnings;
220324
220614
  return;
220325
220615
  }
220326
220616
  if (stepFirstChunk) {
@@ -220338,70 +220628,70 @@ var DefaultStreamTextResult = class {
220338
220628
  warnings: warnings != null ? warnings : []
220339
220629
  });
220340
220630
  }
220341
- const chunkType = chunk.type;
220631
+ const chunkType = chunk2.type;
220342
220632
  switch (chunkType) {
220343
220633
  case "tool-approval-request":
220344
220634
  case "text-start":
220345
220635
  case "text-end": {
220346
- controller.enqueue(chunk);
220636
+ controller.enqueue(chunk2);
220347
220637
  break;
220348
220638
  }
220349
220639
  case "text-delta": {
220350
- if (chunk.delta.length > 0) {
220640
+ if (chunk2.delta.length > 0) {
220351
220641
  controller.enqueue({
220352
220642
  type: "text-delta",
220353
- id: chunk.id,
220354
- text: chunk.delta,
220355
- providerMetadata: chunk.providerMetadata
220643
+ id: chunk2.id,
220644
+ text: chunk2.delta,
220645
+ providerMetadata: chunk2.providerMetadata
220356
220646
  });
220357
- activeText += chunk.delta;
220647
+ activeText += chunk2.delta;
220358
220648
  }
220359
220649
  break;
220360
220650
  }
220361
220651
  case "reasoning-start":
220362
220652
  case "reasoning-end": {
220363
- controller.enqueue(chunk);
220653
+ controller.enqueue(chunk2);
220364
220654
  break;
220365
220655
  }
220366
220656
  case "reasoning-delta": {
220367
220657
  controller.enqueue({
220368
220658
  type: "reasoning-delta",
220369
- id: chunk.id,
220370
- text: chunk.delta,
220371
- providerMetadata: chunk.providerMetadata
220659
+ id: chunk2.id,
220660
+ text: chunk2.delta,
220661
+ providerMetadata: chunk2.providerMetadata
220372
220662
  });
220373
220663
  break;
220374
220664
  }
220375
220665
  case "tool-call": {
220376
- controller.enqueue(chunk);
220377
- stepToolCalls.push(chunk);
220666
+ controller.enqueue(chunk2);
220667
+ stepToolCalls.push(chunk2);
220378
220668
  break;
220379
220669
  }
220380
220670
  case "tool-result": {
220381
- controller.enqueue(chunk);
220382
- if (!chunk.preliminary) {
220383
- stepToolOutputs.push(chunk);
220671
+ controller.enqueue(chunk2);
220672
+ if (!chunk2.preliminary) {
220673
+ stepToolOutputs.push(chunk2);
220384
220674
  }
220385
220675
  break;
220386
220676
  }
220387
220677
  case "tool-error": {
220388
- controller.enqueue(chunk);
220389
- stepToolOutputs.push(chunk);
220678
+ controller.enqueue(chunk2);
220679
+ stepToolOutputs.push(chunk2);
220390
220680
  break;
220391
220681
  }
220392
220682
  case "response-metadata": {
220393
220683
  stepResponse = {
220394
- id: (_a222 = chunk.id) != null ? _a222 : stepResponse.id,
220395
- timestamp: (_b24 = chunk.timestamp) != null ? _b24 : stepResponse.timestamp,
220396
- modelId: (_c2 = chunk.modelId) != null ? _c2 : stepResponse.modelId
220684
+ id: (_a222 = chunk2.id) != null ? _a222 : stepResponse.id,
220685
+ timestamp: (_b24 = chunk2.timestamp) != null ? _b24 : stepResponse.timestamp,
220686
+ modelId: (_c2 = chunk2.modelId) != null ? _c2 : stepResponse.modelId
220397
220687
  };
220398
220688
  break;
220399
220689
  }
220400
220690
  case "finish": {
220401
- stepUsage = chunk.usage;
220402
- stepFinishReason = chunk.finishReason;
220403
- stepRawFinishReason = chunk.rawFinishReason;
220404
- stepProviderMetadata = chunk.providerMetadata;
220691
+ stepUsage = chunk2.usage;
220692
+ stepFinishReason = chunk2.finishReason;
220693
+ stepRawFinishReason = chunk2.rawFinishReason;
220694
+ stepProviderMetadata = chunk2.providerMetadata;
220405
220695
  const msToFinish = now22() - startTimestampMs;
220406
220696
  doStreamSpan.addEvent("ai.stream.finish");
220407
220697
  doStreamSpan.setAttributes({
@@ -220411,59 +220701,59 @@ var DefaultStreamTextResult = class {
220411
220701
  break;
220412
220702
  }
220413
220703
  case "file": {
220414
- controller.enqueue(chunk);
220704
+ controller.enqueue(chunk2);
220415
220705
  break;
220416
220706
  }
220417
220707
  case "source": {
220418
- controller.enqueue(chunk);
220708
+ controller.enqueue(chunk2);
220419
220709
  break;
220420
220710
  }
220421
220711
  case "tool-input-start": {
220422
- activeToolCallToolNames[chunk.id] = chunk.toolName;
220423
- const tool2 = tools == null ? void 0 : tools[chunk.toolName];
220712
+ activeToolCallToolNames[chunk2.id] = chunk2.toolName;
220713
+ const tool2 = tools == null ? void 0 : tools[chunk2.toolName];
220424
220714
  if ((tool2 == null ? void 0 : tool2.onInputStart) != null) {
220425
220715
  await tool2.onInputStart({
220426
- toolCallId: chunk.id,
220716
+ toolCallId: chunk2.id,
220427
220717
  messages: stepInputMessages,
220428
220718
  abortSignal,
220429
220719
  experimental_context
220430
220720
  });
220431
220721
  }
220432
220722
  controller.enqueue({
220433
- ...chunk,
220434
- dynamic: (_e2 = chunk.dynamic) != null ? _e2 : (tool2 == null ? void 0 : tool2.type) === "dynamic",
220723
+ ...chunk2,
220724
+ dynamic: (_e2 = chunk2.dynamic) != null ? _e2 : (tool2 == null ? void 0 : tool2.type) === "dynamic",
220435
220725
  title: tool2 == null ? void 0 : tool2.title
220436
220726
  });
220437
220727
  break;
220438
220728
  }
220439
220729
  case "tool-input-end": {
220440
- delete activeToolCallToolNames[chunk.id];
220441
- controller.enqueue(chunk);
220730
+ delete activeToolCallToolNames[chunk2.id];
220731
+ controller.enqueue(chunk2);
220442
220732
  break;
220443
220733
  }
220444
220734
  case "tool-input-delta": {
220445
- const toolName = activeToolCallToolNames[chunk.id];
220735
+ const toolName = activeToolCallToolNames[chunk2.id];
220446
220736
  const tool2 = tools == null ? void 0 : tools[toolName];
220447
220737
  if ((tool2 == null ? void 0 : tool2.onInputDelta) != null) {
220448
220738
  await tool2.onInputDelta({
220449
- inputTextDelta: chunk.delta,
220450
- toolCallId: chunk.id,
220739
+ inputTextDelta: chunk2.delta,
220740
+ toolCallId: chunk2.id,
220451
220741
  messages: stepInputMessages,
220452
220742
  abortSignal,
220453
220743
  experimental_context
220454
220744
  });
220455
220745
  }
220456
- controller.enqueue(chunk);
220746
+ controller.enqueue(chunk2);
220457
220747
  break;
220458
220748
  }
220459
220749
  case "error": {
220460
- controller.enqueue(chunk);
220750
+ controller.enqueue(chunk2);
220461
220751
  stepFinishReason = "error";
220462
220752
  break;
220463
220753
  }
220464
220754
  case "raw": {
220465
220755
  if (includeRawChunks2) {
220466
- controller.enqueue(chunk);
220756
+ controller.enqueue(chunk2);
220467
220757
  }
220468
220758
  break;
220469
220759
  }
@@ -221930,17 +222220,17 @@ var DeepSeekChatLanguageModel = class {
221930
222220
  start(controller) {
221931
222221
  controller.enqueue({ type: "stream-start", warnings });
221932
222222
  },
221933
- transform(chunk, controller) {
222223
+ transform(chunk2, controller) {
221934
222224
  var _a26, _b18, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
221935
222225
  if (options.includeRawChunks) {
221936
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
222226
+ controller.enqueue({ type: "raw", rawValue: chunk2.rawValue });
221937
222227
  }
221938
- if (!chunk.success) {
222228
+ if (!chunk2.success) {
221939
222229
  finishReason = { unified: "error", raw: void 0 };
221940
- controller.enqueue({ type: "error", error: chunk.error });
222230
+ controller.enqueue({ type: "error", error: chunk2.error });
221941
222231
  return;
221942
222232
  }
221943
- const value = chunk.value;
222233
+ const value = chunk2.value;
221944
222234
  if ("error" in value) {
221945
222235
  finishReason = { unified: "error", raw: void 0 };
221946
222236
  controller.enqueue({ type: "error", error: value.error.message });
@@ -222541,7 +222831,7 @@ function createParser2(callbacks) {
222541
222831
  const { onEvent = noop3, onError = noop3, onRetry = noop3, onComment } = callbacks;
222542
222832
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
222543
222833
  function feed(newChunk) {
222544
- const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk}`);
222834
+ const chunk2 = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines2(`${incompleteLine}${chunk2}`);
222545
222835
  for (const line of complete)
222546
222836
  parseLine(line);
222547
222837
  incompleteLine = incomplete, isFirstChunk = false;
@@ -222609,19 +222899,19 @@ function createParser2(callbacks) {
222609
222899
  }
222610
222900
  return { feed, reset };
222611
222901
  }
222612
- function splitLines2(chunk) {
222902
+ function splitLines2(chunk2) {
222613
222903
  const lines = [];
222614
222904
  let incompleteLine = "", searchIndex = 0;
222615
- for (; searchIndex < chunk.length; ) {
222616
- const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
222905
+ for (; searchIndex < chunk2.length; ) {
222906
+ const crIndex = chunk2.indexOf("\r", searchIndex), lfIndex = chunk2.indexOf(`
222617
222907
  `, searchIndex);
222618
222908
  let lineEnd = -1;
222619
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
222620
- incompleteLine = chunk.slice(searchIndex);
222909
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk2.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
222910
+ incompleteLine = chunk2.slice(searchIndex);
222621
222911
  break;
222622
222912
  } else {
222623
- const line = chunk.slice(searchIndex, lineEnd);
222624
- lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
222913
+ const line = chunk2.slice(searchIndex, lineEnd);
222914
+ lines.push(line), searchIndex = lineEnd + 1, chunk2[searchIndex - 1] === "\r" && chunk2[searchIndex] === `
222625
222915
  ` && searchIndex++;
222626
222916
  }
222627
222917
  }
@@ -222643,8 +222933,8 @@ var EventSourceParserStream2 = class extends TransformStream {
222643
222933
  onComment
222644
222934
  });
222645
222935
  },
222646
- transform(chunk) {
222647
- parser.feed(chunk);
222936
+ transform(chunk2) {
222937
+ parser.feed(chunk2);
222648
222938
  }
222649
222939
  });
222650
222940
  }
@@ -225725,17 +226015,17 @@ var OpenRouterChatLanguageModel = class {
225725
226015
  return {
225726
226016
  stream: safeResponse.pipeThrough(
225727
226017
  new TransformStream({
225728
- transform(chunk, controller) {
226018
+ transform(chunk2, controller) {
225729
226019
  var _a173, _b172, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u;
225730
226020
  if (options.includeRawChunks) {
225731
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
226021
+ controller.enqueue({ type: "raw", rawValue: chunk2.rawValue });
225732
226022
  }
225733
- if (!chunk.success) {
226023
+ if (!chunk2.success) {
225734
226024
  finishReason = createFinishReason("error");
225735
- controller.enqueue({ type: "error", error: chunk.error });
226025
+ controller.enqueue({ type: "error", error: chunk2.error });
225736
226026
  return;
225737
226027
  }
225738
- const value = chunk.value;
226028
+ const value = chunk2.value;
225739
226029
  if ("error" in value) {
225740
226030
  finishReason = createFinishReason("error");
225741
226031
  controller.enqueue({ type: "error", error: value.error });
@@ -226487,17 +226777,17 @@ var OpenRouterCompletionLanguageModel = class {
226487
226777
  return {
226488
226778
  stream: safeResponse.pipeThrough(
226489
226779
  new TransformStream({
226490
- transform(chunk, controller) {
226780
+ transform(chunk2, controller) {
226491
226781
  var _a163, _b162, _c, _d, _e;
226492
226782
  if (options.includeRawChunks) {
226493
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
226783
+ controller.enqueue({ type: "raw", rawValue: chunk2.rawValue });
226494
226784
  }
226495
- if (!chunk.success) {
226785
+ if (!chunk2.success) {
226496
226786
  finishReason = createFinishReason("error");
226497
- controller.enqueue({ type: "error", error: chunk.error });
226787
+ controller.enqueue({ type: "error", error: chunk2.error });
226498
226788
  return;
226499
226789
  }
226500
- const value = chunk.value;
226790
+ const value = chunk2.value;
226501
226791
  if ("error" in value) {
226502
226792
  finishReason = createFinishReason("error");
226503
226793
  controller.enqueue({ type: "error", error: value.error });
@@ -227090,14 +227380,38 @@ async function generateSessionTitle(storage, userMessage, userId) {
227090
227380
  import { execFileSync as execFileSync2 } from "child_process";
227091
227381
  var MAX_BUFFER = 10 * 1024 * 1024;
227092
227382
  var ABSENT = "absent";
227093
- function git(cwd, args) {
227383
+ function git(cwd, args, input) {
227094
227384
  return execFileSync2("git", args, {
227095
227385
  cwd,
227096
227386
  encoding: "utf-8",
227097
227387
  maxBuffer: MAX_BUFFER,
227388
+ input,
227098
227389
  stdio: ["pipe", "pipe", "pipe"]
227099
227390
  });
227100
227391
  }
227392
+ var PATHS_PER_BATCH = 200;
227393
+ function chunk(items, size) {
227394
+ const out = [];
227395
+ for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
227396
+ return out;
227397
+ }
227398
+ function hashObjects(worktreePath, paths) {
227399
+ const hashes = /* @__PURE__ */ new Map();
227400
+ for (const batch of chunk(paths, PATHS_PER_BATCH)) {
227401
+ let shas = [];
227402
+ try {
227403
+ shas = git(worktreePath, ["hash-object", "--", ...batch]).split("\n").map((l) => l.trim()).filter(Boolean);
227404
+ } catch {
227405
+ shas = [];
227406
+ }
227407
+ if (shas.length !== batch.length) {
227408
+ for (const p2 of batch) hashes.set(p2, git(worktreePath, ["hash-object", "--", p2]).trim());
227409
+ continue;
227410
+ }
227411
+ batch.forEach((p2, i) => hashes.set(p2, shas[i]));
227412
+ }
227413
+ return hashes;
227414
+ }
227101
227415
  function captureSnapshot(worktreePath) {
227102
227416
  try {
227103
227417
  const head = git(worktreePath, ["rev-parse", "HEAD"]).trim();
@@ -227110,13 +227424,15 @@ function captureSnapshot(worktreePath) {
227110
227424
  "--name-status",
227111
227425
  "--no-renames"
227112
227426
  ]);
227427
+ const toHash = [];
227113
227428
  for (const line of nameStatus.split("\n")) {
227114
227429
  if (!line.trim()) continue;
227115
227430
  const tab = line.indexOf(" ");
227116
227431
  if (tab < 0) continue;
227117
227432
  const status = line.slice(0, tab).trim();
227118
227433
  const p2 = line.slice(tab + 1).trim();
227119
- dirty[p2] = status.startsWith("D") ? ABSENT : git(worktreePath, ["hash-object", p2]).trim();
227434
+ if (status.startsWith("D")) dirty[p2] = ABSENT;
227435
+ else toHash.push(p2);
227120
227436
  }
227121
227437
  const untracked = git(worktreePath, [
227122
227438
  "-c",
@@ -227127,8 +227443,9 @@ function captureSnapshot(worktreePath) {
227127
227443
  ]);
227128
227444
  for (const p2 of untracked.split("\n")) {
227129
227445
  const t = p2.trim();
227130
- if (t) dirty[t] = git(worktreePath, ["hash-object", t]).trim();
227446
+ if (t) toHash.push(t);
227131
227447
  }
227448
+ for (const [p2, sha] of hashObjects(worktreePath, toHash)) dirty[p2] = sha;
227132
227449
  return { head, dirty };
227133
227450
  } catch {
227134
227451
  return null;
@@ -227141,6 +227458,33 @@ function blobShaOrAbsent(worktreePath, head, filePath) {
227141
227458
  return ABSENT;
227142
227459
  }
227143
227460
  }
227461
+ var BATCH_CHECK_FOUND = /^([0-9a-f]{40,64}) [a-z]+ \d+$/;
227462
+ function blobShasAt(worktreePath, head, paths) {
227463
+ const out = /* @__PURE__ */ new Map();
227464
+ const batchable = [];
227465
+ for (const p2 of paths) {
227466
+ if (p2.includes("\n")) out.set(p2, blobShaOrAbsent(worktreePath, head, p2));
227467
+ else batchable.push(p2);
227468
+ }
227469
+ for (const batch of chunk(batchable, PATHS_PER_BATCH)) {
227470
+ let lines = [];
227471
+ try {
227472
+ const stdin = batch.map((p2) => `${head}:${p2}`).join("\n") + "\n";
227473
+ lines = git(worktreePath, ["cat-file", "--batch-check"], stdin).split("\n").filter((l) => l.length > 0);
227474
+ } catch {
227475
+ lines = [];
227476
+ }
227477
+ if (lines.length !== batch.length) {
227478
+ for (const p2 of batch) out.set(p2, blobShaOrAbsent(worktreePath, head, p2));
227479
+ continue;
227480
+ }
227481
+ batch.forEach((p2, i) => {
227482
+ const found = BATCH_CHECK_FOUND.exec(lines[i]);
227483
+ out.set(p2, found ? found[1] : ABSENT);
227484
+ });
227485
+ }
227486
+ return out;
227487
+ }
227144
227488
  function computeScope(start, end, worktreePath) {
227145
227489
  const candidates = /* @__PURE__ */ new Set();
227146
227490
  if (start.head !== end.head) {
@@ -227160,18 +227504,29 @@ function computeScope(start, end, worktreePath) {
227160
227504
  }
227161
227505
  for (const p2 of Object.keys(start.dirty)) candidates.add(p2);
227162
227506
  for (const p2 of Object.keys(end.dirty)) candidates.add(p2);
227507
+ const candidateList = [...candidates];
227508
+ const startShas = blobShasAt(
227509
+ worktreePath,
227510
+ start.head,
227511
+ candidateList.filter((f2) => start.dirty[f2] === void 0)
227512
+ );
227513
+ const endShas = blobShasAt(
227514
+ worktreePath,
227515
+ end.head,
227516
+ candidateList.filter((f2) => end.dirty[f2] === void 0)
227517
+ );
227163
227518
  const changed = [];
227164
- for (const f2 of candidates) {
227165
- const startSha = start.dirty[f2] ?? blobShaOrAbsent(worktreePath, start.head, f2);
227166
- const endSha = end.dirty[f2] ?? blobShaOrAbsent(worktreePath, end.head, f2);
227519
+ for (const f2 of candidateList) {
227520
+ const startSha = start.dirty[f2] ?? startShas.get(f2) ?? ABSENT;
227521
+ const endSha = end.dirty[f2] ?? endShas.get(f2) ?? ABSENT;
227167
227522
  if (startSha !== endSha) changed.push(f2);
227168
227523
  }
227169
227524
  changed.sort();
227170
227525
  return { changedFiles: changed, startHead: start.head };
227171
227526
  }
227172
- async function recordTurnSnapshot(storage, sessionId, turnEndIndex, worktreePath) {
227527
+ async function recordTurnSnapshot(storage, sessionId, turnEndIndex, worktreePath, captured) {
227173
227528
  try {
227174
- const snap = captureSnapshot(worktreePath);
227529
+ const snap = captured ?? captureSnapshot(worktreePath);
227175
227530
  if (!snap) return;
227176
227531
  await storage.turnSnapshots.create({
227177
227532
  session_id: sessionId,
@@ -227809,7 +228164,7 @@ var AgentSessionManager = class {
227809
228164
  });
227810
228165
  }
227811
228166
  if (!skipDb && !stored) {
227812
- await recordTurnSnapshot(this.storage, sessionId, -1, absoluteWorktreePath);
228167
+ await recordTurnSnapshot(this.storage, sessionId, -1, absoluteWorktreePath, opts.startSnapshot);
227813
228168
  }
227814
228169
  const storedEntries = stored ? await this.storage.agentSessions.getEntries(sessionId) : [];
227815
228170
  const store = storedEntries.length > 0 ? this.rebuildStoreFromRows(storedEntries, sessionId) : (() => {
@@ -230003,19 +230358,19 @@ var RemoteNotificationSync = class {
230003
230358
  }
230004
230359
  async syncMappings(remoteServerId, mappings) {
230005
230360
  for (let i = 0; i < mappings.length; i += MAX_SESSIONS_PER_REQUEST) {
230006
- const chunk = mappings.slice(i, i + MAX_SESSIONS_PER_REQUEST);
230007
- await this.syncChunk(remoteServerId, chunk).catch(
230361
+ const chunk2 = mappings.slice(i, i + MAX_SESSIONS_PER_REQUEST);
230362
+ await this.syncChunk(remoteServerId, chunk2).catch(
230008
230363
  (err) => console.warn(`[RemoteNotifications] chunk sync for ${remoteServerId} failed:`, err)
230009
230364
  );
230010
230365
  }
230011
230366
  }
230012
- async syncChunk(remoteServerId, chunk) {
230013
- const target = await this.resolveTarget(chunk[0]);
230367
+ async syncChunk(remoteServerId, chunk2) {
230368
+ const target = await this.resolveTarget(chunk2[0]);
230014
230369
  if (!target) {
230015
- console.warn(`[RemoteNotifications] no remote link for server ${remoteServerId}; skipping ${chunk.length} mapping(s)`);
230370
+ console.warn(`[RemoteNotifications] no remote link for server ${remoteServerId}; skipping ${chunk2.length} mapping(s)`);
230016
230371
  return;
230017
230372
  }
230018
- let pending = new Map(chunk.map((m2) => [m2.remote_session_id, m2]));
230373
+ let pending = new Map(chunk2.map((m2) => [m2.remote_session_id, m2]));
230019
230374
  for (let page = 0; page < MAX_PAGES_PER_SYNC && pending.size > 0; page++) {
230020
230375
  const cursors = await this.storage.notificationSyncCursors.getMany(
230021
230376
  remoteServerId,
@@ -234316,19 +234671,19 @@ function boundedRecentMessagesKeeping(messages, pinned, limit, maxUtf8Bytes) {
234316
234671
  function splitUtf8Content(content, maxUtf8Bytes) {
234317
234672
  if (Buffer.byteLength(content, "utf8") <= maxUtf8Bytes) return [content];
234318
234673
  const chunks = [];
234319
- let chunk = "";
234674
+ let chunk2 = "";
234320
234675
  let bytes = 0;
234321
234676
  for (const character of content) {
234322
234677
  const characterBytes = Buffer.byteLength(character, "utf8");
234323
- if (bytes + characterBytes > maxUtf8Bytes && chunk) {
234324
- chunks.push(chunk);
234325
- chunk = "";
234678
+ if (bytes + characterBytes > maxUtf8Bytes && chunk2) {
234679
+ chunks.push(chunk2);
234680
+ chunk2 = "";
234326
234681
  bytes = 0;
234327
234682
  }
234328
- chunk += character;
234683
+ chunk2 += character;
234329
234684
  bytes += characterBytes;
234330
234685
  }
234331
- if (chunk) chunks.push(chunk);
234686
+ if (chunk2) chunks.push(chunk2);
234332
234687
  return chunks;
234333
234688
  }
234334
234689
  var ProjectChatNotFoundError = class extends Error {
@@ -236541,8 +236896,9 @@ var WorkflowEngine = class {
236541
236896
  return run2;
236542
236897
  }
236543
236898
  let scope = null;
236899
+ let endSnap = null;
236544
236900
  try {
236545
- const endSnap = captureSnapshot(worktreePath);
236901
+ endSnap = captureSnapshot(worktreePath);
236546
236902
  const startSnap = await resolveStartSnapshot(
236547
236903
  this.storage,
236548
236904
  opts.sourceSessionId,
@@ -236561,7 +236917,9 @@ var WorkflowEngine = class {
236561
236917
  false,
236562
236918
  "plan",
236563
236919
  opts.reviewerAgentType ?? "claude-code",
236564
- true
236920
+ true,
236921
+ false,
236922
+ { startSnapshot: endSnap }
236565
236923
  );
236566
236924
  const taskContext = extractTaskContextBefore(entries, turnEndIndex);
236567
236925
  await this.agentOps.setFinalSessionTitle(
@@ -239736,6 +240094,23 @@ var process_routes_default = (0, import_fastify_plugin9.default)(routes8, { name
239736
240094
  // src/routes/worktree-routes.ts
239737
240095
  var import_fastify_plugin10 = __toESM(require_plugin2(), 1);
239738
240096
  import { mkdir as mkdir3 } from "fs/promises";
240097
+
240098
+ // src/utils/path-project.ts
240099
+ async function ensurePathProjectId(fastify2, projectPath) {
240100
+ const pseudoProjectId = `path:${projectPath}`;
240101
+ if (await fastify2.storage.projects.getById(pseudoProjectId)) return pseudoProjectId;
240102
+ const existingByPath = await fastify2.storage.projects.getByPath(projectPath);
240103
+ if (existingByPath) return existingByPath.id;
240104
+ const name25 = projectPath.split("/").filter(Boolean).pop() || projectPath;
240105
+ try {
240106
+ await fastify2.storage.projects.create({ id: pseudoProjectId, name: name25, path: projectPath });
240107
+ } catch (err) {
240108
+ if (!(err instanceof Error && err.message.includes("UNIQUE constraint failed"))) throw err;
240109
+ }
240110
+ return pseudoProjectId;
240111
+ }
240112
+
240113
+ // src/routes/worktree-routes.ts
239739
240114
  async function getAllRemoteConfigs(fastify2, project) {
239740
240115
  const remotes = await fastify2.storage.projectRemotes.getByProject(project.id);
239741
240116
  return remotes.map((r) => ({
@@ -239747,6 +240122,12 @@ async function getRemoteConfig(fastify2, project) {
239747
240122
  const all = await getAllRemoteConfigs(fastify2, project);
239748
240123
  return all.length > 0 ? all[0] : null;
239749
240124
  }
240125
+ async function ensurePathProject(fastify2, projectPath) {
240126
+ const projectId = await ensurePathProjectId(fastify2, projectPath);
240127
+ const project = await fastify2.storage.projects.getById(projectId);
240128
+ if (!project) throw new Error(`Path project '${projectId}' was not persisted`);
240129
+ return project;
240130
+ }
239750
240131
  var routes9 = async (fastify2) => {
239751
240132
  fastify2.get("/api/path/branches", async (req, reply) => {
239752
240133
  const projectPath = req.query.path;
@@ -239774,7 +240155,8 @@ var routes9 = async (fastify2) => {
239774
240155
  }
239775
240156
  try {
239776
240157
  pruneWorktrees(projectPath);
239777
- const worktrees = getWorktreeBranches(projectPath);
240158
+ const project = await ensurePathProject(fastify2, projectPath);
240159
+ const worktrees = await getRegisteredWorktreeBranches(fastify2.storage, project.id, projectPath);
239778
240160
  return reply.code(200).send({ worktrees });
239779
240161
  } catch (error48) {
239780
240162
  const errorMessage = error48 instanceof Error ? error48.message : "Unknown error";
@@ -239796,6 +240178,7 @@ var routes9 = async (fastify2) => {
239796
240178
  return reply.code(400).send({ error: "Invalid base branch name format" });
239797
240179
  }
239798
240180
  console.log(`[worktree] ${requestId} Creating: branch=${trimmedBranch}, base=${startPoint}, path=${projectPath}`);
240181
+ let pendingWorkspaceId = null;
239799
240182
  try {
239800
240183
  const { execFileSync: execFileSync7 } = await import("child_process");
239801
240184
  try {
@@ -239808,6 +240191,15 @@ var routes9 = async (fastify2) => {
239808
240191
  } catch {
239809
240192
  }
239810
240193
  const worktreeAbsolutePath = resolveWorktreePath(projectPath, trimmedBranch);
240194
+ const project = await ensurePathProject(fastify2, projectPath);
240195
+ const pending = await fastify2.storage.workspaceRegistry.beginCheckout({
240196
+ projectId: project.id,
240197
+ branch: trimmedBranch,
240198
+ targetId: "local",
240199
+ worktreePath: worktreeAbsolutePath,
240200
+ expectedBranch: trimmedBranch
240201
+ });
240202
+ pendingWorkspaceId = pending.workspace.id;
239811
240203
  await mkdir3(getWorktreeBaseForProject(projectPath), { recursive: true });
239812
240204
  execFileSync7("git", ["worktree", "add", "-b", trimmedBranch, worktreeAbsolutePath, startPoint], {
239813
240205
  cwd: projectPath,
@@ -239815,12 +240207,16 @@ var routes9 = async (fastify2) => {
239815
240207
  stdio: ["pipe", "pipe", "pipe"]
239816
240208
  });
239817
240209
  invalidateWorktreeListCache(projectPath);
240210
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pending.workspace.id, "local", "ready");
239818
240211
  console.log(`[worktree] ${requestId} Created: branch=${trimmedBranch}`);
239819
240212
  return reply.code(201).send({
239820
240213
  worktree: { branch: trimmedBranch }
239821
240214
  });
239822
240215
  } catch (error48) {
239823
240216
  const errorMessage = error48 instanceof Error ? error48.message : "Unknown error";
240217
+ if (pendingWorkspaceId) {
240218
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pendingWorkspaceId, "local", "error", errorMessage).catch((registryError) => console.error("[worktree] Failed to record checkout error:", registryError));
240219
+ }
239824
240220
  const stderr = error48?.stderr || "";
239825
240221
  console.error(`[worktree] ${requestId} Failed: ${errorMessage}${stderr ? `, stderr: ${stderr}` : ""}`);
239826
240222
  return reply.code(500).send({ error: `Failed to create worktree: ${errorMessage}` });
@@ -239834,6 +240230,12 @@ var routes9 = async (fastify2) => {
239834
240230
  if (!/^[a-zA-Z0-9]/.test(branch) || /[^a-zA-Z0-9/_-]/.test(branch)) {
239835
240231
  return reply.code(400).send({ error: "Invalid branch name format" });
239836
240232
  }
240233
+ const pathProject = await fastify2.storage.projects.getByPath(projectPath);
240234
+ const registered = pathProject ? await fastify2.storage.workspaceRegistry.getByProjectBranch(pathProject.id, branch, "local") : void 0;
240235
+ if (registered) {
240236
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, "local", "deleting");
240237
+ }
240238
+ let worktreeRemoved = false;
239837
240239
  try {
239838
240240
  const { execSync: execSync2, execFileSync: execFileSync7 } = await import("child_process");
239839
240241
  const worktreeAbsPath = resolveWorktreePath(projectPath, branch);
@@ -239844,6 +240246,9 @@ var routes9 = async (fastify2) => {
239844
240246
  stdio: ["pipe", "pipe", "pipe"]
239845
240247
  });
239846
240248
  if (statusOutput.trim() !== "") {
240249
+ if (registered) {
240250
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, "local", "ready");
240251
+ }
239847
240252
  return reply.code(409).send({
239848
240253
  error: "Worktree has uncommitted changes"
239849
240254
  });
@@ -239862,6 +240267,7 @@ var routes9 = async (fastify2) => {
239862
240267
  encoding: "utf-8",
239863
240268
  stdio: ["pipe", "pipe", "pipe"]
239864
240269
  });
240270
+ worktreeRemoved = true;
239865
240271
  invalidateWorktreeListCache(projectPath);
239866
240272
  if (branchToDelete) {
239867
240273
  try {
@@ -239873,9 +240279,15 @@ var routes9 = async (fastify2) => {
239873
240279
  } catch {
239874
240280
  }
239875
240281
  }
240282
+ if (registered) {
240283
+ await fastify2.storage.workspaceRegistry.removeCheckout(registered.workspace.id, "local");
240284
+ }
239876
240285
  return reply.code(200).send({ success: true });
239877
240286
  } catch (error48) {
239878
240287
  const errorMessage = error48 instanceof Error ? error48.message : "Unknown error";
240288
+ if (registered && !worktreeRemoved) {
240289
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, "local", "error", errorMessage).catch((registryError) => console.error("[worktree] Failed to record delete error:", registryError));
240290
+ }
239879
240291
  return reply.code(500).send({ error: `Failed to delete worktree: ${errorMessage}` });
239880
240292
  }
239881
240293
  });
@@ -239915,7 +240327,7 @@ var routes9 = async (fastify2) => {
239915
240327
  }
239916
240328
  try {
239917
240329
  pruneWorktrees(project.path);
239918
- const worktrees = getWorktreeBranches(project.path);
240330
+ const worktrees = await getRegisteredWorktreeBranches(fastify2.storage, project.id, project.path);
239919
240331
  return reply.code(200).send({ worktrees });
239920
240332
  } catch (error48) {
239921
240333
  const errorMessage = error48 instanceof Error ? error48.message : "Unknown error";
@@ -239987,13 +240399,44 @@ var routes9 = async (fastify2) => {
239987
240399
  const remoteConfigs = await getAllRemoteConfigs(fastify2, project);
239988
240400
  const hasRemote = remoteConfigs.length > 0;
239989
240401
  const deleteOnRemote = async (rc) => {
239990
- return proxyToRemoteAuto(
239991
- rc.serverId,
239992
- "DELETE",
239993
- `/api/path/worktrees`,
239994
- { path: rc.remotePath, branch },
239995
- { reverseConnectManager: fastify2.reverseConnectManager }
239996
- );
240402
+ const registered = await fastify2.storage.workspaceRegistry.getByProjectBranch(project.id, branch, rc.serverId);
240403
+ const restorePreviousStatus = async () => {
240404
+ if (!registered) return;
240405
+ const current = await fastify2.storage.workspaceRegistry.getByProjectBranch(project.id, branch, rc.serverId);
240406
+ if (!current || current.checkout.status !== "deleting") return;
240407
+ await fastify2.storage.workspaceRegistry.setCheckoutStatusIfCurrent(
240408
+ registered.workspace.id,
240409
+ rc.serverId,
240410
+ { status: "deleting", updatedAt: current.checkout.updated_at },
240411
+ registered.checkout.status,
240412
+ registered.checkout.error
240413
+ );
240414
+ };
240415
+ if (registered) {
240416
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, rc.serverId, "deleting");
240417
+ }
240418
+ try {
240419
+ const result = await proxyToRemoteAuto(
240420
+ rc.serverId,
240421
+ "DELETE",
240422
+ `/api/path/worktrees`,
240423
+ { path: rc.remotePath, branch },
240424
+ { reverseConnectManager: fastify2.reverseConnectManager }
240425
+ );
240426
+ if (registered) {
240427
+ if (result.ok) {
240428
+ await fastify2.storage.workspaceRegistry.removeCheckout(registered.workspace.id, rc.serverId);
240429
+ } else {
240430
+ await restorePreviousStatus();
240431
+ }
240432
+ }
240433
+ return result;
240434
+ } catch (error48) {
240435
+ if (registered) {
240436
+ await restorePreviousStatus().catch((registryError) => console.error("[worktree] Failed to restore remote checkout status:", registryError));
240437
+ }
240438
+ throw error48;
240439
+ }
239997
240440
  };
239998
240441
  if (!hasLocal && hasRemote) {
239999
240442
  if (remoteConfigs.length === 1) {
@@ -240030,40 +240473,58 @@ var routes9 = async (fastify2) => {
240030
240473
  const deleteLocal = async () => {
240031
240474
  const { execSync: execSync2, execFileSync: execFileSync7 } = await import("child_process");
240032
240475
  const worktreeAbsPath = resolveWorktreePath(project.path, branch);
240033
- try {
240034
- const statusOutput = execSync2("git status --porcelain", {
240035
- cwd: worktreeAbsPath,
240036
- encoding: "utf-8",
240037
- stdio: ["pipe", "pipe", "pipe"]
240038
- });
240039
- if (statusOutput.trim() !== "") {
240040
- throw new Error("Worktree has uncommitted changes. Please commit or discard changes before deleting.");
240041
- }
240042
- } catch (err) {
240043
- if (err instanceof Error && err.message.includes("uncommitted changes")) throw err;
240476
+ const registered = await fastify2.storage.workspaceRegistry.getByProjectBranch(project.id, branch, "local");
240477
+ if (registered) {
240478
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, "local", "deleting");
240044
240479
  }
240045
- let branchToDelete = null;
240480
+ let worktreeRemoved = false;
240046
240481
  try {
240047
- const entries = parseGitWorktreeList(project.path);
240048
- const match2 = entries.find((e) => e.path === worktreeAbsPath);
240049
- if (match2) branchToDelete = match2.branch;
240050
- } catch {
240051
- }
240052
- execFileSync7("git", ["worktree", "remove", worktreeAbsPath], {
240053
- cwd: project.path,
240054
- encoding: "utf-8",
240055
- stdio: ["pipe", "pipe", "pipe"]
240056
- });
240057
- invalidateWorktreeListCache(project.path);
240058
- if (branchToDelete) {
240059
240482
  try {
240060
- execFileSync7("git", ["branch", "-d", branchToDelete], {
240061
- cwd: project.path,
240483
+ const statusOutput = execSync2("git status --porcelain", {
240484
+ cwd: worktreeAbsPath,
240062
240485
  encoding: "utf-8",
240063
240486
  stdio: ["pipe", "pipe", "pipe"]
240064
240487
  });
240488
+ if (statusOutput.trim() !== "") {
240489
+ throw new Error("Worktree has uncommitted changes. Please commit or discard changes before deleting.");
240490
+ }
240491
+ } catch (err) {
240492
+ if (err instanceof Error && err.message.includes("uncommitted changes")) throw err;
240493
+ }
240494
+ let branchToDelete = null;
240495
+ try {
240496
+ const entries = parseGitWorktreeList(project.path);
240497
+ const match2 = entries.find((e) => e.path === worktreeAbsPath);
240498
+ if (match2) branchToDelete = match2.branch;
240065
240499
  } catch {
240066
240500
  }
240501
+ execFileSync7("git", ["worktree", "remove", worktreeAbsPath], {
240502
+ cwd: project.path,
240503
+ encoding: "utf-8",
240504
+ stdio: ["pipe", "pipe", "pipe"]
240505
+ });
240506
+ worktreeRemoved = true;
240507
+ invalidateWorktreeListCache(project.path);
240508
+ if (branchToDelete) {
240509
+ try {
240510
+ execFileSync7("git", ["branch", "-d", branchToDelete], {
240511
+ cwd: project.path,
240512
+ encoding: "utf-8",
240513
+ stdio: ["pipe", "pipe", "pipe"]
240514
+ });
240515
+ } catch {
240516
+ }
240517
+ }
240518
+ if (registered) {
240519
+ await fastify2.storage.workspaceRegistry.removeCheckout(registered.workspace.id, "local");
240520
+ }
240521
+ } catch (error48) {
240522
+ if (registered && !worktreeRemoved) {
240523
+ const message = error48 instanceof Error ? error48.message : "Local deletion failed";
240524
+ const status = message.includes("uncommitted changes") ? "ready" : "error";
240525
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(registered.workspace.id, "local", status, status === "error" ? message : null).catch((registryError) => console.error("[worktree] Failed to record local delete error:", registryError));
240526
+ }
240527
+ throw error48;
240067
240528
  }
240068
240529
  };
240069
240530
  if (!hasRemote) {
@@ -240150,13 +240611,47 @@ var routes9 = async (fastify2) => {
240150
240611
  return reply.code(400).send({ error: "Project has no remote configuration" });
240151
240612
  }
240152
240613
  const createOnRemote = async (rc) => {
240153
- return proxyToRemoteAuto(
240154
- rc.serverId,
240155
- "POST",
240156
- `/api/path/worktrees`,
240157
- { path: rc.remotePath, branchName: trimmedBranch, baseBranch: remoteStartPoint },
240158
- { reverseConnectManager: fastify2.reverseConnectManager }
240159
- );
240614
+ const previous = await fastify2.storage.workspaceRegistry.getByProjectBranch(project.id, trimmedBranch, rc.serverId);
240615
+ const preserveReady = previous?.checkout.status === "ready";
240616
+ const pending = preserveReady && previous ? previous : await fastify2.storage.workspaceRegistry.beginCheckout({
240617
+ projectId: project.id,
240618
+ branch: trimmedBranch,
240619
+ targetId: rc.serverId,
240620
+ worktreePath: conventionalWorktreePath(rc.remotePath, trimmedBranch),
240621
+ expectedBranch: trimmedBranch
240622
+ });
240623
+ try {
240624
+ const result = await proxyToRemoteAuto(
240625
+ rc.serverId,
240626
+ "POST",
240627
+ `/api/path/worktrees`,
240628
+ { path: rc.remotePath, branchName: trimmedBranch, baseBranch: remoteStartPoint },
240629
+ { reverseConnectManager: fastify2.reverseConnectManager }
240630
+ );
240631
+ if (result.ok) {
240632
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pending.workspace.id, rc.serverId, "ready");
240633
+ } else if (preserveReady) {
240634
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pending.workspace.id, rc.serverId, "ready");
240635
+ } else {
240636
+ const detail = result.data;
240637
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(
240638
+ pending.workspace.id,
240639
+ rc.serverId,
240640
+ "error",
240641
+ detail.error ?? result.errorCode ?? "Remote creation failed"
240642
+ );
240643
+ }
240644
+ return result;
240645
+ } catch (error48) {
240646
+ const message = error48 instanceof Error ? error48.message : "Remote creation failed";
240647
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(
240648
+ pending.workspace.id,
240649
+ rc.serverId,
240650
+ preserveReady ? "ready" : "error",
240651
+ preserveReady ? null : message
240652
+ ).catch((registryError) => console.error("[worktree] Failed to record remote checkout error:", registryError));
240653
+ throw error48;
240654
+ }
240160
240655
  };
240161
240656
  if (targets.length === 1 && targets[0] === "remote") {
240162
240657
  if (remoteConfigs.length === 1) {
@@ -240207,14 +240702,28 @@ var routes9 = async (fastify2) => {
240207
240702
  if (err instanceof Error && err.message.includes("already exists")) throw err;
240208
240703
  }
240209
240704
  const worktreeAbsolutePath = resolveWorktreePath(project.path, trimmedBranch);
240210
- await mkdir3(getWorktreeBaseForProject(project.path), { recursive: true });
240211
- execFileSync7("git", ["worktree", "add", "-b", trimmedBranch, worktreeAbsolutePath, localStartPoint], {
240212
- cwd: project.path,
240213
- encoding: "utf-8",
240214
- stdio: ["pipe", "pipe", "pipe"]
240705
+ const pending = await fastify2.storage.workspaceRegistry.beginCheckout({
240706
+ projectId: project.id,
240707
+ branch: trimmedBranch,
240708
+ targetId: "local",
240709
+ worktreePath: worktreeAbsolutePath,
240710
+ expectedBranch: trimmedBranch
240215
240711
  });
240216
- invalidateWorktreeListCache(project.path);
240217
- return { branch: trimmedBranch };
240712
+ try {
240713
+ await mkdir3(getWorktreeBaseForProject(project.path), { recursive: true });
240714
+ execFileSync7("git", ["worktree", "add", "-b", trimmedBranch, worktreeAbsolutePath, localStartPoint], {
240715
+ cwd: project.path,
240716
+ encoding: "utf-8",
240717
+ stdio: ["pipe", "pipe", "pipe"]
240718
+ });
240719
+ invalidateWorktreeListCache(project.path);
240720
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pending.workspace.id, "local", "ready");
240721
+ return { branch: trimmedBranch };
240722
+ } catch (error48) {
240723
+ const message = error48 instanceof Error ? error48.message : "Local creation failed";
240724
+ await fastify2.storage.workspaceRegistry.setCheckoutStatus(pending.workspace.id, "local", "error", message).catch((registryError) => console.error("[worktree] Failed to record local checkout error:", registryError));
240725
+ throw error48;
240726
+ }
240218
240727
  };
240219
240728
  if (targets.length === 1 && targets[0] === "local") {
240220
240729
  try {
@@ -240425,8 +240934,8 @@ function computeBranchMergeStatus(repoPath, branch, target) {
240425
240934
  const missing = !branchTip ? branch : target;
240426
240935
  throw Object.assign(new Error(`Branch not found: ${missing}`), { statusCode: 400 });
240427
240936
  }
240428
- const cacheKey = `${repoPath}\0${branch}\0${target}`;
240429
- const cached2 = statusCache.get(cacheKey);
240937
+ const cacheKey2 = `${repoPath}\0${branch}\0${target}`;
240938
+ const cached2 = statusCache.get(cacheKey2);
240430
240939
  if (cached2 && cached2.branchTip === branchTip && cached2.targetTip === targetTip) {
240431
240940
  return { status: cached2.status, unmergedCount: cached2.unmergedCount };
240432
240941
  }
@@ -240448,7 +240957,7 @@ function computeBranchMergeStatus(repoPath, branch, target) {
240448
240957
  unmergedCount = 0;
240449
240958
  }
240450
240959
  }
240451
- statusCache.set(cacheKey, { branchTip, targetTip, status, unmergedCount });
240960
+ statusCache.set(cacheKey2, { branchTip, targetTip, status, unmergedCount });
240452
240961
  return { status, unmergedCount };
240453
240962
  }
240454
240963
  function isDirty2(worktreePath) {
@@ -241592,8 +242101,355 @@ async function writePasteToTempFile(content) {
241592
242101
  return { path: filePath, size: Buffer.byteLength(content, "utf8") };
241593
242102
  }
241594
242103
 
242104
+ // src/utils/review-brief.ts
242105
+ import { createHash as createHash5 } from "crypto";
242106
+ var BASE_TIMEOUT_MS = 15e3;
242107
+ var JUDGMENT_TIMEOUT_MS = 9e4;
242108
+ var TIMEOUT_MS_PER_1K_CHARS = 120;
242109
+ var MAX_TIMEOUT_MS = 6e4;
242110
+ var PER_MESSAGE_MAX_CHARS = 6e3;
242111
+ var COMPACT_TRIGGER_CHARS = 12e4;
242112
+ var COMPACT_SLICE_BUDGETS = [96e3, 24e3, 6e3];
242113
+ var RECENT_VERBATIM_RATIO = 0.3;
242114
+ var MIN_RECENT_VERBATIM_CHARS = 2e3;
242115
+ var MAX_FOLD_CALLS = 8;
242116
+ var COMPACT_SUMMARY_MAX_CHARS = 6e3;
242117
+ var COMPACT_SUMMARY_MAX_TOKENS = 3e3;
242118
+ var REVERSALS_MAX_CHARS = 2e3;
242119
+ var REVERSALS_MAX_TOKENS = 2e3;
242120
+ var BRIEF_MAX_CHARS = 4e3;
242121
+ var BRIEF_MAX_TOKENS = 3e3;
242122
+ var REVERSAL_MIN_CHARS = 6e3;
242123
+ var SEP = "\n\n";
242124
+ var COMPACTION_NOTE = "_Note: the source conversation was compressed before distillation \u2014 older turns were summarized rather than read verbatim._";
242125
+ var BRIEF_TRUNCATION_NOTE = "\n\n_[brief truncated at the length limit \u2014 treat it as incomplete]_";
242126
+ var SYSTEM_PROMPT2 = [
242127
+ "You distill a coding-agent conversation into an intent brief for an independent code reviewer.",
242128
+ "The reviewer will NOT see the conversation \u2014 only your brief plus the actual code, so capture what the code alone cannot show:",
242129
+ "0. Dominant question \u2014 1 or 2 sentences: the single question the reviewer must answer to judge this work (what must actually work, toward what goal). Derive it from the conversation's own emphasis \u2014 what the user repeated, finally decided, or reversed course over \u2014 never from your own engineering judgment. If the conversation does not clearly support one, write 'unclear' instead of inventing one.",
242130
+ "1. The original request and its goal.",
242131
+ "2. Hard constraints \u2014 requirements whose violation the user would treat as failure regardless of everything else (security, data loss, an explicit compatibility or behaviour promise). Only list ones the user actually stated; an empty section is fine.",
242132
+ "3. Constraints and decisions, including approaches that were rejected and why. A rejection counts whether the user made it or the agent made it under a principle the user set.",
242133
+ "4. Non-goals, trade-offs and limitations that were acknowledged and accepted.",
242134
+ "5. Behaviour established by actually running something \u2014 observed output, exit codes, error text, which stream an error arrived on. Report what was observed; that is evidence the reviewer cannot recover by reading code.",
242135
+ "Tag every item under headings 3 and 4 with exactly [settled] or [tentative] \u2014 the bare tag; keep any justification to a few words or omit it, always after the tag, never inside the brackets. Settled ONLY when the user explicitly confirmed it, instructed it, or reversed course to it; an agent proposal the user never answered is tentative \u2014 silence is never settled.",
242136
+ "Within each heading, order items by how much they matter to the dominant question, not by when they were said.",
242137
+ "Later statements supersede earlier ones on the same topic. An option explored at length early is often rejected later in a single sentence, and the rejection wins. Where the conversation ends in a decision table or summary, that is authoritative wherever it conflicts with earlier prose.",
242138
+ "The input may arrive as numbered compressed slices followed by verbatim recent turns. Slice numbers are chronological: a later slice overrules an earlier one.",
242139
+ "Decisions the agent made that the user did not contradict are worth reporting, but user silence only ever yields tentative status.",
242140
+ "Do NOT include the agent's self-assessment or any claim that the work is correct or complete \u2014 the reviewer must judge that independently.",
242141
+ "Every statement must trace to something in the conversation. If a heading has nothing real to report, say so rather than inventing plausible-sounding content.",
242142
+ "Write concise markdown bullets under those numbered headings, under 500 words total, in the same language as the conversation. Reply with the brief only."
242143
+ ].join("\n");
242144
+ var REVERSAL_SYSTEM_PROMPT = [
242145
+ "You read a coding-agent conversation and report ONLY the conclusions that were later reversed, dropped, or replaced.",
242146
+ "A design conversation converges by killing its own hypotheses: an option explored in depth early is often rejected later in one sentence, so weigh finality over how much was written.",
242147
+ "A reversal counts whether the user or the agent made it. Ignore rewording that leaves the decision intact.",
242148
+ "Output one line per reversal: SUPERSEDED: <what was concluded earlier> -> <what replaced it> (<why>)",
242149
+ "Report the most decisive reversals first and stay under 200 words \u2014 a list that runs long will be discarded whole, so prioritise rather than pad.",
242150
+ "If nothing was reversed, reply with exactly: NONE"
242151
+ ].join("\n");
242152
+ var COMPACT_SYSTEM_PROMPT = [
242153
+ "You compress one slice of a coding-agent conversation. A later pass will distill the whole thing into an intent brief for a code reviewer.",
242154
+ "You are told which slice of how many this is. Other slices are compressed separately and you cannot see them, so never present a conclusion here as final \u2014 a later slice may overturn it.",
242155
+ "Preserve, in this order of priority:",
242156
+ "1. Reversals and corrections \u2014 any conclusion that was dropped, replaced, or corrected. Quote the deciding sentence verbatim.",
242157
+ "2. Constraints and decisions the user stated, and approaches that were rejected, with the reason. Preserve who made each decision \u2014 an explicit user confirmation must stay distinguishable from an agent proposal the user never answered; quote the user's deciding sentence when there is one.",
242158
+ "3. Behaviour established by actually running something: observed output, exit codes, error text, which stream an error arrived on.",
242159
+ "4. Trade-offs that were acknowledged and accepted.",
242160
+ "Drop: exploration narrative, restated background, tool mechanics, and anything a reviewer could recover by reading the code.",
242161
+ "Stay under 800 words. An over-long slice is discarded whole rather than cut short, so drop lower-priority material instead of running over.",
242162
+ "Keep the conversation's own language. Reply with the compressed slice only, no preamble."
242163
+ ].join("\n");
242164
+ function timeoutForInput(chars) {
242165
+ return Math.min(MAX_TIMEOUT_MS, BASE_TIMEOUT_MS + Math.floor(chars / 1e3) * TIMEOUT_MS_PER_1K_CHARS);
242166
+ }
242167
+ function isSizeRelatedFailure(error48) {
242168
+ const err = error48;
242169
+ if (err?.name === "AbortError" || err?.name === "TimeoutError") return true;
242170
+ const message = err?.message ?? "";
242171
+ return /context[ _-]?length|maximum context|too many tokens|token limit|prompt is too long|request too large|timed? ?out/i.test(
242172
+ message
242173
+ );
242174
+ }
242175
+ function withinLimit(text2, max, label) {
242176
+ if (text2.length <= max) return true;
242177
+ console.warn(`[ReviewBrief] ${label} ran to ${text2.length} chars (limit ${max}) \u2014 discarding rather than truncating`);
242178
+ return false;
242179
+ }
242180
+ function capMessage(text2) {
242181
+ return text2.length > PER_MESSAGE_MAX_CHARS ? text2.slice(0, PER_MESSAGE_MAX_CHARS) + "\u2026" : text2;
242182
+ }
242183
+ function toEntries(messages) {
242184
+ const entries = [];
242185
+ for (const msg of messages) {
242186
+ if (!msg) continue;
242187
+ if (msg.type === "user" && !msg.event) {
242188
+ const text2 = extractUserText(msg.content).trim();
242189
+ if (text2) entries.push({ role: "User", text: capMessage(text2) });
242190
+ } else if (msg.type === "assistant" && typeof msg.content === "string") {
242191
+ const text2 = msg.content.trim();
242192
+ if (text2) entries.push({ role: "Agent", text: capMessage(text2) });
242193
+ }
242194
+ }
242195
+ return entries;
242196
+ }
242197
+ function render(entry) {
242198
+ return `${entry.role}: ${entry.text}`;
242199
+ }
242200
+ function renderAll(entries) {
242201
+ return entries.map(render).join(SEP);
242202
+ }
242203
+ function serializeConversationForBrief(messages) {
242204
+ return renderAll(toEntries(messages));
242205
+ }
242206
+ function projectMessagesForBrief(messages) {
242207
+ return toEntries(messages).map(
242208
+ (entry) => entry.role === "User" ? { type: "user", content: entry.text, timestamp: 0 } : { type: "assistant", content: entry.text, timestamp: 0 }
242209
+ );
242210
+ }
242211
+ function splitRecent(entries, maxChars) {
242212
+ let size = 0;
242213
+ let i = entries.length;
242214
+ while (i > 0) {
242215
+ const len = render(entries[i - 1]).length + SEP.length;
242216
+ if (size + len > maxChars) break;
242217
+ size += len;
242218
+ i--;
242219
+ }
242220
+ return { older: entries.slice(0, i), recent: entries.slice(i) };
242221
+ }
242222
+ function chunkEntries(entries, maxChars) {
242223
+ const chunks = [];
242224
+ let current = [];
242225
+ let size = 0;
242226
+ for (const entry of entries) {
242227
+ const len = render(entry).length + SEP.length;
242228
+ if (current.length > 0 && size + len > maxChars) {
242229
+ chunks.push(current);
242230
+ current = [];
242231
+ size = 0;
242232
+ }
242233
+ current.push(entry);
242234
+ size += len;
242235
+ }
242236
+ if (current.length > 0) chunks.push(current);
242237
+ return chunks;
242238
+ }
242239
+ function telemetryFor(functionId, userId) {
242240
+ return userId ? {
242241
+ isEnabled: true,
242242
+ functionId,
242243
+ metadata: { userId, tags: ["vibedeckx", functionId] }
242244
+ } : void 0;
242245
+ }
242246
+ async function compactChunk(model, chunk2, part, total, userId) {
242247
+ try {
242248
+ const result = await generateText({
242249
+ model,
242250
+ system: COMPACT_SYSTEM_PROMPT,
242251
+ prompt: `Slice ${part} of ${total}.
242252
+
242253
+ ${chunk2}`,
242254
+ timeout: timeoutForInput(chunk2.length),
242255
+ maxOutputTokens: COMPACT_SUMMARY_MAX_TOKENS,
242256
+ experimental_telemetry: telemetryFor("review-intent-brief-compact", userId)
242257
+ });
242258
+ const { text: rawText, finishReason } = result;
242259
+ if (finishReason === "length") {
242260
+ console.warn(`[ReviewBrief] slice ${part}/${total} summary hit the token cap \u2014 discarding`);
242261
+ return null;
242262
+ }
242263
+ const text2 = (rawText ?? "").trim();
242264
+ if (text2.length === 0) {
242265
+ console.warn(`[ReviewBrief] slice ${part}/${total} came back empty (finishReason: ${finishReason ?? "unknown"})`);
242266
+ return null;
242267
+ }
242268
+ return withinLimit(text2, COMPACT_SUMMARY_MAX_CHARS, `slice ${part}/${total} summary`) ? text2 : null;
242269
+ } catch (error48) {
242270
+ if (isSizeRelatedFailure(error48)) throw error48;
242271
+ console.warn(`[ReviewBrief] compaction of slice ${part}/${total} failed:`, error48.message);
242272
+ return null;
242273
+ }
242274
+ }
242275
+ async function compactConversation(model, messages, options = {}) {
242276
+ const sliceChars = options.sliceChars ?? COMPACT_SLICE_BUDGETS[0];
242277
+ const recentChars = Math.max(MIN_RECENT_VERBATIM_CHARS, Math.floor(sliceChars * RECENT_VERBATIM_RATIO));
242278
+ const entries = toEntries(messages);
242279
+ if (entries.length === 0) return null;
242280
+ const { older, recent } = splitRecent(entries, recentChars);
242281
+ if (older.length === 0) return null;
242282
+ const chunks = chunkEntries(older, sliceChars);
242283
+ if (chunks.length > MAX_FOLD_CALLS) {
242284
+ console.warn(
242285
+ `[ReviewBrief] conversation needs ${chunks.length} slices of ${sliceChars} chars (max ${MAX_FOLD_CALLS}) \u2014 falling back to tier 2`
242286
+ );
242287
+ return null;
242288
+ }
242289
+ const settled = await Promise.allSettled(
242290
+ chunks.map((chunk2, i) => compactChunk(model, renderAll(chunk2), i + 1, chunks.length, options.userId))
242291
+ );
242292
+ const sizeRejection = settled.find((r) => r.status === "rejected" && isSizeRelatedFailure(r.reason));
242293
+ if (sizeRejection) throw sizeRejection.reason;
242294
+ if (settled.some((r) => r.status === "rejected" || r.value === null)) return null;
242295
+ const parts = settled.map(
242296
+ (r, i) => `[Compressed slice ${i + 1} of ${chunks.length}]
242297
+ ${r.value}`
242298
+ );
242299
+ if (recent.length > 0) parts.push(`[Recent turns, verbatim]
242300
+ ${renderAll(recent)}`);
242301
+ return parts.join(SEP);
242302
+ }
242303
+ function buildBriefPrompt(conversation, reversals) {
242304
+ const preamble = reversals ? "Conclusions this conversation reversed. The right-hand side is the current state \u2014 never report the left-hand side as what was decided:\n" + reversals + SEP : "";
242305
+ return `${preamble}Distill this conversation into an intent brief:
242306
+
242307
+ ${conversation}`;
242308
+ }
242309
+ function appendCompactionNote(brief, compacted) {
242310
+ return compacted ? `${brief}${SEP}${COMPACTION_NOTE}` : brief;
242311
+ }
242312
+ async function extractReversalsWithModel(model, conversation, options = {}) {
242313
+ if (conversation.trim().length < REVERSAL_MIN_CHARS) return null;
242314
+ try {
242315
+ const result = await generateText({
242316
+ model,
242317
+ system: REVERSAL_SYSTEM_PROMPT,
242318
+ prompt: `Report the reversals in this conversation:
242319
+
242320
+ ${conversation}`,
242321
+ timeout: JUDGMENT_TIMEOUT_MS,
242322
+ maxOutputTokens: REVERSALS_MAX_TOKENS,
242323
+ experimental_telemetry: telemetryFor("review-intent-brief-reversals", options.userId)
242324
+ });
242325
+ const { text: rawText, finishReason } = result;
242326
+ if (finishReason === "length") {
242327
+ console.warn("[ReviewBrief] reversal list hit the token cap \u2014 discarding");
242328
+ return null;
242329
+ }
242330
+ const text2 = (rawText ?? "").trim();
242331
+ if (text2.length === 0 || /^none\b/i.test(text2)) return null;
242332
+ return withinLimit(text2, REVERSALS_MAX_CHARS, "reversal list") ? text2 : null;
242333
+ } catch (error48) {
242334
+ if (!isSizeRelatedFailure(error48)) throw error48;
242335
+ console.warn("[ReviewBrief] reversal pass hit a size limit \u2014 skipping it:", error48.message);
242336
+ return null;
242337
+ }
242338
+ }
242339
+ async function generateIntentBriefWithModel(model, conversation, options = {}) {
242340
+ if (conversation.trim().length === 0) return null;
242341
+ try {
242342
+ const result = await generateText({
242343
+ model,
242344
+ system: SYSTEM_PROMPT2,
242345
+ prompt: buildBriefPrompt(conversation, options.reversals ?? null),
242346
+ timeout: JUDGMENT_TIMEOUT_MS,
242347
+ maxOutputTokens: BRIEF_MAX_TOKENS,
242348
+ experimental_telemetry: telemetryFor("review-intent-brief", options.userId)
242349
+ });
242350
+ const { text: rawText, finishReason } = result;
242351
+ const text2 = (rawText ?? "").trim();
242352
+ if (text2.length === 0) {
242353
+ console.warn(`[ReviewBrief] model returned empty text (finishReason: ${finishReason ?? "unknown"})`);
242354
+ return null;
242355
+ }
242356
+ if (finishReason === "length") return text2.slice(0, BRIEF_MAX_CHARS) + BRIEF_TRUNCATION_NOTE;
242357
+ return text2.length <= BRIEF_MAX_CHARS ? text2 : text2.slice(0, BRIEF_MAX_CHARS) + BRIEF_TRUNCATION_NOTE;
242358
+ } catch (error48) {
242359
+ if (options.rethrowSizeFailures && isSizeRelatedFailure(error48)) throw error48;
242360
+ console.warn("[ReviewBrief] AI generation failed:", error48.message);
242361
+ return null;
242362
+ }
242363
+ }
242364
+ async function distill(model, conversation, userId, rethrowSizeFailures) {
242365
+ const reversals = await extractReversalsWithModel(model, conversation, { userId });
242366
+ return generateIntentBriefWithModel(model, conversation, { userId, reversals, rethrowSizeFailures });
242367
+ }
242368
+ var BRIEF_CACHE_TTL_MS = 30 * 6e4;
242369
+ var BRIEF_CACHE_MAX_ENTRIES = 50;
242370
+ var briefCache = /* @__PURE__ */ new Map();
242371
+ var briefInFlight = /* @__PURE__ */ new Map();
242372
+ function cacheKey(userId, conversation) {
242373
+ return createHash5("sha256").update(userId).update("\0").update(conversation).digest("hex");
242374
+ }
242375
+ function readBriefCache(key) {
242376
+ const hit = briefCache.get(key);
242377
+ if (!hit) return null;
242378
+ if (Date.now() - hit.at > BRIEF_CACHE_TTL_MS) {
242379
+ briefCache.delete(key);
242380
+ return null;
242381
+ }
242382
+ return hit.brief;
242383
+ }
242384
+ function writeBriefCache(key, brief) {
242385
+ briefCache.set(key, { brief, at: Date.now() });
242386
+ while (briefCache.size > BRIEF_CACHE_MAX_ENTRIES) {
242387
+ const oldest = briefCache.keys().next();
242388
+ if (oldest.done) break;
242389
+ briefCache.delete(oldest.value);
242390
+ }
242391
+ }
242392
+ async function generateIntentBrief(storage, userId, messages) {
242393
+ let conversation;
242394
+ let mainOk;
242395
+ let fastOk;
242396
+ try {
242397
+ const config2 = await getChatProviderConfig(storage, userId);
242398
+ mainOk = isModelConfigured(config2, config2.main);
242399
+ fastOk = isModelConfigured(config2, config2.fast);
242400
+ if (!mainOk && !fastOk) return null;
242401
+ conversation = serializeConversationForBrief(messages);
242402
+ if (!conversation) return null;
242403
+ } catch (error48) {
242404
+ console.warn("[ReviewBrief] generation failed:", error48.message);
242405
+ return null;
242406
+ }
242407
+ const key = cacheKey(userId, conversation);
242408
+ const cached2 = readBriefCache(key);
242409
+ if (cached2 !== null) return cached2;
242410
+ const pending = briefInFlight.get(key);
242411
+ if (pending) return pending;
242412
+ const run2 = distillConversation(storage, userId, messages, conversation, mainOk, fastOk).then((brief) => {
242413
+ if (brief !== null) writeBriefCache(key, brief);
242414
+ return brief;
242415
+ }).finally(() => briefInFlight.delete(key));
242416
+ briefInFlight.set(key, run2);
242417
+ return run2;
242418
+ }
242419
+ async function distillConversation(storage, userId, messages, conversation, mainOk, fastOk) {
242420
+ try {
242421
+ const distillModel = mainOk ? await resolveChatModel(storage, userId) : await resolveFastChatModel(storage, userId);
242422
+ const compactModel = fastOk ? await resolveFastChatModel(storage, userId) : distillModel;
242423
+ if (conversation.length <= COMPACT_TRIGGER_CHARS) {
242424
+ try {
242425
+ const brief = await distill(distillModel, conversation, userId, true);
242426
+ return brief === null ? null : appendCompactionNote(brief, false);
242427
+ } catch (error48) {
242428
+ if (!isSizeRelatedFailure(error48)) throw error48;
242429
+ console.warn("[ReviewBrief] full conversation rejected as too large \u2014 compacting and retrying");
242430
+ }
242431
+ }
242432
+ for (const sliceChars of COMPACT_SLICE_BUDGETS) {
242433
+ try {
242434
+ const compacted = await compactConversation(compactModel, messages, { userId, sliceChars });
242435
+ if (compacted === null) return null;
242436
+ const brief = await distill(distillModel, compacted, userId, true);
242437
+ return brief === null ? null : appendCompactionNote(brief, true);
242438
+ } catch (error48) {
242439
+ if (!isSizeRelatedFailure(error48)) throw error48;
242440
+ console.warn(`[ReviewBrief] ${sliceChars}-char slices still too large \u2014 retrying smaller`);
242441
+ }
242442
+ }
242443
+ console.warn("[ReviewBrief] could not compact the conversation small enough \u2014 falling back to tier 2");
242444
+ return null;
242445
+ } catch (error48) {
242446
+ console.warn("[ReviewBrief] generation failed:", error48.message);
242447
+ return null;
242448
+ }
242449
+ }
242450
+
241595
242451
  // src/routes/agent-session-routes.ts
241596
- import { createHash as createHash5, randomUUID as randomUUID15 } from "crypto";
242452
+ import { createHash as createHash6, randomUUID as randomUUID15 } from "crypto";
241597
242453
 
241598
242454
  // src/protocol/model-suggestions.ts
241599
242455
  var MODEL_SUGGESTIONS = {
@@ -241639,7 +242495,7 @@ var routes12 = async (fastify2) => {
241639
242495
  }
241640
242496
  function instructionContentHash(content) {
241641
242497
  const canonical = typeof content === "string" ? JSON.stringify({ type: "string", content }) : JSON.stringify(content.map((part) => part.type === "text" ? { type: "text", text: part.text } : { type: "image", mediaType: part.mediaType, data: part.data }));
241642
- return createHash5("sha256").update(canonical).digest("hex");
242498
+ return createHash6("sha256").update(canonical).digest("hex");
241643
242499
  }
241644
242500
  function proxyAuto(remoteServerId, method, apiPath, body) {
241645
242501
  return proxyToRemoteAuto(remoteServerId, method, apiPath, body, {
@@ -242269,6 +243125,16 @@ var routes12 = async (fastify2) => {
242269
243125
  });
242270
243126
  }
242271
243127
  );
243128
+ fastify2.get(
243129
+ "/api/agent-sessions/:sessionId/brief-source",
243130
+ async (req, reply) => {
243131
+ const session = fastify2.agentSessionManager.getSession(req.params.sessionId);
243132
+ if (!session) return reply.code(404).send({ error: "Session not found" });
243133
+ return reply.code(200).send({
243134
+ messages: projectMessagesForBrief(fastify2.agentSessionManager.getMessages(req.params.sessionId))
243135
+ });
243136
+ }
243137
+ );
242272
243138
  fastify2.post("/api/agent-sessions/:sessionId/message", { bodyLimit: 10 * 1024 * 1024 }, async (req, reply) => {
242273
243139
  const authResult = requireUserFacingUserId(req, reply);
242274
243140
  if (authResult === null) return;
@@ -243407,7 +244273,7 @@ var chat_session_routes_default = (0, import_fastify_plugin16.default)(routes15,
243407
244273
 
243408
244274
  // src/routes/project-chat-routes.ts
243409
244275
  var import_fastify_plugin17 = __toESM(require_plugin2(), 1);
243410
- import { createHash as createHash6, randomUUID as randomUUID16 } from "crypto";
244276
+ import { createHash as createHash7, randomUUID as randomUUID16 } from "crypto";
243411
244277
  var MAX_TITLE_LENGTH = 200;
243412
244278
  var MAX_MESSAGE_LENGTH = 1e5;
243413
244279
  var THREAD_PAGE_LIMIT = 50;
@@ -243576,7 +244442,7 @@ var routes16 = async (fastify2) => {
243576
244442
  const body = parseCreateBody(req.body);
243577
244443
  if (!body) return reply.code(400).send({ error: "Body must contain only an optional non-empty message" });
243578
244444
  const createRequestId = body.createRequestId ?? randomUUID16();
243579
- const createPayloadHash = createHash6("sha256").update(JSON.stringify({ message: body.message ?? null })).digest("hex");
244445
+ const createPayloadHash = createHash7("sha256").update(JSON.stringify({ message: body.message ?? null })).digest("hex");
243580
244446
  let accepted;
243581
244447
  try {
243582
244448
  accepted = await fastify2.storage.projectChatThreads.createIdempotent({
@@ -244209,304 +245075,6 @@ var command_routes_default = (0, import_fastify_plugin21.default)(routes20, { na
244209
245075
 
244210
245076
  // src/routes/workflow-run-routes.ts
244211
245077
  var import_fastify_plugin22 = __toESM(require_plugin2(), 1);
244212
-
244213
- // src/utils/review-brief.ts
244214
- var BASE_TIMEOUT_MS = 15e3;
244215
- var JUDGMENT_TIMEOUT_MS = 9e4;
244216
- var TIMEOUT_MS_PER_1K_CHARS = 120;
244217
- var MAX_TIMEOUT_MS = 6e4;
244218
- var PER_MESSAGE_MAX_CHARS = 6e3;
244219
- var COMPACT_TRIGGER_CHARS = 12e4;
244220
- var COMPACT_SLICE_BUDGETS = [96e3, 24e3, 6e3];
244221
- var RECENT_VERBATIM_RATIO = 0.3;
244222
- var MIN_RECENT_VERBATIM_CHARS = 2e3;
244223
- var MAX_FOLD_CALLS = 8;
244224
- var COMPACT_SUMMARY_MAX_CHARS = 6e3;
244225
- var COMPACT_SUMMARY_MAX_TOKENS = 3e3;
244226
- var REVERSALS_MAX_CHARS = 2e3;
244227
- var REVERSALS_MAX_TOKENS = 2e3;
244228
- var BRIEF_MAX_CHARS = 4e3;
244229
- var BRIEF_MAX_TOKENS = 3e3;
244230
- var REVERSAL_MIN_CHARS = 6e3;
244231
- var SEP = "\n\n";
244232
- var COMPACTION_NOTE = "_Note: the source conversation was compressed before distillation \u2014 older turns were summarized rather than read verbatim._";
244233
- var BRIEF_TRUNCATION_NOTE = "\n\n_[brief truncated at the length limit \u2014 treat it as incomplete]_";
244234
- var SYSTEM_PROMPT2 = [
244235
- "You distill a coding-agent conversation into an intent brief for an independent code reviewer.",
244236
- "The reviewer will NOT see the conversation \u2014 only your brief plus the actual code, so capture what the code alone cannot show:",
244237
- "0. Dominant question \u2014 1 or 2 sentences: the single question the reviewer must answer to judge this work (what must actually work, toward what goal). Derive it from the conversation's own emphasis \u2014 what the user repeated, finally decided, or reversed course over \u2014 never from your own engineering judgment. If the conversation does not clearly support one, write 'unclear' instead of inventing one.",
244238
- "1. The original request and its goal.",
244239
- "2. Hard constraints \u2014 requirements whose violation the user would treat as failure regardless of everything else (security, data loss, an explicit compatibility or behaviour promise). Only list ones the user actually stated; an empty section is fine.",
244240
- "3. Constraints and decisions, including approaches that were rejected and why. A rejection counts whether the user made it or the agent made it under a principle the user set.",
244241
- "4. Non-goals, trade-offs and limitations that were acknowledged and accepted.",
244242
- "5. Behaviour established by actually running something \u2014 observed output, exit codes, error text, which stream an error arrived on. Report what was observed; that is evidence the reviewer cannot recover by reading code.",
244243
- "Tag every item under headings 3 and 4 with exactly [settled] or [tentative] \u2014 the bare tag; keep any justification to a few words or omit it, always after the tag, never inside the brackets. Settled ONLY when the user explicitly confirmed it, instructed it, or reversed course to it; an agent proposal the user never answered is tentative \u2014 silence is never settled.",
244244
- "Within each heading, order items by how much they matter to the dominant question, not by when they were said.",
244245
- "Later statements supersede earlier ones on the same topic. An option explored at length early is often rejected later in a single sentence, and the rejection wins. Where the conversation ends in a decision table or summary, that is authoritative wherever it conflicts with earlier prose.",
244246
- "The input may arrive as numbered compressed slices followed by verbatim recent turns. Slice numbers are chronological: a later slice overrules an earlier one.",
244247
- "Decisions the agent made that the user did not contradict are worth reporting, but user silence only ever yields tentative status.",
244248
- "Do NOT include the agent's self-assessment or any claim that the work is correct or complete \u2014 the reviewer must judge that independently.",
244249
- "Every statement must trace to something in the conversation. If a heading has nothing real to report, say so rather than inventing plausible-sounding content.",
244250
- "Write concise markdown bullets under those numbered headings, under 500 words total, in the same language as the conversation. Reply with the brief only."
244251
- ].join("\n");
244252
- var REVERSAL_SYSTEM_PROMPT = [
244253
- "You read a coding-agent conversation and report ONLY the conclusions that were later reversed, dropped, or replaced.",
244254
- "A design conversation converges by killing its own hypotheses: an option explored in depth early is often rejected later in one sentence, so weigh finality over how much was written.",
244255
- "A reversal counts whether the user or the agent made it. Ignore rewording that leaves the decision intact.",
244256
- "Output one line per reversal: SUPERSEDED: <what was concluded earlier> -> <what replaced it> (<why>)",
244257
- "Report the most decisive reversals first and stay under 200 words \u2014 a list that runs long will be discarded whole, so prioritise rather than pad.",
244258
- "If nothing was reversed, reply with exactly: NONE"
244259
- ].join("\n");
244260
- var COMPACT_SYSTEM_PROMPT = [
244261
- "You compress one slice of a coding-agent conversation. A later pass will distill the whole thing into an intent brief for a code reviewer.",
244262
- "You are told which slice of how many this is. Other slices are compressed separately and you cannot see them, so never present a conclusion here as final \u2014 a later slice may overturn it.",
244263
- "Preserve, in this order of priority:",
244264
- "1. Reversals and corrections \u2014 any conclusion that was dropped, replaced, or corrected. Quote the deciding sentence verbatim.",
244265
- "2. Constraints and decisions the user stated, and approaches that were rejected, with the reason. Preserve who made each decision \u2014 an explicit user confirmation must stay distinguishable from an agent proposal the user never answered; quote the user's deciding sentence when there is one.",
244266
- "3. Behaviour established by actually running something: observed output, exit codes, error text, which stream an error arrived on.",
244267
- "4. Trade-offs that were acknowledged and accepted.",
244268
- "Drop: exploration narrative, restated background, tool mechanics, and anything a reviewer could recover by reading the code.",
244269
- "Stay under 800 words. An over-long slice is discarded whole rather than cut short, so drop lower-priority material instead of running over.",
244270
- "Keep the conversation's own language. Reply with the compressed slice only, no preamble."
244271
- ].join("\n");
244272
- function timeoutForInput(chars) {
244273
- return Math.min(MAX_TIMEOUT_MS, BASE_TIMEOUT_MS + Math.floor(chars / 1e3) * TIMEOUT_MS_PER_1K_CHARS);
244274
- }
244275
- function isSizeRelatedFailure(error48) {
244276
- const err = error48;
244277
- if (err?.name === "AbortError" || err?.name === "TimeoutError") return true;
244278
- const message = err?.message ?? "";
244279
- return /context[ _-]?length|maximum context|too many tokens|token limit|prompt is too long|request too large|timed? ?out/i.test(
244280
- message
244281
- );
244282
- }
244283
- function withinLimit(text2, max, label) {
244284
- if (text2.length <= max) return true;
244285
- console.warn(`[ReviewBrief] ${label} ran to ${text2.length} chars (limit ${max}) \u2014 discarding rather than truncating`);
244286
- return false;
244287
- }
244288
- function capMessage(text2) {
244289
- return text2.length > PER_MESSAGE_MAX_CHARS ? text2.slice(0, PER_MESSAGE_MAX_CHARS) + "\u2026" : text2;
244290
- }
244291
- function toEntries(messages) {
244292
- const entries = [];
244293
- for (const msg of messages) {
244294
- if (!msg) continue;
244295
- if (msg.type === "user" && !msg.event) {
244296
- const text2 = extractUserText(msg.content).trim();
244297
- if (text2) entries.push({ role: "User", text: capMessage(text2) });
244298
- } else if (msg.type === "assistant" && typeof msg.content === "string") {
244299
- const text2 = msg.content.trim();
244300
- if (text2) entries.push({ role: "Agent", text: capMessage(text2) });
244301
- }
244302
- }
244303
- return entries;
244304
- }
244305
- function render(entry) {
244306
- return `${entry.role}: ${entry.text}`;
244307
- }
244308
- function renderAll(entries) {
244309
- return entries.map(render).join(SEP);
244310
- }
244311
- function serializeConversationForBrief(messages) {
244312
- return renderAll(toEntries(messages));
244313
- }
244314
- function splitRecent(entries, maxChars) {
244315
- let size = 0;
244316
- let i = entries.length;
244317
- while (i > 0) {
244318
- const len = render(entries[i - 1]).length + SEP.length;
244319
- if (size + len > maxChars) break;
244320
- size += len;
244321
- i--;
244322
- }
244323
- return { older: entries.slice(0, i), recent: entries.slice(i) };
244324
- }
244325
- function chunkEntries(entries, maxChars) {
244326
- const chunks = [];
244327
- let current = [];
244328
- let size = 0;
244329
- for (const entry of entries) {
244330
- const len = render(entry).length + SEP.length;
244331
- if (current.length > 0 && size + len > maxChars) {
244332
- chunks.push(current);
244333
- current = [];
244334
- size = 0;
244335
- }
244336
- current.push(entry);
244337
- size += len;
244338
- }
244339
- if (current.length > 0) chunks.push(current);
244340
- return chunks;
244341
- }
244342
- function telemetryFor(functionId, userId) {
244343
- return userId ? {
244344
- isEnabled: true,
244345
- functionId,
244346
- metadata: { userId, tags: ["vibedeckx", functionId] }
244347
- } : void 0;
244348
- }
244349
- async function compactChunk(model, chunk, part, total, userId) {
244350
- try {
244351
- const result = await generateText({
244352
- model,
244353
- system: COMPACT_SYSTEM_PROMPT,
244354
- prompt: `Slice ${part} of ${total}.
244355
-
244356
- ${chunk}`,
244357
- timeout: timeoutForInput(chunk.length),
244358
- maxOutputTokens: COMPACT_SUMMARY_MAX_TOKENS,
244359
- experimental_telemetry: telemetryFor("review-intent-brief-compact", userId)
244360
- });
244361
- const { text: rawText, finishReason } = result;
244362
- if (finishReason === "length") {
244363
- console.warn(`[ReviewBrief] slice ${part}/${total} summary hit the token cap \u2014 discarding`);
244364
- return null;
244365
- }
244366
- const text2 = (rawText ?? "").trim();
244367
- if (text2.length === 0) {
244368
- console.warn(`[ReviewBrief] slice ${part}/${total} came back empty (finishReason: ${finishReason ?? "unknown"})`);
244369
- return null;
244370
- }
244371
- return withinLimit(text2, COMPACT_SUMMARY_MAX_CHARS, `slice ${part}/${total} summary`) ? text2 : null;
244372
- } catch (error48) {
244373
- if (isSizeRelatedFailure(error48)) throw error48;
244374
- console.warn(`[ReviewBrief] compaction of slice ${part}/${total} failed:`, error48.message);
244375
- return null;
244376
- }
244377
- }
244378
- async function compactConversation(model, messages, options = {}) {
244379
- const sliceChars = options.sliceChars ?? COMPACT_SLICE_BUDGETS[0];
244380
- const recentChars = Math.max(MIN_RECENT_VERBATIM_CHARS, Math.floor(sliceChars * RECENT_VERBATIM_RATIO));
244381
- const entries = toEntries(messages);
244382
- if (entries.length === 0) return null;
244383
- const { older, recent } = splitRecent(entries, recentChars);
244384
- if (older.length === 0) return null;
244385
- const chunks = chunkEntries(older, sliceChars);
244386
- if (chunks.length > MAX_FOLD_CALLS) {
244387
- console.warn(
244388
- `[ReviewBrief] conversation needs ${chunks.length} slices of ${sliceChars} chars (max ${MAX_FOLD_CALLS}) \u2014 falling back to tier 2`
244389
- );
244390
- return null;
244391
- }
244392
- const settled = await Promise.allSettled(
244393
- chunks.map((chunk, i) => compactChunk(model, renderAll(chunk), i + 1, chunks.length, options.userId))
244394
- );
244395
- const sizeRejection = settled.find((r) => r.status === "rejected" && isSizeRelatedFailure(r.reason));
244396
- if (sizeRejection) throw sizeRejection.reason;
244397
- if (settled.some((r) => r.status === "rejected" || r.value === null)) return null;
244398
- const parts = settled.map(
244399
- (r, i) => `[Compressed slice ${i + 1} of ${chunks.length}]
244400
- ${r.value}`
244401
- );
244402
- if (recent.length > 0) parts.push(`[Recent turns, verbatim]
244403
- ${renderAll(recent)}`);
244404
- return parts.join(SEP);
244405
- }
244406
- function buildBriefPrompt(conversation, reversals) {
244407
- const preamble = reversals ? "Conclusions this conversation reversed. The right-hand side is the current state \u2014 never report the left-hand side as what was decided:\n" + reversals + SEP : "";
244408
- return `${preamble}Distill this conversation into an intent brief:
244409
-
244410
- ${conversation}`;
244411
- }
244412
- function appendCompactionNote(brief, compacted) {
244413
- return compacted ? `${brief}${SEP}${COMPACTION_NOTE}` : brief;
244414
- }
244415
- async function extractReversalsWithModel(model, conversation, options = {}) {
244416
- if (conversation.trim().length < REVERSAL_MIN_CHARS) return null;
244417
- try {
244418
- const result = await generateText({
244419
- model,
244420
- system: REVERSAL_SYSTEM_PROMPT,
244421
- prompt: `Report the reversals in this conversation:
244422
-
244423
- ${conversation}`,
244424
- timeout: JUDGMENT_TIMEOUT_MS,
244425
- maxOutputTokens: REVERSALS_MAX_TOKENS,
244426
- experimental_telemetry: telemetryFor("review-intent-brief-reversals", options.userId)
244427
- });
244428
- const { text: rawText, finishReason } = result;
244429
- if (finishReason === "length") {
244430
- console.warn("[ReviewBrief] reversal list hit the token cap \u2014 discarding");
244431
- return null;
244432
- }
244433
- const text2 = (rawText ?? "").trim();
244434
- if (text2.length === 0 || /^none\b/i.test(text2)) return null;
244435
- return withinLimit(text2, REVERSALS_MAX_CHARS, "reversal list") ? text2 : null;
244436
- } catch (error48) {
244437
- if (!isSizeRelatedFailure(error48)) throw error48;
244438
- console.warn("[ReviewBrief] reversal pass hit a size limit \u2014 skipping it:", error48.message);
244439
- return null;
244440
- }
244441
- }
244442
- async function generateIntentBriefWithModel(model, conversation, options = {}) {
244443
- if (conversation.trim().length === 0) return null;
244444
- try {
244445
- const result = await generateText({
244446
- model,
244447
- system: SYSTEM_PROMPT2,
244448
- prompt: buildBriefPrompt(conversation, options.reversals ?? null),
244449
- timeout: JUDGMENT_TIMEOUT_MS,
244450
- maxOutputTokens: BRIEF_MAX_TOKENS,
244451
- experimental_telemetry: telemetryFor("review-intent-brief", options.userId)
244452
- });
244453
- const { text: rawText, finishReason } = result;
244454
- const text2 = (rawText ?? "").trim();
244455
- if (text2.length === 0) {
244456
- console.warn(`[ReviewBrief] model returned empty text (finishReason: ${finishReason ?? "unknown"})`);
244457
- return null;
244458
- }
244459
- if (finishReason === "length") return text2.slice(0, BRIEF_MAX_CHARS) + BRIEF_TRUNCATION_NOTE;
244460
- return text2.length <= BRIEF_MAX_CHARS ? text2 : text2.slice(0, BRIEF_MAX_CHARS) + BRIEF_TRUNCATION_NOTE;
244461
- } catch (error48) {
244462
- if (options.rethrowSizeFailures && isSizeRelatedFailure(error48)) throw error48;
244463
- console.warn("[ReviewBrief] AI generation failed:", error48.message);
244464
- return null;
244465
- }
244466
- }
244467
- async function distill(model, conversation, userId, rethrowSizeFailures) {
244468
- const reversals = await extractReversalsWithModel(model, conversation, { userId });
244469
- return generateIntentBriefWithModel(model, conversation, { userId, reversals, rethrowSizeFailures });
244470
- }
244471
- async function generateIntentBrief(storage, userId, messages) {
244472
- try {
244473
- const config2 = await getChatProviderConfig(storage, userId);
244474
- const mainOk = isModelConfigured(config2, config2.main);
244475
- const fastOk = isModelConfigured(config2, config2.fast);
244476
- if (!mainOk && !fastOk) return null;
244477
- const conversation = serializeConversationForBrief(messages);
244478
- if (!conversation) return null;
244479
- const distillModel = mainOk ? await resolveChatModel(storage, userId) : await resolveFastChatModel(storage, userId);
244480
- const compactModel = fastOk ? await resolveFastChatModel(storage, userId) : distillModel;
244481
- if (conversation.length <= COMPACT_TRIGGER_CHARS) {
244482
- try {
244483
- const brief = await distill(distillModel, conversation, userId, true);
244484
- return brief === null ? null : appendCompactionNote(brief, false);
244485
- } catch (error48) {
244486
- if (!isSizeRelatedFailure(error48)) throw error48;
244487
- console.warn("[ReviewBrief] full conversation rejected as too large \u2014 compacting and retrying");
244488
- }
244489
- }
244490
- for (const sliceChars of COMPACT_SLICE_BUDGETS) {
244491
- try {
244492
- const compacted = await compactConversation(compactModel, messages, { userId, sliceChars });
244493
- if (compacted === null) return null;
244494
- const brief = await distill(distillModel, compacted, userId, true);
244495
- return brief === null ? null : appendCompactionNote(brief, true);
244496
- } catch (error48) {
244497
- if (!isSizeRelatedFailure(error48)) throw error48;
244498
- console.warn(`[ReviewBrief] ${sliceChars}-char slices still too large \u2014 retrying smaller`);
244499
- }
244500
- }
244501
- console.warn("[ReviewBrief] could not compact the conversation small enough \u2014 falling back to tier 2");
244502
- return null;
244503
- } catch (error48) {
244504
- console.warn("[ReviewBrief] generation failed:", error48.message);
244505
- return null;
244506
- }
244507
- }
244508
-
244509
- // src/routes/workflow-run-routes.ts
244510
245078
  function parseReviewerAgentType(raw) {
244511
245079
  if (raw === void 0) return void 0;
244512
245080
  return typeof raw === "string" && REVIEWER_AGENT_TYPES.has(raw) ? raw : null;
@@ -244569,7 +245137,7 @@ async function routes21(fastify2) {
244569
245137
  const historyResult = await proxyAuto(
244570
245138
  remoteInfo,
244571
245139
  "GET",
244572
- `/api/agent-sessions/${remoteInfo.remoteSessionId}`
245140
+ `/api/agent-sessions/${remoteInfo.remoteSessionId}/brief-source`
244573
245141
  );
244574
245142
  if (!historyResult.ok) return void 0;
244575
245143
  messages = historyResult.data.messages ?? [];
@@ -246140,7 +246708,7 @@ var websocket_routes_default = (0, import_fastify_plugin25.default)(routes24, {
246140
246708
 
246141
246709
  // src/routes/reverse-connect-routes.ts
246142
246710
  var import_fastify_plugin26 = __toESM(require_plugin2(), 1);
246143
- import { randomBytes as randomBytes2, createHash as createHash7, verify as cryptoVerify } from "crypto";
246711
+ import { randomBytes as randomBytes2, createHash as createHash8, verify as cryptoVerify } from "crypto";
246144
246712
 
246145
246713
  // src/utils/rate-limited-warn.ts
246146
246714
  function createRateLimitedWarn(windowMs, maxKeys) {
@@ -246290,7 +246858,7 @@ var routes25 = async (fastify2) => {
246290
246858
  socket.close(4003, "Bad machine signature");
246291
246859
  return;
246292
246860
  }
246293
- const fingerprint = createHash7("sha256").update(publicKey).digest("hex");
246861
+ const fingerprint = createHash8("sha256").update(publicKey).digest("hex");
246294
246862
  const { owned, created } = await fastify2.storage.machineIdentity.claimOrVerify(fingerprint, publicKey, ownerId);
246295
246863
  if (!owned) {
246296
246864
  console.warn(`[ReverseConnect] Machine ${fingerprint.slice(0, 12)} owner mismatch \u2014 rejecting ${serverId}`);
@@ -246389,23 +246957,6 @@ var event_routes_default = (0, import_fastify_plugin27.default)(routes26, { name
246389
246957
  // src/routes/terminal-routes.ts
246390
246958
  var import_fastify_plugin28 = __toESM(require_plugin2(), 1);
246391
246959
  import path13 from "path";
246392
-
246393
- // src/utils/path-project.ts
246394
- async function ensurePathProjectId(fastify2, projectPath) {
246395
- const pseudoProjectId = `path:${projectPath}`;
246396
- if (await fastify2.storage.projects.getById(pseudoProjectId)) return pseudoProjectId;
246397
- const existingByPath = await fastify2.storage.projects.getByPath(projectPath);
246398
- if (existingByPath) return existingByPath.id;
246399
- const name25 = projectPath.split("/").filter(Boolean).pop() || projectPath;
246400
- try {
246401
- await fastify2.storage.projects.create({ id: pseudoProjectId, name: name25, path: projectPath });
246402
- } catch (err) {
246403
- if (!(err instanceof Error && err.message.includes("UNIQUE constraint failed"))) throw err;
246404
- }
246405
- return pseudoProjectId;
246406
- }
246407
-
246408
- // src/routes/terminal-routes.ts
246409
246960
  async function getRemoteConfig5(fastify2, project, remoteServerId) {
246410
246961
  const remotes = await fastify2.storage.projectRemotes.getByProject(project.id);
246411
246962
  const target = remoteServerId ? remotes.find((r) => r.remote_server_id === remoteServerId) : remotes[0];
@@ -248018,8 +248569,8 @@ var parseDbTimestamp5 = (ts) => {
248018
248569
  };
248019
248570
  async function buildSearchCatalog(deps, projectId, projectPath) {
248020
248571
  pruneWorktrees(projectPath);
248021
- const workspaces = getWorktreeBranches(projectPath);
248022
248572
  const sessions = await deps.storage.agentSessions.getByProjectId(projectId);
248573
+ const workspaces = await getRegisteredWorktreeBranches(deps.storage, projectId, projectPath);
248023
248574
  const counts = new Map(
248024
248575
  (await deps.storage.agentSessions.countEntries()).map((r) => [r.session_id, r.cnt])
248025
248576
  );
@@ -248786,8 +249337,8 @@ var RotatingFileStream = class extends Writable {
248786
249337
  _final(callback) {
248787
249338
  this.refinal(void 0, callback);
248788
249339
  }
248789
- _write(chunk, encoding, callback) {
248790
- this.rewrite([{ chunk, encoding }], 0, callback);
249340
+ _write(chunk2, encoding, callback) {
249341
+ this.rewrite([{ chunk: chunk2, encoding }], 0, callback);
248791
249342
  }
248792
249343
  _writev(chunks, callback) {
248793
249344
  this.rewrite(chunks, 0, callback);
@@ -248811,13 +249362,13 @@ var RotatingFileStream = class extends Writable {
248811
249362
  if (this.initPromise)
248812
249363
  await this.initPromise;
248813
249364
  for (let i = 0; i < chunks.length; ++i) {
248814
- const { chunk } = chunks[i];
248815
- this.size += chunk.length;
249365
+ const { chunk: chunk2 } = chunks[i];
249366
+ this.size += chunk2.length;
248816
249367
  if (this.timeoutPromise)
248817
249368
  await this.timeoutPromise;
248818
- await this.file.write(chunk);
249369
+ await this.file.write(chunk2);
248819
249370
  if (teeToStdout && !this.stdout.destroyed)
248820
- this.stdout.write(chunk);
249371
+ this.stdout.write(chunk2);
248821
249372
  if (size && this.size >= size)
248822
249373
  await this.rotate();
248823
249374
  }
@@ -249838,6 +250389,9 @@ var WORKER_CAPABILITIES = {
249838
250389
  "http:POST /api/path/agent-sessions": { since: "0.2.0", summary: "\u521B\u5EFA\u4F1A\u8BDD" },
249839
250390
  "http:POST /api/path/agent-sessions/new": { since: "0.2.0", summary: "\u521B\u5EFA\u4F1A\u8BDD(\u6307\u5B9A ID)" },
249840
250391
  "http:GET /api/agent-sessions/:param": { since: "0.2.0", summary: "\u8BFB\u4F1A\u8BDD\u8BE6\u60C5/\u5BF9\u8BDD" },
250392
+ // Additive: a worker below 0.3.6 404s it and the hub's intent-brief
250393
+ // distillation degrades to the deterministic excerpt (tier 2).
250394
+ "http:GET /api/agent-sessions/:param/brief-source": { since: "0.3.6", summary: "\u8BFB\u4F1A\u8BDD\u5BF9\u8BDD(\u4EC5\u84B8\u998F\u7528\u6587\u672C)" },
249841
250395
  "http:POST /api/agent-sessions/:param/message": { since: "0.2.0", summary: "\u53D1\u6D88\u606F\u7ED9\u4F1A\u8BDD" },
249842
250396
  "http:POST /api/agent-sessions/:param/paste": { since: "0.2.0", summary: "\u7C98\u8D34\u56FE\u7247/\u957F\u6587\u672C" },
249843
250397
  "http:POST /api/agent-sessions/:param/stop": { since: "0.2.0", summary: "\u505C\u6B62\u4F1A\u8BDD turn" },