newmark-agent 0.6.2 → 0.6.3

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.
@@ -3713,9 +3713,9 @@ var require_decoder = __commonJS({
3713
3713
  return a < 0 ? 0 : a > 255 ? 255 : a;
3714
3714
  }
3715
3715
  constructor.prototype = {
3716
- load: function load2(path31) {
3716
+ load: function load2(path32) {
3717
3717
  var xhr = new XMLHttpRequest();
3718
- xhr.open("GET", path31, true);
3718
+ xhr.open("GET", path32, true);
3719
3719
  xhr.responseType = "arraybuffer";
3720
3720
  xhr.onload = (function() {
3721
3721
  var data2 = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);
@@ -5389,14 +5389,14 @@ var require_util = __commonJS({
5389
5389
  }
5390
5390
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
5391
5391
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
5392
- let path31 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
5392
+ let path32 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
5393
5393
  if (origin[origin.length - 1] === "/") {
5394
5394
  origin = origin.slice(0, origin.length - 1);
5395
5395
  }
5396
- if (path31 && path31[0] !== "/") {
5397
- path31 = `/${path31}`;
5396
+ if (path32 && path32[0] !== "/") {
5397
+ path32 = `/${path32}`;
5398
5398
  }
5399
- return new URL(`${origin}${path31}`);
5399
+ return new URL(`${origin}${path32}`);
5400
5400
  }
5401
5401
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
5402
5402
  throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -6217,9 +6217,9 @@ var require_diagnostics = __commonJS({
6217
6217
  "undici:client:sendHeaders",
6218
6218
  (evt) => {
6219
6219
  const {
6220
- request: { method, path: path31, origin }
6220
+ request: { method, path: path32, origin }
6221
6221
  } = evt;
6222
- debugLog("sending request to %s %s%s", method, origin, path31);
6222
+ debugLog("sending request to %s %s%s", method, origin, path32);
6223
6223
  }
6224
6224
  );
6225
6225
  }
@@ -6237,14 +6237,14 @@ var require_diagnostics = __commonJS({
6237
6237
  "undici:request:headers",
6238
6238
  (evt) => {
6239
6239
  const {
6240
- request: { method, path: path31, origin },
6240
+ request: { method, path: path32, origin },
6241
6241
  response: { statusCode }
6242
6242
  } = evt;
6243
6243
  debugLog(
6244
6244
  "received response to %s %s%s - HTTP %d",
6245
6245
  method,
6246
6246
  origin,
6247
- path31,
6247
+ path32,
6248
6248
  statusCode
6249
6249
  );
6250
6250
  }
@@ -6253,23 +6253,23 @@ var require_diagnostics = __commonJS({
6253
6253
  "undici:request:trailers",
6254
6254
  (evt) => {
6255
6255
  const {
6256
- request: { method, path: path31, origin }
6256
+ request: { method, path: path32, origin }
6257
6257
  } = evt;
6258
- debugLog("trailers received from %s %s%s", method, origin, path31);
6258
+ debugLog("trailers received from %s %s%s", method, origin, path32);
6259
6259
  }
6260
6260
  );
6261
6261
  diagnosticsChannel.subscribe(
6262
6262
  "undici:request:error",
6263
6263
  (evt) => {
6264
6264
  const {
6265
- request: { method, path: path31, origin },
6265
+ request: { method, path: path32, origin },
6266
6266
  error: error2
6267
6267
  } = evt;
6268
6268
  debugLog(
6269
6269
  "request to %s %s%s errored - %s",
6270
6270
  method,
6271
6271
  origin,
6272
- path31,
6272
+ path32,
6273
6273
  error2.message
6274
6274
  );
6275
6275
  }
@@ -6384,7 +6384,7 @@ var require_request = __commonJS({
6384
6384
  var kHandler = /* @__PURE__ */ Symbol("handler");
6385
6385
  var Request = class {
6386
6386
  constructor(origin, {
6387
- path: path31,
6387
+ path: path32,
6388
6388
  method,
6389
6389
  body,
6390
6390
  headers,
@@ -6401,11 +6401,11 @@ var require_request = __commonJS({
6401
6401
  maxRedirections,
6402
6402
  typeOfService
6403
6403
  }, handler) {
6404
- if (typeof path31 !== "string") {
6404
+ if (typeof path32 !== "string") {
6405
6405
  throw new InvalidArgumentError("path must be a string");
6406
- } else if (path31[0] !== "/" && !(path31.startsWith("http://") || path31.startsWith("https://")) && method !== "CONNECT") {
6406
+ } else if (path32[0] !== "/" && !(path32.startsWith("http://") || path32.startsWith("https://")) && method !== "CONNECT") {
6407
6407
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
6408
- } else if (invalidPathRegex.test(path31)) {
6408
+ } else if (invalidPathRegex.test(path32)) {
6409
6409
  throw new InvalidArgumentError("invalid request path");
6410
6410
  }
6411
6411
  if (typeof method !== "string") {
@@ -6480,7 +6480,7 @@ var require_request = __commonJS({
6480
6480
  this.completed = false;
6481
6481
  this.aborted = false;
6482
6482
  this.upgrade = upgrade || null;
6483
- this.path = query ? serializePathWithQuery(path31, query) : path31;
6483
+ this.path = query ? serializePathWithQuery(path32, query) : path32;
6484
6484
  this.origin = origin;
6485
6485
  this.protocol = getProtocolFromUrlString(origin);
6486
6486
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -6984,9 +6984,9 @@ var require_dispatcher_base = __commonJS({
6984
6984
  }
6985
6985
  close(callback) {
6986
6986
  if (callback === void 0) {
6987
- return new Promise((resolve15, reject) => {
6987
+ return new Promise((resolve16, reject) => {
6988
6988
  this.close((err, data2) => {
6989
- return err ? reject(err) : resolve15(data2);
6989
+ return err ? reject(err) : resolve16(data2);
6990
6990
  });
6991
6991
  });
6992
6992
  }
@@ -7024,9 +7024,9 @@ var require_dispatcher_base = __commonJS({
7024
7024
  err = null;
7025
7025
  }
7026
7026
  if (callback === void 0) {
7027
- return new Promise((resolve15, reject) => {
7027
+ return new Promise((resolve16, reject) => {
7028
7028
  this.destroy(err, (err2, data2) => {
7029
- return err2 ? reject(err2) : resolve15(data2);
7029
+ return err2 ? reject(err2) : resolve16(data2);
7030
7030
  });
7031
7031
  });
7032
7032
  }
@@ -10523,8 +10523,8 @@ var require_promise = __commonJS({
10523
10523
  function createDeferredPromise() {
10524
10524
  let res;
10525
10525
  let rej;
10526
- const promise = new Promise((resolve15, reject) => {
10527
- res = resolve15;
10526
+ const promise = new Promise((resolve16, reject) => {
10527
+ res = resolve16;
10528
10528
  rej = reject;
10529
10529
  });
10530
10530
  return { promise, resolve: res, reject: rej };
@@ -11663,7 +11663,7 @@ var require_client_h1 = __commonJS({
11663
11663
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
11664
11664
  }
11665
11665
  function writeH1(client, request) {
11666
- const { method, path: path31, host: host2, upgrade, blocking, reset } = request;
11666
+ const { method, path: path32, host: host2, upgrade, blocking, reset } = request;
11667
11667
  let { body, headers, contentLength } = request;
11668
11668
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
11669
11669
  if (util.isFormDataLike(body)) {
@@ -11741,7 +11741,7 @@ var require_client_h1 = __commonJS({
11741
11741
  if (socket.setTypeOfService) {
11742
11742
  socket.setTypeOfService(request.typeOfService);
11743
11743
  }
11744
- let header = `${method} ${path31} HTTP/1.1\r
11744
+ let header = `${method} ${path32} HTTP/1.1\r
11745
11745
  `;
11746
11746
  if (typeof host2 === "string") {
11747
11747
  header += `host: ${host2}\r
@@ -11928,12 +11928,12 @@ upgrade: ${upgrade}\r
11928
11928
  cb();
11929
11929
  }
11930
11930
  }
11931
- const waitForDrain = () => new Promise((resolve15, reject) => {
11931
+ const waitForDrain = () => new Promise((resolve16, reject) => {
11932
11932
  assert4(callback === null);
11933
11933
  if (socket[kError]) {
11934
11934
  reject(socket[kError]);
11935
11935
  } else {
11936
- callback = resolve15;
11936
+ callback = resolve16;
11937
11937
  }
11938
11938
  });
11939
11939
  socket.on("close", onDrain).on("drain", onDrain);
@@ -12394,7 +12394,7 @@ var require_client_h2 = __commonJS({
12394
12394
  function writeH2(client, request) {
12395
12395
  const requestTimeout = request.bodyTimeout ?? client[kBodyTimeout];
12396
12396
  const session = client[kHTTP2Session];
12397
- const { method, path: path31, host: host2, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
12397
+ const { method, path: path32, host: host2, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
12398
12398
  let { body } = request;
12399
12399
  if (upgrade != null && upgrade !== "websocket") {
12400
12400
  util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -12462,7 +12462,7 @@ var require_client_h2 = __commonJS({
12462
12462
  }
12463
12463
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
12464
12464
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
12465
- headers[HTTP2_HEADER_PATH] = path31;
12465
+ headers[HTTP2_HEADER_PATH] = path32;
12466
12466
  if (protocol === "ws:" || protocol === "wss:") {
12467
12467
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
12468
12468
  } else {
@@ -12503,7 +12503,7 @@ var require_client_h2 = __commonJS({
12503
12503
  stream.setTimeout(requestTimeout);
12504
12504
  return true;
12505
12505
  }
12506
- headers[HTTP2_HEADER_PATH] = path31;
12506
+ headers[HTTP2_HEADER_PATH] = path32;
12507
12507
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
12508
12508
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
12509
12509
  if (body && typeof body.read === "function") {
@@ -12778,12 +12778,12 @@ var require_client_h2 = __commonJS({
12778
12778
  cb();
12779
12779
  }
12780
12780
  }
12781
- const waitForDrain = () => new Promise((resolve15, reject) => {
12781
+ const waitForDrain = () => new Promise((resolve16, reject) => {
12782
12782
  assert4(callback === null);
12783
12783
  if (socket[kError]) {
12784
12784
  reject(socket[kError]);
12785
12785
  } else {
12786
- callback = resolve15;
12786
+ callback = resolve16;
12787
12787
  }
12788
12788
  });
12789
12789
  h2stream.on("close", onDrain).on("drain", onDrain);
@@ -13099,16 +13099,16 @@ var require_client = __commonJS({
13099
13099
  return this[kNeedDrain] < 2;
13100
13100
  }
13101
13101
  [kClose]() {
13102
- return new Promise((resolve15) => {
13102
+ return new Promise((resolve16) => {
13103
13103
  if (this[kSize]) {
13104
- this[kClosedResolve] = resolve15;
13104
+ this[kClosedResolve] = resolve16;
13105
13105
  } else {
13106
- resolve15(null);
13106
+ resolve16(null);
13107
13107
  }
13108
13108
  });
13109
13109
  }
13110
13110
  [kDestroy](err) {
13111
- return new Promise((resolve15) => {
13111
+ return new Promise((resolve16) => {
13112
13112
  const requests = this[kQueue].splice(this[kPendingIdx]);
13113
13113
  for (let i = 0; i < requests.length; i++) {
13114
13114
  const request = requests[i];
@@ -13119,7 +13119,7 @@ var require_client = __commonJS({
13119
13119
  this[kClosedResolve]();
13120
13120
  this[kClosedResolve] = null;
13121
13121
  }
13122
- resolve15(null);
13122
+ resolve16(null);
13123
13123
  };
13124
13124
  if (this[kHTTPContext]) {
13125
13125
  this[kHTTPContext].destroy(err, callback);
@@ -13524,8 +13524,8 @@ var require_pool_base = __commonJS({
13524
13524
  }
13525
13525
  return Promise.all(closeAll);
13526
13526
  } else {
13527
- return new Promise((resolve15) => {
13528
- this[kClosedResolve] = resolve15;
13527
+ return new Promise((resolve16) => {
13528
+ this[kClosedResolve] = resolve16;
13529
13529
  });
13530
13530
  }
13531
13531
  }
@@ -14642,7 +14642,7 @@ var require_socks5_proxy_agent = __commonJS({
14642
14642
  const proxyHost = this[kProxyUrl].hostname;
14643
14643
  const proxyPort = parseInt(this[kProxyUrl].port) || 1080;
14644
14644
  debug3("creating SOCKS5 connection to", proxyHost, proxyPort);
14645
- const socket = await new Promise((resolve15, reject) => {
14645
+ const socket = await new Promise((resolve16, reject) => {
14646
14646
  this[kConnector]({
14647
14647
  hostname: proxyHost,
14648
14648
  host: proxyHost,
@@ -14652,7 +14652,7 @@ var require_socks5_proxy_agent = __commonJS({
14652
14652
  if (err) {
14653
14653
  reject(err);
14654
14654
  } else {
14655
- resolve15(socket2);
14655
+ resolve16(socket2);
14656
14656
  }
14657
14657
  });
14658
14658
  });
@@ -14662,14 +14662,14 @@ var require_socks5_proxy_agent = __commonJS({
14662
14662
  socket.destroy();
14663
14663
  });
14664
14664
  await socks5Client.handshake();
14665
- await new Promise((resolve15, reject) => {
14665
+ await new Promise((resolve16, reject) => {
14666
14666
  const timeout = setTimeout(() => {
14667
14667
  reject(new Error("SOCKS5 authentication timeout"));
14668
14668
  }, 5e3);
14669
14669
  const onAuthenticated = () => {
14670
14670
  clearTimeout(timeout);
14671
14671
  socks5Client.removeListener("error", onError);
14672
- resolve15();
14672
+ resolve16();
14673
14673
  };
14674
14674
  const onError = (err) => {
14675
14675
  clearTimeout(timeout);
@@ -14678,14 +14678,14 @@ var require_socks5_proxy_agent = __commonJS({
14678
14678
  };
14679
14679
  if (socks5Client.state === STATES.AUTHENTICATED) {
14680
14680
  clearTimeout(timeout);
14681
- resolve15();
14681
+ resolve16();
14682
14682
  } else {
14683
14683
  socks5Client.once("authenticated", onAuthenticated);
14684
14684
  socks5Client.once("error", onError);
14685
14685
  }
14686
14686
  });
14687
14687
  await socks5Client.connect(targetHost, targetPort);
14688
- await new Promise((resolve15, reject) => {
14688
+ await new Promise((resolve16, reject) => {
14689
14689
  const timeout = setTimeout(() => {
14690
14690
  reject(new Error("SOCKS5 connection timeout"));
14691
14691
  }, 5e3);
@@ -14693,7 +14693,7 @@ var require_socks5_proxy_agent = __commonJS({
14693
14693
  debug3("SOCKS5 tunnel established to", targetHost, targetPort, "via", info2);
14694
14694
  clearTimeout(timeout);
14695
14695
  socks5Client.removeListener("error", onError);
14696
- resolve15();
14696
+ resolve16();
14697
14697
  };
14698
14698
  const onError = (err) => {
14699
14699
  clearTimeout(timeout);
@@ -14736,8 +14736,8 @@ var require_socks5_proxy_agent = __commonJS({
14736
14736
  socket,
14737
14737
  servername: this[kRequestTls]?.servername || targetHost
14738
14738
  });
14739
- await new Promise((resolve15, reject) => {
14740
- finalSocket.once("secureConnect", resolve15);
14739
+ await new Promise((resolve16, reject) => {
14740
+ finalSocket.once("secureConnect", resolve16);
14741
14741
  finalSocket.once("error", reject);
14742
14742
  });
14743
14743
  }
@@ -14846,10 +14846,10 @@ var require_proxy_agent = __commonJS({
14846
14846
  };
14847
14847
  const {
14848
14848
  origin,
14849
- path: path31 = "/",
14849
+ path: path32 = "/",
14850
14850
  headers = {}
14851
14851
  } = opts;
14852
- opts.path = origin + path31;
14852
+ opts.path = origin + path32;
14853
14853
  if (!("host" in headers) && !("Host" in headers)) {
14854
14854
  const { host: host2 } = new URL(origin);
14855
14855
  headers.host = host2;
@@ -15793,7 +15793,7 @@ var require_readable = __commonJS({
15793
15793
  if (this._readableState.closeEmitted) {
15794
15794
  return Promise.resolve(null);
15795
15795
  }
15796
- return new Promise((resolve15, reject) => {
15796
+ return new Promise((resolve16, reject) => {
15797
15797
  if (this[kContentLength] && this[kContentLength] > limit || this[kBytesRead] > limit) {
15798
15798
  this.destroy(new AbortError());
15799
15799
  }
@@ -15807,11 +15807,11 @@ var require_readable = __commonJS({
15807
15807
  if (signal.aborted) {
15808
15808
  reject(signal.reason ?? new AbortError());
15809
15809
  } else {
15810
- resolve15(null);
15810
+ resolve16(null);
15811
15811
  }
15812
15812
  });
15813
15813
  } else {
15814
- this.on("close", resolve15);
15814
+ this.on("close", resolve16);
15815
15815
  }
15816
15816
  this.on("error", noop2).on("data", () => {
15817
15817
  if (this[kBytesRead] > limit) {
@@ -15839,7 +15839,7 @@ var require_readable = __commonJS({
15839
15839
  }
15840
15840
  function consume(stream, type) {
15841
15841
  assert4(!stream[kConsume]);
15842
- return new Promise((resolve15, reject) => {
15842
+ return new Promise((resolve16, reject) => {
15843
15843
  if (isUnusable(stream)) {
15844
15844
  const rState = stream._readableState;
15845
15845
  if (rState.destroyed && rState.closeEmitted === false) {
@@ -15854,7 +15854,7 @@ var require_readable = __commonJS({
15854
15854
  stream[kConsume] = {
15855
15855
  type,
15856
15856
  stream,
15857
- resolve: resolve15,
15857
+ resolve: resolve16,
15858
15858
  reject,
15859
15859
  length: 0,
15860
15860
  body: []
@@ -15928,18 +15928,18 @@ var require_readable = __commonJS({
15928
15928
  return buffer;
15929
15929
  }
15930
15930
  function consumeEnd(consume2, encoding) {
15931
- const { type, body, resolve: resolve15, stream, length } = consume2;
15931
+ const { type, body, resolve: resolve16, stream, length } = consume2;
15932
15932
  try {
15933
15933
  if (type === "text") {
15934
- resolve15(chunksDecode(body, length, encoding));
15934
+ resolve16(chunksDecode(body, length, encoding));
15935
15935
  } else if (type === "json") {
15936
- resolve15(JSON.parse(chunksDecode(body, length, encoding)));
15936
+ resolve16(JSON.parse(chunksDecode(body, length, encoding)));
15937
15937
  } else if (type === "arrayBuffer") {
15938
- resolve15(chunksConcat(body, length).buffer);
15938
+ resolve16(chunksConcat(body, length).buffer);
15939
15939
  } else if (type === "blob") {
15940
- resolve15(new Blob(body, { type: stream[kContentType] }));
15940
+ resolve16(new Blob(body, { type: stream[kContentType] }));
15941
15941
  } else if (type === "bytes") {
15942
- resolve15(chunksConcat(body, length));
15942
+ resolve16(chunksConcat(body, length));
15943
15943
  }
15944
15944
  consumeFinish(consume2);
15945
15945
  } catch (err) {
@@ -16129,9 +16129,9 @@ var require_api_request = __commonJS({
16129
16129
  };
16130
16130
  function request(opts, callback) {
16131
16131
  if (callback === void 0) {
16132
- return new Promise((resolve15, reject) => {
16132
+ return new Promise((resolve16, reject) => {
16133
16133
  request.call(this, opts, (err, data2) => {
16134
- return err ? reject(err) : resolve15(data2);
16134
+ return err ? reject(err) : resolve16(data2);
16135
16135
  });
16136
16136
  });
16137
16137
  }
@@ -16343,9 +16343,9 @@ var require_api_stream = __commonJS({
16343
16343
  };
16344
16344
  function stream(opts, factory, callback) {
16345
16345
  if (callback === void 0) {
16346
- return new Promise((resolve15, reject) => {
16346
+ return new Promise((resolve16, reject) => {
16347
16347
  stream.call(this, opts, factory, (err, data2) => {
16348
- return err ? reject(err) : resolve15(data2);
16348
+ return err ? reject(err) : resolve16(data2);
16349
16349
  });
16350
16350
  });
16351
16351
  }
@@ -16633,9 +16633,9 @@ var require_api_upgrade = __commonJS({
16633
16633
  };
16634
16634
  function upgrade(opts, callback) {
16635
16635
  if (callback === void 0) {
16636
- return new Promise((resolve15, reject) => {
16636
+ return new Promise((resolve16, reject) => {
16637
16637
  upgrade.call(this, opts, (err, data2) => {
16638
- return err ? reject(err) : resolve15(data2);
16638
+ return err ? reject(err) : resolve16(data2);
16639
16639
  });
16640
16640
  });
16641
16641
  }
@@ -16728,9 +16728,9 @@ var require_api_connect = __commonJS({
16728
16728
  };
16729
16729
  function connect3(opts, callback) {
16730
16730
  if (callback === void 0) {
16731
- return new Promise((resolve15, reject) => {
16731
+ return new Promise((resolve16, reject) => {
16732
16732
  connect3.call(this, opts, (err, data2) => {
16733
- return err ? reject(err) : resolve15(data2);
16733
+ return err ? reject(err) : resolve16(data2);
16734
16734
  });
16735
16735
  });
16736
16736
  }
@@ -16932,20 +16932,20 @@ var require_mock_utils = __commonJS({
16932
16932
  }
16933
16933
  return normalizedQp;
16934
16934
  }
16935
- function safeUrl(path31) {
16936
- if (typeof path31 !== "string") {
16937
- return path31;
16935
+ function safeUrl(path32) {
16936
+ if (typeof path32 !== "string") {
16937
+ return path32;
16938
16938
  }
16939
- const pathSegments = path31.split("?", 3);
16939
+ const pathSegments = path32.split("?", 3);
16940
16940
  if (pathSegments.length !== 2) {
16941
- return path31;
16941
+ return path32;
16942
16942
  }
16943
16943
  const qp = new URLSearchParams(pathSegments.pop());
16944
16944
  qp.sort();
16945
16945
  return [...pathSegments, qp.toString()].join("?");
16946
16946
  }
16947
- function matchKey(mockDispatch2, { path: path31, method, body, headers }) {
16948
- const pathMatch = matchValue(mockDispatch2.path, path31);
16947
+ function matchKey(mockDispatch2, { path: path32, method, body, headers }) {
16948
+ const pathMatch = matchValue(mockDispatch2.path, path32);
16949
16949
  const methodMatch = matchValue(mockDispatch2.method, method);
16950
16950
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
16951
16951
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -16970,8 +16970,8 @@ var require_mock_utils = __commonJS({
16970
16970
  const basePath = key3.query ? serializePathWithQuery(key3.path, key3.query) : key3.path;
16971
16971
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
16972
16972
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
16973
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path31, ignoreTrailingSlash }) => {
16974
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path31)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path31), resolvedPath);
16973
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path32, ignoreTrailingSlash }) => {
16974
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path32)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path32), resolvedPath);
16975
16975
  });
16976
16976
  if (matchedMockDispatches.length === 0) {
16977
16977
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -17010,19 +17010,19 @@ var require_mock_utils = __commonJS({
17010
17010
  mockDispatches.splice(index2, 1);
17011
17011
  }
17012
17012
  }
17013
- function removeTrailingSlash(path31) {
17014
- while (path31.endsWith("/")) {
17015
- path31 = path31.slice(0, -1);
17013
+ function removeTrailingSlash(path32) {
17014
+ while (path32.endsWith("/")) {
17015
+ path32 = path32.slice(0, -1);
17016
17016
  }
17017
- if (path31.length === 0) {
17018
- path31 = "/";
17017
+ if (path32.length === 0) {
17018
+ path32 = "/";
17019
17019
  }
17020
- return path31;
17020
+ return path32;
17021
17021
  }
17022
17022
  function buildKey(opts) {
17023
- const { path: path31, method, body, headers, query } = opts;
17023
+ const { path: path32, method, body, headers, query } = opts;
17024
17024
  return {
17025
- path: path31,
17025
+ path: path32,
17026
17026
  method,
17027
17027
  body,
17028
17028
  headers,
@@ -17712,10 +17712,10 @@ var require_pending_interceptors_formatter = __commonJS({
17712
17712
  }
17713
17713
  format(pendingInterceptors) {
17714
17714
  const withPrettyHeaders = pendingInterceptors.map(
17715
- ({ method, path: path31, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
17715
+ ({ method, path: path32, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
17716
17716
  Method: method,
17717
17717
  Origin: origin,
17718
- Path: path31,
17718
+ Path: path32,
17719
17719
  "Status code": statusCode,
17720
17720
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
17721
17721
  Invocations: timesInvoked,
@@ -17797,9 +17797,9 @@ var require_mock_agent = __commonJS({
17797
17797
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
17798
17798
  const dispatchOpts = { ...opts };
17799
17799
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
17800
- const [path31, searchParams] = dispatchOpts.path.split("?");
17800
+ const [path32, searchParams] = dispatchOpts.path.split("?");
17801
17801
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
17802
- dispatchOpts.path = `${path31}?${normalizedSearchParams}`;
17802
+ dispatchOpts.path = `${path32}?${normalizedSearchParams}`;
17803
17803
  }
17804
17804
  return this[kAgent].dispatch(dispatchOpts, handler);
17805
17805
  }
@@ -18004,7 +18004,7 @@ var require_snapshot_recorder = __commonJS({
18004
18004
  "node_modules/undici/lib/mock/snapshot-recorder.js"(exports2, module2) {
18005
18005
  "use strict";
18006
18006
  var { writeFile, readFile: readFile2, mkdir } = require("node:fs/promises");
18007
- var { dirname: dirname19, resolve: resolve15 } = require("node:path");
18007
+ var { dirname: dirname20, resolve: resolve16 } = require("node:path");
18008
18008
  var { setTimeout: setTimeout2, clearTimeout: clearTimeout2 } = require("node:timers");
18009
18009
  var { InvalidArgumentError, UndiciError } = require_errors();
18010
18010
  var { hashId, isUrlExcludedFactory, normalizeHeaders: normalizeHeaders2, createHeaderFilters } = require_snapshot_utils();
@@ -18200,12 +18200,12 @@ var require_snapshot_recorder = __commonJS({
18200
18200
  * @return {Promise<void>} - Resolves when snapshots are loaded
18201
18201
  */
18202
18202
  async loadSnapshots(filePath) {
18203
- const path31 = filePath || this.#snapshotPath;
18204
- if (!path31) {
18203
+ const path32 = filePath || this.#snapshotPath;
18204
+ if (!path32) {
18205
18205
  throw new InvalidArgumentError("Snapshot path is required");
18206
18206
  }
18207
18207
  try {
18208
- const data2 = await readFile2(resolve15(path31), "utf8");
18208
+ const data2 = await readFile2(resolve16(path32), "utf8");
18209
18209
  const parsed = JSON.parse(data2);
18210
18210
  if (Array.isArray(parsed)) {
18211
18211
  this.#snapshots.clear();
@@ -18219,7 +18219,7 @@ var require_snapshot_recorder = __commonJS({
18219
18219
  if (error2.code === "ENOENT") {
18220
18220
  this.#snapshots.clear();
18221
18221
  } else {
18222
- throw new UndiciError(`Failed to load snapshots from ${path31}`, { cause: error2 });
18222
+ throw new UndiciError(`Failed to load snapshots from ${path32}`, { cause: error2 });
18223
18223
  }
18224
18224
  }
18225
18225
  }
@@ -18230,12 +18230,12 @@ var require_snapshot_recorder = __commonJS({
18230
18230
  * @returns {Promise<void>} - Resolves when snapshots are saved
18231
18231
  */
18232
18232
  async saveSnapshots(filePath) {
18233
- const path31 = filePath || this.#snapshotPath;
18234
- if (!path31) {
18233
+ const path32 = filePath || this.#snapshotPath;
18234
+ if (!path32) {
18235
18235
  throw new InvalidArgumentError("Snapshot path is required");
18236
18236
  }
18237
- const resolvedPath = resolve15(path31);
18238
- await mkdir(dirname19(resolvedPath), { recursive: true });
18237
+ const resolvedPath = resolve16(path32);
18238
+ await mkdir(dirname20(resolvedPath), { recursive: true });
18239
18239
  const data2 = Array.from(this.#snapshots.entries()).map(([hash, snapshot2]) => ({
18240
18240
  hash,
18241
18241
  snapshot: snapshot2
@@ -18866,15 +18866,15 @@ var require_redirect_handler = __commonJS({
18866
18866
  return;
18867
18867
  }
18868
18868
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
18869
- const path31 = search ? `${pathname}${search}` : pathname;
18870
- const redirectUrlString = `${origin}${path31}`;
18869
+ const path32 = search ? `${pathname}${search}` : pathname;
18870
+ const redirectUrlString = `${origin}${path32}`;
18871
18871
  for (const historyUrl of this.history) {
18872
18872
  if (historyUrl.toString() === redirectUrlString) {
18873
18873
  throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
18874
18874
  }
18875
18875
  }
18876
18876
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
18877
- this.opts.path = path31;
18877
+ this.opts.path = path32;
18878
18878
  this.opts.origin = origin;
18879
18879
  this.opts.query = null;
18880
18880
  }
@@ -20643,10 +20643,10 @@ var require_cache_handler = __commonJS({
20643
20643
  }
20644
20644
  return locationUrl.pathname + locationUrl.search;
20645
20645
  }
20646
- function deleteCachedUri(store, cacheKey, path31) {
20646
+ function deleteCachedUri(store, cacheKey, path32) {
20647
20647
  deleteCachedValue(store, {
20648
20648
  ...cacheKey,
20649
- path: path31
20649
+ path: path32
20650
20650
  });
20651
20651
  for (let i = 0; i < util.safeHTTPMethods.length; i++) {
20652
20652
  const method = util.safeHTTPMethods[i];
@@ -20654,7 +20654,7 @@ var require_cache_handler = __commonJS({
20654
20654
  deleteCachedValue(store, {
20655
20655
  ...cacheKey,
20656
20656
  method,
20657
- path: path31
20657
+ path: path32
20658
20658
  });
20659
20659
  }
20660
20660
  }
@@ -20665,9 +20665,9 @@ var require_cache_handler = __commonJS({
20665
20665
  }
20666
20666
  const values = Array.isArray(headerValue) ? headerValue : [headerValue];
20667
20667
  for (let i = 0; i < values.length; i++) {
20668
- const path31 = getSameOriginPath(cacheKey, values[i]);
20669
- if (path31 !== void 0) {
20670
- deleteCachedUri(store, cacheKey, path31);
20668
+ const path32 = getSameOriginPath(cacheKey, values[i]);
20669
+ if (path32 !== void 0) {
20670
+ deleteCachedUri(store, cacheKey, path32);
20671
20671
  }
20672
20672
  }
20673
20673
  }
@@ -25545,11 +25545,11 @@ var require_fetch = __commonJS({
25545
25545
  function dispatch({ body }) {
25546
25546
  const url2 = requestCurrentURL(request);
25547
25547
  const agent = fetchParams.controller.dispatcher;
25548
- const path31 = url2.pathname + url2.search;
25548
+ const path32 = url2.pathname + url2.search;
25549
25549
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
25550
- return new Promise((resolve15, reject) => agent.dispatch(
25550
+ return new Promise((resolve16, reject) => agent.dispatch(
25551
25551
  {
25552
- path: hasTrailingQuestionMark ? `${path31}?` : path31,
25552
+ path: hasTrailingQuestionMark ? `${path32}?` : path32,
25553
25553
  origin: url2.origin,
25554
25554
  method: request.method,
25555
25555
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -25635,7 +25635,7 @@ var require_fetch = __commonJS({
25635
25635
  }
25636
25636
  }
25637
25637
  const onError = this.onError.bind(this);
25638
- resolve15({
25638
+ resolve16({
25639
25639
  status,
25640
25640
  statusText,
25641
25641
  headersList,
@@ -25688,7 +25688,7 @@ var require_fetch = __commonJS({
25688
25688
  headersList.append(headerName, String(value), true);
25689
25689
  }
25690
25690
  }
25691
- resolve15({
25691
+ resolve16({
25692
25692
  status,
25693
25693
  statusText: STATUS_CODES[status],
25694
25694
  headersList,
@@ -25712,7 +25712,7 @@ var require_fetch = __commonJS({
25712
25712
  headersList.append(nameStr, value.toString("latin1"), true);
25713
25713
  }
25714
25714
  }
25715
- resolve15({
25715
+ resolve16({
25716
25716
  status,
25717
25717
  statusText: STATUS_CODES[status],
25718
25718
  headersList,
@@ -26496,9 +26496,9 @@ var require_util4 = __commonJS({
26496
26496
  }
26497
26497
  }
26498
26498
  }
26499
- function validateCookiePath(path31) {
26500
- for (let i = 0; i < path31.length; ++i) {
26501
- const code = path31.charCodeAt(i);
26499
+ function validateCookiePath(path32) {
26500
+ for (let i = 0; i < path32.length; ++i) {
26501
+ const code = path32.charCodeAt(i);
26502
26502
  if (code < 32 || // exclude CTLs (0-31)
26503
26503
  code > 126 || // exclude DEL and non-ascii
26504
26504
  code === 59) {
@@ -29735,11 +29735,11 @@ var require_undici = __commonJS({
29735
29735
  if (typeof opts.path !== "string") {
29736
29736
  throw new InvalidArgumentError("invalid opts.path");
29737
29737
  }
29738
- let path31 = opts.path;
29738
+ let path32 = opts.path;
29739
29739
  if (!opts.path.startsWith("/")) {
29740
- path31 = `/${path31}`;
29740
+ path32 = `/${path32}`;
29741
29741
  }
29742
- url2 = new URL(util.parseOrigin(url2).origin + path31);
29742
+ url2 = new URL(util.parseOrigin(url2).origin + path32);
29743
29743
  } else {
29744
29744
  if (!opts) {
29745
29745
  opts = typeof url2 === "object" ? url2 : {};
@@ -30742,7 +30742,7 @@ var init_dist = __esm({
30742
30742
 
30743
30743
  // node_modules/https-proxy-agent/dist/parse-proxy-response.js
30744
30744
  function parseProxyResponse(socket) {
30745
- return new Promise((resolve15, reject) => {
30745
+ return new Promise((resolve16, reject) => {
30746
30746
  let buffersLength = 0;
30747
30747
  const buffers = [];
30748
30748
  function read() {
@@ -30808,7 +30808,7 @@ function parseProxyResponse(socket) {
30808
30808
  }
30809
30809
  debug("got proxy server response: %o %o", firstLine, headers);
30810
30810
  cleanup();
30811
- resolve15({
30811
+ resolve16({
30812
30812
  connect: {
30813
30813
  statusCode,
30814
30814
  statusText,
@@ -39815,7 +39815,7 @@ var require_runtime = __commonJS({
39815
39815
  return { __await: arg };
39816
39816
  };
39817
39817
  function AsyncIterator(generator, PromiseImpl) {
39818
- function invoke(method, arg, resolve15, reject) {
39818
+ function invoke(method, arg, resolve16, reject) {
39819
39819
  var record3 = tryCatch(generator[method], generator, arg);
39820
39820
  if (record3.type === "throw") {
39821
39821
  reject(record3.arg);
@@ -39824,24 +39824,24 @@ var require_runtime = __commonJS({
39824
39824
  var value = result.value;
39825
39825
  if (value && typeof value === "object" && hasOwn2.call(value, "__await")) {
39826
39826
  return PromiseImpl.resolve(value.__await).then(function(value2) {
39827
- invoke("next", value2, resolve15, reject);
39827
+ invoke("next", value2, resolve16, reject);
39828
39828
  }, function(err) {
39829
- invoke("throw", err, resolve15, reject);
39829
+ invoke("throw", err, resolve16, reject);
39830
39830
  });
39831
39831
  }
39832
39832
  return PromiseImpl.resolve(value).then(function(unwrapped) {
39833
39833
  result.value = unwrapped;
39834
- resolve15(result);
39834
+ resolve16(result);
39835
39835
  }, function(error2) {
39836
- return invoke("throw", error2, resolve15, reject);
39836
+ return invoke("throw", error2, resolve16, reject);
39837
39837
  });
39838
39838
  }
39839
39839
  }
39840
39840
  var previousPromise;
39841
39841
  function enqueue(method, arg) {
39842
39842
  function callInvokeWithMethodAndArg() {
39843
- return new PromiseImpl(function(resolve15, reject) {
39844
- invoke(method, arg, resolve15, reject);
39843
+ return new PromiseImpl(function(resolve16, reject) {
39844
+ invoke(method, arg, resolve16, reject);
39845
39845
  });
39846
39846
  }
39847
39847
  return previousPromise = // If enqueue has been called before, then we want to wait until
@@ -40299,13 +40299,13 @@ var require_createScheduler = __commonJS({
40299
40299
  }
40300
40300
  }
40301
40301
  };
40302
- const queue = (action, payload) => new Promise((resolve15, reject) => {
40302
+ const queue = (action, payload) => new Promise((resolve16, reject) => {
40303
40303
  const job = createJob({ action, payload });
40304
40304
  jobQueue.push(async (w) => {
40305
40305
  jobQueue.shift();
40306
40306
  runningWorkers[w.id] = job;
40307
40307
  try {
40308
- resolve15(await w[action].apply(exports2, [...payload, job.id]));
40308
+ resolve16(await w[action].apply(exports2, [...payload, job.id]));
40309
40309
  } catch (err) {
40310
40310
  reject(err);
40311
40311
  } finally {
@@ -40420,11 +40420,11 @@ var require_defaultOptions = __commonJS({
40420
40420
  var require_defaultOptions2 = __commonJS({
40421
40421
  "node_modules/tesseract.js/src/worker/node/defaultOptions.js"(exports2, module2) {
40422
40422
  "use strict";
40423
- var path31 = require("path");
40423
+ var path32 = require("path");
40424
40424
  var defaultOptions2 = require_defaultOptions();
40425
40425
  module2.exports = {
40426
40426
  ...defaultOptions2,
40427
- workerPath: path31.join(__dirname, "..", "..", "worker-script", "node", "index.js")
40427
+ workerPath: path32.join(__dirname, "..", "..", "worker-script", "node", "index.js")
40428
40428
  };
40429
40429
  }
40430
40430
  });
@@ -41200,14 +41200,14 @@ var require_url_state_machine = __commonJS({
41200
41200
  return url2.replace(/\u0009|\u000A|\u000D/g, "");
41201
41201
  }
41202
41202
  function shortenPath(url2) {
41203
- const path31 = url2.path;
41204
- if (path31.length === 0) {
41203
+ const path32 = url2.path;
41204
+ if (path32.length === 0) {
41205
41205
  return;
41206
41206
  }
41207
- if (url2.scheme === "file" && path31.length === 1 && isNormalizedWindowsDriveLetter(path31[0])) {
41207
+ if (url2.scheme === "file" && path32.length === 1 && isNormalizedWindowsDriveLetter(path32[0])) {
41208
41208
  return;
41209
41209
  }
41210
- path31.pop();
41210
+ path32.pop();
41211
41211
  }
41212
41212
  function includesCredentials(url2) {
41213
41213
  return url2.username !== "" || url2.password !== "";
@@ -42527,7 +42527,7 @@ var require_lib4 = __commonJS({
42527
42527
  let accum = [];
42528
42528
  let accumBytes = 0;
42529
42529
  let abort = false;
42530
- return new Body.Promise(function(resolve15, reject) {
42530
+ return new Body.Promise(function(resolve16, reject) {
42531
42531
  let resTimeout;
42532
42532
  if (_this4.timeout) {
42533
42533
  resTimeout = setTimeout(function() {
@@ -42561,7 +42561,7 @@ var require_lib4 = __commonJS({
42561
42561
  }
42562
42562
  clearTimeout(resTimeout);
42563
42563
  try {
42564
- resolve15(Buffer.concat(accum, accumBytes));
42564
+ resolve16(Buffer.concat(accum, accumBytes));
42565
42565
  } catch (err) {
42566
42566
  reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, "system", err));
42567
42567
  }
@@ -43236,7 +43236,7 @@ var require_lib4 = __commonJS({
43236
43236
  throw new Error("native promise missing, set fetch.Promise to your favorite alternative");
43237
43237
  }
43238
43238
  Body.Promise = fetch3.Promise;
43239
- return new fetch3.Promise(function(resolve15, reject) {
43239
+ return new fetch3.Promise(function(resolve16, reject) {
43240
43240
  const request = new Request(url2, opts);
43241
43241
  const options = getNodeRequestOptions(request);
43242
43242
  const send = (options.protocol === "https:" ? https2 : http3).request;
@@ -43369,7 +43369,7 @@ var require_lib4 = __commonJS({
43369
43369
  requestOpts.body = void 0;
43370
43370
  requestOpts.headers.delete("content-length");
43371
43371
  }
43372
- resolve15(fetch3(new Request(locationURL, requestOpts)));
43372
+ resolve16(fetch3(new Request(locationURL, requestOpts)));
43373
43373
  finalize2();
43374
43374
  return;
43375
43375
  }
@@ -43390,7 +43390,7 @@ var require_lib4 = __commonJS({
43390
43390
  const codings = headers.get("Content-Encoding");
43391
43391
  if (!request.compress || request.method === "HEAD" || codings === null || res.statusCode === 204 || res.statusCode === 304) {
43392
43392
  response = new Response2(body, response_options);
43393
- resolve15(response);
43393
+ resolve16(response);
43394
43394
  return;
43395
43395
  }
43396
43396
  const zlibOptions = {
@@ -43400,7 +43400,7 @@ var require_lib4 = __commonJS({
43400
43400
  if (codings == "gzip" || codings == "x-gzip") {
43401
43401
  body = body.pipe(zlib.createGunzip(zlibOptions));
43402
43402
  response = new Response2(body, response_options);
43403
- resolve15(response);
43403
+ resolve16(response);
43404
43404
  return;
43405
43405
  }
43406
43406
  if (codings == "deflate" || codings == "x-deflate") {
@@ -43412,12 +43412,12 @@ var require_lib4 = __commonJS({
43412
43412
  body = body.pipe(zlib.createInflateRaw());
43413
43413
  }
43414
43414
  response = new Response2(body, response_options);
43415
- resolve15(response);
43415
+ resolve16(response);
43416
43416
  });
43417
43417
  raw.on("end", function() {
43418
43418
  if (!response) {
43419
43419
  response = new Response2(body, response_options);
43420
- resolve15(response);
43420
+ resolve16(response);
43421
43421
  }
43422
43422
  });
43423
43423
  return;
@@ -43425,11 +43425,11 @@ var require_lib4 = __commonJS({
43425
43425
  if (codings == "br" && typeof zlib.createBrotliDecompress === "function") {
43426
43426
  body = body.pipe(zlib.createBrotliDecompress());
43427
43427
  response = new Response2(body, response_options);
43428
- resolve15(response);
43428
+ resolve16(response);
43429
43429
  return;
43430
43430
  }
43431
43431
  response = new Response2(body, response_options);
43432
- resolve15(response);
43432
+ resolve16(response);
43433
43433
  });
43434
43434
  writeToStream(req, request);
43435
43435
  });
@@ -43508,10 +43508,10 @@ var require_loadImage = __commonJS({
43508
43508
  "node_modules/tesseract.js/src/worker/node/loadImage.js"(exports2, module2) {
43509
43509
  "use strict";
43510
43510
  var util = require("util");
43511
- var fs29 = require("fs");
43511
+ var fs30 = require("fs");
43512
43512
  var fetch3 = global.fetch || require_lib4();
43513
43513
  var isURL = require_is_url();
43514
- var readFile2 = util.promisify(fs29.readFile);
43514
+ var readFile2 = util.promisify(fs30.readFile);
43515
43515
  module2.exports = async (image) => {
43516
43516
  let data2 = image;
43517
43517
  if (typeof image === "undefined") {
@@ -43590,8 +43590,8 @@ var require_createWorker = __commonJS({
43590
43590
  const lstmOnlyCore = [OEM.DEFAULT, OEM.LSTM_ONLY].includes(oem) && !options.legacyCore;
43591
43591
  let workerResReject;
43592
43592
  let workerResResolve;
43593
- const workerRes = new Promise((resolve15, reject) => {
43594
- workerResResolve = resolve15;
43593
+ const workerRes = new Promise((resolve16, reject) => {
43594
+ workerResResolve = resolve16;
43595
43595
  workerResReject = reject;
43596
43596
  });
43597
43597
  const workerError = (event) => {
@@ -43600,10 +43600,10 @@ var require_createWorker = __commonJS({
43600
43600
  let worker = spawnWorker(options);
43601
43601
  worker.onerror = workerError;
43602
43602
  workerCounter += 1;
43603
- const startJob = ({ id: jobId, action, payload }) => new Promise((resolve15, reject) => {
43603
+ const startJob = ({ id: jobId, action, payload }) => new Promise((resolve16, reject) => {
43604
43604
  log(`[${id}]: Start ${jobId}, action=${action}`);
43605
43605
  const promiseId = `${action}-${jobId}`;
43606
- promises4[promiseId] = { resolve: resolve15, reject };
43606
+ promises4[promiseId] = { resolve: resolve16, reject };
43607
43607
  send(worker, {
43608
43608
  workerId: id,
43609
43609
  jobId,
@@ -43617,20 +43617,20 @@ var require_createWorker = __commonJS({
43617
43617
  action: "load",
43618
43618
  payload: { options: { lstmOnly: lstmOnlyCore, corePath: options.corePath, logging: options.logging } }
43619
43619
  }));
43620
- const writeText = (path31, text3, jobId) => startJob(createJob({
43620
+ const writeText = (path32, text3, jobId) => startJob(createJob({
43621
43621
  id: jobId,
43622
43622
  action: "FS",
43623
- payload: { method: "writeFile", args: [path31, text3] }
43623
+ payload: { method: "writeFile", args: [path32, text3] }
43624
43624
  }));
43625
- const readText = (path31, jobId) => startJob(createJob({
43625
+ const readText = (path32, jobId) => startJob(createJob({
43626
43626
  id: jobId,
43627
43627
  action: "FS",
43628
- payload: { method: "readFile", args: [path31, { encoding: "utf8" }] }
43628
+ payload: { method: "readFile", args: [path32, { encoding: "utf8" }] }
43629
43629
  }));
43630
- const removeFile = (path31, jobId) => startJob(createJob({
43630
+ const removeFile = (path32, jobId) => startJob(createJob({
43631
43631
  id: jobId,
43632
43632
  action: "FS",
43633
- payload: { method: "unlink", args: [path31] }
43633
+ payload: { method: "unlink", args: [path32] }
43634
43634
  }));
43635
43635
  const FS = (method, args, jobId) => startJob(createJob({
43636
43636
  id: jobId,
@@ -46877,7 +46877,7 @@ var require_compile = __commonJS({
46877
46877
  const schOrFunc = root3.refs[ref];
46878
46878
  if (schOrFunc)
46879
46879
  return schOrFunc;
46880
- let _sch = resolve15.call(this, root3, ref);
46880
+ let _sch = resolve16.call(this, root3, ref);
46881
46881
  if (_sch === void 0) {
46882
46882
  const schema = (_a9 = root3.localRefs) === null || _a9 === void 0 ? void 0 : _a9[ref];
46883
46883
  const { schemaId } = this.opts;
@@ -46904,7 +46904,7 @@ var require_compile = __commonJS({
46904
46904
  function sameSchemaEnv(s1, s2) {
46905
46905
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
46906
46906
  }
46907
- function resolve15(root3, ref) {
46907
+ function resolve16(root3, ref) {
46908
46908
  let sch;
46909
46909
  while (typeof (sch = this.refs[ref]) == "string")
46910
46910
  ref = sch;
@@ -47122,8 +47122,8 @@ var require_utils4 = __commonJS({
47122
47122
  }
47123
47123
  return ind;
47124
47124
  }
47125
- function removeDotSegments(path31) {
47126
- let input2 = path31;
47125
+ function removeDotSegments(path32) {
47126
+ let input2 = path32;
47127
47127
  const output = [];
47128
47128
  let nextSlash = -1;
47129
47129
  let len = 0;
@@ -47375,8 +47375,8 @@ var require_schemes = __commonJS({
47375
47375
  wsComponent.secure = void 0;
47376
47376
  }
47377
47377
  if (wsComponent.resourceName) {
47378
- const [path31, query] = wsComponent.resourceName.split("?");
47379
- wsComponent.path = path31 && path31 !== "/" ? path31 : void 0;
47378
+ const [path32, query] = wsComponent.resourceName.split("?");
47379
+ wsComponent.path = path32 && path32 !== "/" ? path32 : void 0;
47380
47380
  wsComponent.query = query;
47381
47381
  wsComponent.resourceName = void 0;
47382
47382
  }
@@ -47535,7 +47535,7 @@ var require_fast_uri = __commonJS({
47535
47535
  }
47536
47536
  return uri;
47537
47537
  }
47538
- function resolve15(baseURI, relativeURI, options) {
47538
+ function resolve16(baseURI, relativeURI, options) {
47539
47539
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
47540
47540
  const { parsed: baseParsed, malformedAuthorityOrPort: baseMalformed } = parseWithStatus(baseURI, schemelessOptions);
47541
47541
  const { parsed: relativeParsed, malformedAuthorityOrPort: relativeMalformed } = parseWithStatus(relativeURI, schemelessOptions);
@@ -47819,7 +47819,7 @@ var require_fast_uri = __commonJS({
47819
47819
  var fastUri = {
47820
47820
  SCHEMES,
47821
47821
  normalize: normalize2,
47822
- resolve: resolve15,
47822
+ resolve: resolve16,
47823
47823
  resolveComponent,
47824
47824
  equal,
47825
47825
  serialize: serialize5,
@@ -50795,12 +50795,12 @@ var require_dist = __commonJS({
50795
50795
  throw new Error(`Unknown format "${name}"`);
50796
50796
  return f;
50797
50797
  };
50798
- function addFormats(ajv, list, fs29, exportName) {
50798
+ function addFormats(ajv, list, fs30, exportName) {
50799
50799
  var _a9;
50800
50800
  var _b;
50801
50801
  (_a9 = (_b = ajv.opts.code).formats) !== null && _a9 !== void 0 ? _a9 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
50802
50802
  for (const f of list)
50803
- ajv.addFormat(f, fs29[f]);
50803
+ ajv.addFormat(f, fs30[f]);
50804
50804
  }
50805
50805
  module2.exports = exports2 = formatsPlugin;
50806
50806
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -50813,8 +50813,8 @@ var require_windows = __commonJS({
50813
50813
  "node_modules/cross-spawn/node_modules/isexe/windows.js"(exports2, module2) {
50814
50814
  module2.exports = isexe;
50815
50815
  isexe.sync = sync;
50816
- var fs29 = require("fs");
50817
- function checkPathExt(path31, options) {
50816
+ var fs30 = require("fs");
50817
+ function checkPathExt(path32, options) {
50818
50818
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
50819
50819
  if (!pathext) {
50820
50820
  return true;
@@ -50825,25 +50825,25 @@ var require_windows = __commonJS({
50825
50825
  }
50826
50826
  for (var i = 0; i < pathext.length; i++) {
50827
50827
  var p = pathext[i].toLowerCase();
50828
- if (p && path31.substr(-p.length).toLowerCase() === p) {
50828
+ if (p && path32.substr(-p.length).toLowerCase() === p) {
50829
50829
  return true;
50830
50830
  }
50831
50831
  }
50832
50832
  return false;
50833
50833
  }
50834
- function checkStat(stat, path31, options) {
50834
+ function checkStat(stat, path32, options) {
50835
50835
  if (!stat.isSymbolicLink() && !stat.isFile()) {
50836
50836
  return false;
50837
50837
  }
50838
- return checkPathExt(path31, options);
50838
+ return checkPathExt(path32, options);
50839
50839
  }
50840
- function isexe(path31, options, cb) {
50841
- fs29.stat(path31, function(er, stat) {
50842
- cb(er, er ? false : checkStat(stat, path31, options));
50840
+ function isexe(path32, options, cb) {
50841
+ fs30.stat(path32, function(er, stat) {
50842
+ cb(er, er ? false : checkStat(stat, path32, options));
50843
50843
  });
50844
50844
  }
50845
- function sync(path31, options) {
50846
- return checkStat(fs29.statSync(path31), path31, options);
50845
+ function sync(path32, options) {
50846
+ return checkStat(fs30.statSync(path32), path32, options);
50847
50847
  }
50848
50848
  }
50849
50849
  });
@@ -50853,14 +50853,14 @@ var require_mode = __commonJS({
50853
50853
  "node_modules/cross-spawn/node_modules/isexe/mode.js"(exports2, module2) {
50854
50854
  module2.exports = isexe;
50855
50855
  isexe.sync = sync;
50856
- var fs29 = require("fs");
50857
- function isexe(path31, options, cb) {
50858
- fs29.stat(path31, function(er, stat) {
50856
+ var fs30 = require("fs");
50857
+ function isexe(path32, options, cb) {
50858
+ fs30.stat(path32, function(er, stat) {
50859
50859
  cb(er, er ? false : checkStat(stat, options));
50860
50860
  });
50861
50861
  }
50862
- function sync(path31, options) {
50863
- return checkStat(fs29.statSync(path31), options);
50862
+ function sync(path32, options) {
50863
+ return checkStat(fs30.statSync(path32), options);
50864
50864
  }
50865
50865
  function checkStat(stat, options) {
50866
50866
  return stat.isFile() && checkMode(stat, options);
@@ -50884,7 +50884,7 @@ var require_mode = __commonJS({
50884
50884
  // node_modules/cross-spawn/node_modules/isexe/index.js
50885
50885
  var require_isexe = __commonJS({
50886
50886
  "node_modules/cross-spawn/node_modules/isexe/index.js"(exports2, module2) {
50887
- var fs29 = require("fs");
50887
+ var fs30 = require("fs");
50888
50888
  var core;
50889
50889
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
50890
50890
  core = require_windows();
@@ -50893,7 +50893,7 @@ var require_isexe = __commonJS({
50893
50893
  }
50894
50894
  module2.exports = isexe;
50895
50895
  isexe.sync = sync;
50896
- function isexe(path31, options, cb) {
50896
+ function isexe(path32, options, cb) {
50897
50897
  if (typeof options === "function") {
50898
50898
  cb = options;
50899
50899
  options = {};
@@ -50902,17 +50902,17 @@ var require_isexe = __commonJS({
50902
50902
  if (typeof Promise !== "function") {
50903
50903
  throw new TypeError("callback not provided");
50904
50904
  }
50905
- return new Promise(function(resolve15, reject) {
50906
- isexe(path31, options || {}, function(er, is4) {
50905
+ return new Promise(function(resolve16, reject) {
50906
+ isexe(path32, options || {}, function(er, is4) {
50907
50907
  if (er) {
50908
50908
  reject(er);
50909
50909
  } else {
50910
- resolve15(is4);
50910
+ resolve16(is4);
50911
50911
  }
50912
50912
  });
50913
50913
  });
50914
50914
  }
50915
- core(path31, options || {}, function(er, is4) {
50915
+ core(path32, options || {}, function(er, is4) {
50916
50916
  if (er) {
50917
50917
  if (er.code === "EACCES" || options && options.ignoreErrors) {
50918
50918
  er = null;
@@ -50922,9 +50922,9 @@ var require_isexe = __commonJS({
50922
50922
  cb(er, is4);
50923
50923
  });
50924
50924
  }
50925
- function sync(path31, options) {
50925
+ function sync(path32, options) {
50926
50926
  try {
50927
- return core.sync(path31, options || {});
50927
+ return core.sync(path32, options || {});
50928
50928
  } catch (er) {
50929
50929
  if (options && options.ignoreErrors || er.code === "EACCES") {
50930
50930
  return false;
@@ -50940,7 +50940,7 @@ var require_isexe = __commonJS({
50940
50940
  var require_which = __commonJS({
50941
50941
  "node_modules/cross-spawn/node_modules/which/which.js"(exports2, module2) {
50942
50942
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
50943
- var path31 = require("path");
50943
+ var path32 = require("path");
50944
50944
  var COLON = isWindows ? ";" : ":";
50945
50945
  var isexe = require_isexe();
50946
50946
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -50973,27 +50973,27 @@ var require_which = __commonJS({
50973
50973
  opt = {};
50974
50974
  const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
50975
50975
  const found = [];
50976
- const step = (i) => new Promise((resolve15, reject) => {
50976
+ const step = (i) => new Promise((resolve16, reject) => {
50977
50977
  if (i === pathEnv.length)
50978
- return opt.all && found.length ? resolve15(found) : reject(getNotFoundError(cmd));
50978
+ return opt.all && found.length ? resolve16(found) : reject(getNotFoundError(cmd));
50979
50979
  const ppRaw = pathEnv[i];
50980
50980
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
50981
- const pCmd = path31.join(pathPart, cmd);
50981
+ const pCmd = path32.join(pathPart, cmd);
50982
50982
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
50983
- resolve15(subStep(p, i, 0));
50983
+ resolve16(subStep(p, i, 0));
50984
50984
  });
50985
- const subStep = (p, i, ii) => new Promise((resolve15, reject) => {
50985
+ const subStep = (p, i, ii) => new Promise((resolve16, reject) => {
50986
50986
  if (ii === pathExt.length)
50987
- return resolve15(step(i + 1));
50987
+ return resolve16(step(i + 1));
50988
50988
  const ext = pathExt[ii];
50989
50989
  isexe(p + ext, { pathExt: pathExtExe }, (er, is4) => {
50990
50990
  if (!er && is4) {
50991
50991
  if (opt.all)
50992
50992
  found.push(p + ext);
50993
50993
  else
50994
- return resolve15(p + ext);
50994
+ return resolve16(p + ext);
50995
50995
  }
50996
- return resolve15(subStep(p, i, ii + 1));
50996
+ return resolve16(subStep(p, i, ii + 1));
50997
50997
  });
50998
50998
  });
50999
50999
  return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
@@ -51005,7 +51005,7 @@ var require_which = __commonJS({
51005
51005
  for (let i = 0; i < pathEnv.length; i++) {
51006
51006
  const ppRaw = pathEnv[i];
51007
51007
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
51008
- const pCmd = path31.join(pathPart, cmd);
51008
+ const pCmd = path32.join(pathPart, cmd);
51009
51009
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
51010
51010
  for (let j = 0; j < pathExt.length; j++) {
51011
51011
  const cur = p + pathExt[j];
@@ -51053,7 +51053,7 @@ var require_path_key = __commonJS({
51053
51053
  var require_resolveCommand = __commonJS({
51054
51054
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports2, module2) {
51055
51055
  "use strict";
51056
- var path31 = require("path");
51056
+ var path32 = require("path");
51057
51057
  var which = require_which();
51058
51058
  var getPathKey = require_path_key();
51059
51059
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -51071,7 +51071,7 @@ var require_resolveCommand = __commonJS({
51071
51071
  try {
51072
51072
  resolved = which.sync(parsed.command, {
51073
51073
  path: env[getPathKey({ env })],
51074
- pathExt: withoutPathExt ? path31.delimiter : void 0
51074
+ pathExt: withoutPathExt ? path32.delimiter : void 0
51075
51075
  });
51076
51076
  } catch (e) {
51077
51077
  } finally {
@@ -51080,7 +51080,7 @@ var require_resolveCommand = __commonJS({
51080
51080
  }
51081
51081
  }
51082
51082
  if (resolved) {
51083
- resolved = path31.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
51083
+ resolved = path32.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
51084
51084
  }
51085
51085
  return resolved;
51086
51086
  }
@@ -51134,8 +51134,8 @@ var require_shebang_command = __commonJS({
51134
51134
  if (!match) {
51135
51135
  return null;
51136
51136
  }
51137
- const [path31, argument] = match[0].replace(/#! ?/, "").split(" ");
51138
- const binary = path31.split("/").pop();
51137
+ const [path32, argument] = match[0].replace(/#! ?/, "").split(" ");
51138
+ const binary = path32.split("/").pop();
51139
51139
  if (binary === "env") {
51140
51140
  return argument;
51141
51141
  }
@@ -51148,16 +51148,16 @@ var require_shebang_command = __commonJS({
51148
51148
  var require_readShebang = __commonJS({
51149
51149
  "node_modules/cross-spawn/lib/util/readShebang.js"(exports2, module2) {
51150
51150
  "use strict";
51151
- var fs29 = require("fs");
51151
+ var fs30 = require("fs");
51152
51152
  var shebangCommand = require_shebang_command();
51153
51153
  function readShebang(command) {
51154
51154
  const size = 150;
51155
51155
  const buffer = Buffer.alloc(size);
51156
51156
  let fd;
51157
51157
  try {
51158
- fd = fs29.openSync(command, "r");
51159
- fs29.readSync(fd, buffer, 0, size, 0);
51160
- fs29.closeSync(fd);
51158
+ fd = fs30.openSync(command, "r");
51159
+ fs30.readSync(fd, buffer, 0, size, 0);
51160
+ fs30.closeSync(fd);
51161
51161
  } catch (e) {
51162
51162
  }
51163
51163
  return shebangCommand(buffer.toString());
@@ -51170,7 +51170,7 @@ var require_readShebang = __commonJS({
51170
51170
  var require_parse3 = __commonJS({
51171
51171
  "node_modules/cross-spawn/lib/parse.js"(exports2, module2) {
51172
51172
  "use strict";
51173
- var path31 = require("path");
51173
+ var path32 = require("path");
51174
51174
  var resolveCommand = require_resolveCommand();
51175
51175
  var escape3 = require_escape();
51176
51176
  var readShebang = require_readShebang();
@@ -51195,7 +51195,7 @@ var require_parse3 = __commonJS({
51195
51195
  const needsShell = !isExecutableRegExp.test(commandFile);
51196
51196
  if (parsed.options.forceShell || needsShell) {
51197
51197
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
51198
- parsed.command = path31.normalize(parsed.command);
51198
+ parsed.command = path32.normalize(parsed.command);
51199
51199
  parsed.command = escape3.command(parsed.command);
51200
51200
  parsed.args = parsed.args.map((arg) => escape3.argument(arg, needsDoubleEscapeMetaChars));
51201
51201
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -52188,7 +52188,7 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur
52188
52188
  g.minimatch.escape = vi.escape;
52189
52189
  g.minimatch.unescape = Ei.unescape;
52190
52190
  });
52191
- var fs29 = R((Wt) => {
52191
+ var fs30 = R((Wt) => {
52192
52192
  "use strict";
52193
52193
  Object.defineProperty(Wt, "__esModule", { value: true });
52194
52194
  Wt.LRUCache = void 0;
@@ -53057,7 +53057,7 @@ globstar while`, t, d, e, u, m), this.matchOne(t.slice(d), e.slice(u), s)) retur
53057
53057
  };
53058
53058
  Object.defineProperty(_, "__esModule", { value: true });
53059
53059
  _.PathScurry = _.Path = _.PathScurryDarwin = _.PathScurryPosix = _.PathScurryWin32 = _.PathScurryBase = _.PathPosix = _.PathWin32 = _.PathBase = _.ChildrenCache = _.ResolveCache = void 0;
53060
- var Qt = fs29(), Yt = require("node:path"), yr = require("node:url"), pt = require("fs"), Sr = br(require("node:fs")), vr = pt.realpathSync.native, Ht = require("node:fs/promises"), bs = Oe(), mt = { lstatSync: pt.lstatSync, readdir: pt.readdir, readdirSync: pt.readdirSync, readlinkSync: pt.readlinkSync, realpathSync: vr, promises: { lstat: Ht.lstat, readdir: Ht.readdir, readlink: Ht.readlink, realpath: Ht.realpath } }, _s = (n) => !n || n === mt || n === Sr ? mt : { ...mt, ...n, promises: { ...mt.promises, ...n.promises || {} } }, Os = /^\\\\\?\\([a-z]:)\\?$/i, Er = (n) => n.replace(/\//g, "\\").replace(Os, "$1\\"), _r = /[\\\/]/, N = 0, xs = 1, Ts = 2, G = 4, Cs = 6, Rs = 8, Q = 10, As = 12, j = 15, dt = ~j, xe = 16, ys = 32, gt = 64, W = 128, Vt = 256, Xt = 512, Ss = gt | W | Xt, Or = 1023, Te = (n) => n.isFile() ? Rs : n.isDirectory() ? G : n.isSymbolicLink() ? Q : n.isCharacterDevice() ? Ts : n.isBlockDevice() ? Cs : n.isSocket() ? As : n.isFIFO() ? xs : N, vs = new Qt.LRUCache({ max: 2 ** 12 }), wt = (n) => {
53060
+ var Qt = fs30(), Yt = require("node:path"), yr = require("node:url"), pt = require("fs"), Sr = br(require("node:fs")), vr = pt.realpathSync.native, Ht = require("node:fs/promises"), bs = Oe(), mt = { lstatSync: pt.lstatSync, readdir: pt.readdir, readdirSync: pt.readdirSync, readlinkSync: pt.readlinkSync, realpathSync: vr, promises: { lstat: Ht.lstat, readdir: Ht.readdir, readlink: Ht.readlink, realpath: Ht.realpath } }, _s = (n) => !n || n === mt || n === Sr ? mt : { ...mt, ...n, promises: { ...mt.promises, ...n.promises || {} } }, Os = /^\\\\\?\\([a-z]:)\\?$/i, Er = (n) => n.replace(/\//g, "\\").replace(Os, "$1\\"), _r = /[\\\/]/, N = 0, xs = 1, Ts = 2, G = 4, Cs = 6, Rs = 8, Q = 10, As = 12, j = 15, dt = ~j, xe = 16, ys = 32, gt = 64, W = 128, Vt = 256, Xt = 512, Ss = gt | W | Xt, Or = 1023, Te = (n) => n.isFile() ? Rs : n.isDirectory() ? G : n.isSymbolicLink() ? Q : n.isCharacterDevice() ? Ts : n.isBlockDevice() ? Cs : n.isSocket() ? As : n.isFIFO() ? xs : N, vs = new Qt.LRUCache({ max: 2 ** 12 }), wt = (n) => {
53061
53061
  let t = vs.get(n);
53062
53062
  if (t) return t;
53063
53063
  let e = n.normalize("NFKD");
@@ -54725,7 +54725,7 @@ async function fetchData(url2, type = "text") {
54725
54725
  }
54726
54726
  return response.text();
54727
54727
  }
54728
- return new Promise((resolve15, reject) => {
54728
+ return new Promise((resolve16, reject) => {
54729
54729
  const request = new XMLHttpRequest();
54730
54730
  request.open("GET", url2, true);
54731
54731
  request.responseType = type;
@@ -54738,10 +54738,10 @@ async function fetchData(url2, type = "text") {
54738
54738
  case "arraybuffer":
54739
54739
  case "blob":
54740
54740
  case "json":
54741
- resolve15(request.response);
54741
+ resolve16(request.response);
54742
54742
  return;
54743
54743
  }
54744
- resolve15(request.responseText);
54744
+ resolve16(request.responseText);
54745
54745
  return;
54746
54746
  }
54747
54747
  reject(new Error(request.statusText));
@@ -55008,8 +55008,8 @@ function wrapReason(ex) {
55008
55008
  return new UnknownErrorException(ex.message, ex.toString());
55009
55009
  }
55010
55010
  async function node_utils_fetchData(url2) {
55011
- const fs29 = process.getBuiltinModule("fs");
55012
- const data2 = await fs29.promises.readFile(url2);
55011
+ const fs30 = process.getBuiltinModule("fs");
55012
+ const data2 = await fs30.promises.readFile(url2);
55013
55013
  return new Uint8Array(data2);
55014
55014
  }
55015
55015
  function applyBoundingBox(ctx, bbox) {
@@ -55969,7 +55969,7 @@ var init_pdf = __esm({
55969
55969
  var defineProperty = Object.defineProperty;
55970
55970
  var stringSlice = uncurryThis("".slice);
55971
55971
  var replace = uncurryThis("".replace);
55972
- var join27 = uncurryThis([].join);
55972
+ var join28 = uncurryThis([].join);
55973
55973
  var CONFIGURABLE_LENGTH = DESCRIPTORS && !fails(function() {
55974
55974
  return defineProperty(function() {
55975
55975
  }, "length", { value: 8 }).length !== 8;
@@ -55996,7 +55996,7 @@ var init_pdf = __esm({
55996
55996
  }
55997
55997
  var state = enforceInternalState(value);
55998
55998
  if (!hasOwn2(state, "source")) {
55999
- state.source = join27(TEMPLATE, typeof name == "string" ? name : "");
55999
+ state.source = join28(TEMPLATE, typeof name == "string" ? name : "");
56000
56000
  }
56001
56001
  return value;
56002
56002
  };
@@ -58548,13 +58548,13 @@ var init_pdf = __esm({
58548
58548
  var aCallable = __webpack_require__2(9306);
58549
58549
  var $TypeError = TypeError;
58550
58550
  var PromiseCapability = function(C) {
58551
- var resolve15, reject;
58551
+ var resolve16, reject;
58552
58552
  this.promise = new C(function($$resolve, $$reject) {
58553
- if (resolve15 !== void 0 || reject !== void 0) throw new $TypeError("Bad Promise constructor");
58554
- resolve15 = $$resolve;
58553
+ if (resolve16 !== void 0 || reject !== void 0) throw new $TypeError("Bad Promise constructor");
58554
+ resolve16 = $$resolve;
58555
58555
  reject = $$reject;
58556
58556
  });
58557
- this.resolve = aCallable(resolve15);
58557
+ this.resolve = aCallable(resolve16);
58558
58558
  this.reject = aCallable(reject);
58559
58559
  };
58560
58560
  module2.exports.f = function(C) {
@@ -61753,11 +61753,11 @@ var init_pdf = __esm({
61753
61753
  const mustRemoveAspectRatioPromise = _ImageManager._isSVGFittingCanvas;
61754
61754
  const fileReader = new FileReader();
61755
61755
  const imageElement = new Image();
61756
- const imagePromise = new Promise((resolve15, reject) => {
61756
+ const imagePromise = new Promise((resolve16, reject) => {
61757
61757
  imageElement.onload = () => {
61758
61758
  data2.bitmap = imageElement;
61759
61759
  data2.isSvg = true;
61760
- resolve15();
61760
+ resolve16();
61761
61761
  };
61762
61762
  fileReader.onload = async () => {
61763
61763
  const url2 = data2.svgUrl = fileReader.result;
@@ -66033,8 +66033,8 @@ var init_pdf = __esm({
66033
66033
  if (this.isSyncFontLoadingSupported) {
66034
66034
  return;
66035
66035
  }
66036
- await new Promise((resolve15) => {
66037
- const request = this._queueLoadingCallback(resolve15);
66036
+ await new Promise((resolve16) => {
66037
+ const request = this._queueLoadingCallback(resolve16);
66038
66038
  this._prepareFontLoadEvent(font, request);
66039
66039
  });
66040
66040
  }
@@ -66191,11 +66191,11 @@ var init_pdf = __esm({
66191
66191
  } catch (ex) {
66192
66192
  warn(`getPathGenerator - ignoring character: "${ex}".`);
66193
66193
  }
66194
- const path31 = new Path2D(cmds || "");
66194
+ const path32 = new Path2D(cmds || "");
66195
66195
  if (!this.fontExtraProperties) {
66196
66196
  objs.delete(objId);
66197
66197
  }
66198
- return this.compiledGlyphs[character] = path31;
66198
+ return this.compiledGlyphs[character] = path32;
66199
66199
  }
66200
66200
  };
66201
66201
  isRefProxy = (v) => typeof v === "object" && Number.isInteger(v?.num) && v.num >= 0 && Number.isInteger(v?.gen) && v.gen >= 0;
@@ -68576,47 +68576,47 @@ var init_pdf = __esm({
68576
68576
  this._cachedGetSinglePixelWidth = null;
68577
68577
  }
68578
68578
  constructPath(opIdx, op, data2, minMax) {
68579
- let [path31] = data2;
68579
+ let [path32] = data2;
68580
68580
  if (!minMax) {
68581
- path31 ||= data2[0] = new Path2D();
68582
- this[op](opIdx, path31);
68581
+ path32 ||= data2[0] = new Path2D();
68582
+ this[op](opIdx, path32);
68583
68583
  return;
68584
68584
  }
68585
68585
  if (this.dependencyTracker !== null) {
68586
68586
  const outerExtraSize = op === OPS.stroke ? this.current.lineWidth / 2 : 0;
68587
68587
  this.dependencyTracker.resetBBox(opIdx).recordBBox(opIdx, this.ctx, minMax[0] - outerExtraSize, minMax[2] + outerExtraSize, minMax[1] - outerExtraSize, minMax[3] + outerExtraSize).recordDependencies(opIdx, ["transform"]);
68588
68588
  }
68589
- if (!(path31 instanceof Path2D)) {
68589
+ if (!(path32 instanceof Path2D)) {
68590
68590
  const path2d = data2[0] = new Path2D();
68591
- for (let i = 0, ii = path31.length; i < ii; ) {
68592
- switch (path31[i++]) {
68591
+ for (let i = 0, ii = path32.length; i < ii; ) {
68592
+ switch (path32[i++]) {
68593
68593
  case DrawOPS.moveTo:
68594
- path2d.moveTo(path31[i++], path31[i++]);
68594
+ path2d.moveTo(path32[i++], path32[i++]);
68595
68595
  break;
68596
68596
  case DrawOPS.lineTo:
68597
- path2d.lineTo(path31[i++], path31[i++]);
68597
+ path2d.lineTo(path32[i++], path32[i++]);
68598
68598
  break;
68599
68599
  case DrawOPS.curveTo:
68600
- path2d.bezierCurveTo(path31[i++], path31[i++], path31[i++], path31[i++], path31[i++], path31[i++]);
68600
+ path2d.bezierCurveTo(path32[i++], path32[i++], path32[i++], path32[i++], path32[i++], path32[i++]);
68601
68601
  break;
68602
68602
  case DrawOPS.closePath:
68603
68603
  path2d.closePath();
68604
68604
  break;
68605
68605
  default:
68606
- warn(`Unrecognized drawing path operator: ${path31[i - 1]}`);
68606
+ warn(`Unrecognized drawing path operator: ${path32[i - 1]}`);
68607
68607
  break;
68608
68608
  }
68609
68609
  }
68610
- path31 = path2d;
68610
+ path32 = path2d;
68611
68611
  }
68612
68612
  Util.axialAlignedBoundingBox(minMax, getCurrentTransform(this.ctx), this.current.minMax);
68613
- this[op](opIdx, path31);
68613
+ this[op](opIdx, path32);
68614
68614
  this._pathStartIdx = opIdx;
68615
68615
  }
68616
68616
  closePath(opIdx) {
68617
68617
  this.ctx.closePath();
68618
68618
  }
68619
- stroke(opIdx, path31, consumePath = true) {
68619
+ stroke(opIdx, path32, consumePath = true) {
68620
68620
  const ctx = this.ctx;
68621
68621
  const strokeColor = this.current.strokeColor;
68622
68622
  ctx.globalAlpha = this.current.strokeAlpha;
@@ -68627,25 +68627,25 @@ var init_pdf = __esm({
68627
68627
  ctx.strokeStyle = strokeColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.STROKE);
68628
68628
  if (baseTransform) {
68629
68629
  const newPath = new Path2D();
68630
- newPath.addPath(path31, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
68631
- path31 = newPath;
68630
+ newPath.addPath(path32, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
68631
+ path32 = newPath;
68632
68632
  }
68633
- this.rescaleAndStroke(path31, false);
68633
+ this.rescaleAndStroke(path32, false);
68634
68634
  ctx.restore();
68635
68635
  } else {
68636
- this.rescaleAndStroke(path31, true);
68636
+ this.rescaleAndStroke(path32, true);
68637
68637
  }
68638
68638
  }
68639
68639
  this.dependencyTracker?.recordDependencies(opIdx, Dependencies.stroke);
68640
68640
  if (consumePath) {
68641
- this.consumePath(opIdx, path31, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));
68641
+ this.consumePath(opIdx, path32, this.current.getClippedPathBoundingBox(PathType.STROKE, getCurrentTransform(this.ctx)));
68642
68642
  }
68643
68643
  ctx.globalAlpha = this.current.fillAlpha;
68644
68644
  }
68645
- closeStroke(opIdx, path31) {
68646
- this.stroke(opIdx, path31);
68645
+ closeStroke(opIdx, path32) {
68646
+ this.stroke(opIdx, path32);
68647
68647
  }
68648
- fill(opIdx, path31, consumePath = true) {
68648
+ fill(opIdx, path32, consumePath = true) {
68649
68649
  const ctx = this.ctx;
68650
68650
  const fillColor = this.current.fillColor;
68651
68651
  const isPatternFill = this.current.patternFill;
@@ -68657,18 +68657,18 @@ var init_pdf = __esm({
68657
68657
  ctx.fillStyle = fillColor.getPattern(ctx, this, getCurrentTransformInverse(ctx), PathType.FILL);
68658
68658
  if (baseTransform) {
68659
68659
  const newPath = new Path2D();
68660
- newPath.addPath(path31, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
68661
- path31 = newPath;
68660
+ newPath.addPath(path32, ctx.getTransform().invertSelf().multiplySelf(baseTransform));
68661
+ path32 = newPath;
68662
68662
  }
68663
68663
  needRestore = true;
68664
68664
  }
68665
68665
  const intersect = this.current.getClippedPathBoundingBox();
68666
68666
  if (this.contentVisible && intersect !== null) {
68667
68667
  if (this.pendingEOFill) {
68668
- ctx.fill(path31, "evenodd");
68668
+ ctx.fill(path32, "evenodd");
68669
68669
  this.pendingEOFill = false;
68670
68670
  } else {
68671
- ctx.fill(path31);
68671
+ ctx.fill(path32);
68672
68672
  }
68673
68673
  }
68674
68674
  this.dependencyTracker?.recordDependencies(opIdx, Dependencies.fill);
@@ -68677,34 +68677,34 @@ var init_pdf = __esm({
68677
68677
  this.dependencyTracker?.restore(opIdx);
68678
68678
  }
68679
68679
  if (consumePath) {
68680
- this.consumePath(opIdx, path31, intersect);
68680
+ this.consumePath(opIdx, path32, intersect);
68681
68681
  }
68682
68682
  }
68683
- eoFill(opIdx, path31) {
68683
+ eoFill(opIdx, path32) {
68684
68684
  this.pendingEOFill = true;
68685
- this.fill(opIdx, path31);
68685
+ this.fill(opIdx, path32);
68686
68686
  }
68687
- fillStroke(opIdx, path31) {
68688
- this.fill(opIdx, path31, false);
68689
- this.stroke(opIdx, path31, false);
68690
- this.consumePath(opIdx, path31);
68687
+ fillStroke(opIdx, path32) {
68688
+ this.fill(opIdx, path32, false);
68689
+ this.stroke(opIdx, path32, false);
68690
+ this.consumePath(opIdx, path32);
68691
68691
  }
68692
- eoFillStroke(opIdx, path31) {
68692
+ eoFillStroke(opIdx, path32) {
68693
68693
  this.pendingEOFill = true;
68694
- this.fillStroke(opIdx, path31);
68694
+ this.fillStroke(opIdx, path32);
68695
68695
  }
68696
- closeFillStroke(opIdx, path31) {
68697
- this.fillStroke(opIdx, path31);
68696
+ closeFillStroke(opIdx, path32) {
68697
+ this.fillStroke(opIdx, path32);
68698
68698
  }
68699
- closeEOFillStroke(opIdx, path31) {
68699
+ closeEOFillStroke(opIdx, path32) {
68700
68700
  this.pendingEOFill = true;
68701
- this.fillStroke(opIdx, path31);
68701
+ this.fillStroke(opIdx, path32);
68702
68702
  }
68703
- endPath(opIdx, path31) {
68704
- this.consumePath(opIdx, path31);
68703
+ endPath(opIdx, path32) {
68704
+ this.consumePath(opIdx, path32);
68705
68705
  }
68706
- rawFillPath(opIdx, path31) {
68707
- this.ctx.fill(path31);
68706
+ rawFillPath(opIdx, path32) {
68707
+ this.ctx.fill(path32);
68708
68708
  this.dependencyTracker?.recordDependencies(opIdx, Dependencies.rawFillPath).recordOperation(opIdx);
68709
68709
  }
68710
68710
  clip(opIdx) {
@@ -68742,12 +68742,12 @@ var init_pdf = __esm({
68742
68742
  x,
68743
68743
  y,
68744
68744
  fontSize,
68745
- path: path31
68745
+ path: path32
68746
68746
  } of paths) {
68747
- if (!path31) {
68747
+ if (!path32) {
68748
68748
  continue;
68749
68749
  }
68750
- newPath.addPath(path31, new DOMMatrix(transform2).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize));
68750
+ newPath.addPath(path32, new DOMMatrix(transform2).preMultiplySelf(invTransf).translate(x, y).scale(fontSize, -fontSize));
68751
68751
  }
68752
68752
  ctx.clip(newPath);
68753
68753
  }
@@ -68840,9 +68840,9 @@ var init_pdf = __esm({
68840
68840
  this.moveText(opIdx, 0, this.current.leading);
68841
68841
  this.dependencyTracker?.recordIncrementalData("moveText", this.dependencyTracker.getSimpleIndex("leading") ?? opIdx);
68842
68842
  }
68843
- #getScaledPath(path31, currentTransform, transform2) {
68843
+ #getScaledPath(path32, currentTransform, transform2) {
68844
68844
  const newPath = new Path2D();
68845
- newPath.addPath(path31, new DOMMatrix(transform2).invertSelf().multiplySelf(currentTransform));
68845
+ newPath.addPath(path32, new DOMMatrix(transform2).invertSelf().multiplySelf(currentTransform));
68846
68846
  return newPath;
68847
68847
  }
68848
68848
  paintChar(opIdx, character, x, y, patternFillTransform, patternStrokeTransform) {
@@ -68855,11 +68855,11 @@ var init_pdf = __esm({
68855
68855
  const isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG);
68856
68856
  const patternFill = current.patternFill && !font.missingFile;
68857
68857
  const patternStroke = current.patternStroke && !font.missingFile;
68858
- let path31;
68858
+ let path32;
68859
68859
  if ((font.disableFontFace || isAddToPathSet || patternFill || patternStroke) && !font.missingFile) {
68860
- path31 = font.getPathGenerator(this.commonObjs, character);
68860
+ path32 = font.getPathGenerator(this.commonObjs, character);
68861
68861
  }
68862
- if (path31 && (font.disableFontFace || patternFill || patternStroke)) {
68862
+ if (path32 && (font.disableFontFace || patternFill || patternStroke)) {
68863
68863
  ctx.save();
68864
68864
  ctx.translate(x, y);
68865
68865
  ctx.scale(fontSize, -fontSize);
@@ -68869,10 +68869,10 @@ var init_pdf = __esm({
68869
68869
  if (patternFillTransform) {
68870
68870
  currentTransform = ctx.getTransform();
68871
68871
  ctx.setTransform(...patternFillTransform);
68872
- const scaledPath = this.#getScaledPath(path31, currentTransform, patternFillTransform);
68872
+ const scaledPath = this.#getScaledPath(path32, currentTransform, patternFillTransform);
68873
68873
  ctx.fill(scaledPath);
68874
68874
  } else {
68875
- ctx.fill(path31);
68875
+ ctx.fill(path32);
68876
68876
  }
68877
68877
  }
68878
68878
  if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) {
@@ -68889,10 +68889,10 @@ var init_pdf = __esm({
68889
68889
  const transf = Util.transform([a, b, c, d, 0, 0], invPatternTransform);
68890
68890
  Util.singularValueDecompose2dScale(transf, XY);
68891
68891
  ctx.lineWidth *= Math.max(XY[0], XY[1]) / fontSize;
68892
- ctx.stroke(this.#getScaledPath(path31, currentTransform, patternStrokeTransform));
68892
+ ctx.stroke(this.#getScaledPath(path32, currentTransform, patternStrokeTransform));
68893
68893
  } else {
68894
68894
  ctx.lineWidth /= fontSize;
68895
- ctx.stroke(path31);
68895
+ ctx.stroke(path32);
68896
68896
  }
68897
68897
  }
68898
68898
  ctx.restore();
@@ -68915,7 +68915,7 @@ var init_pdf = __esm({
68915
68915
  x,
68916
68916
  y,
68917
68917
  fontSize,
68918
- path: path31
68918
+ path: path32
68919
68919
  });
68920
68920
  this.dependencyTracker?.recordCharacterBBox(opIdx, ctx, font, fontSize, x, y);
68921
68921
  }
@@ -69322,9 +69322,9 @@ var init_pdf = __esm({
69322
69322
  const [x0, y0, x1, y1] = group.bbox;
69323
69323
  clip.rect(x0, y0, x1 - x0, y1 - y0);
69324
69324
  if (group.matrix) {
69325
- const path31 = new Path2D();
69326
- path31.addPath(clip, new DOMMatrix(group.matrix));
69327
- clip = path31;
69325
+ const path32 = new Path2D();
69326
+ path32.addPath(clip, new DOMMatrix(group.matrix));
69327
+ clip = path32;
69328
69328
  }
69329
69329
  groupCtx.clip(clip);
69330
69330
  if (group.smask) {
@@ -69668,7 +69668,7 @@ var init_pdf = __esm({
69668
69668
  }
69669
69669
  endCompat(opIdx) {
69670
69670
  }
69671
- consumePath(opIdx, path31, clipBox) {
69671
+ consumePath(opIdx, path32, clipBox) {
69672
69672
  const isEmpty = this.current.isEmptyClip();
69673
69673
  if (this.pendingClip) {
69674
69674
  this.current.updateClipFromPath();
@@ -69680,9 +69680,9 @@ var init_pdf = __esm({
69680
69680
  if (this.pendingClip) {
69681
69681
  if (!isEmpty) {
69682
69682
  if (this.pendingClip === EO_CLIP) {
69683
- ctx.clip(path31, "evenodd");
69683
+ ctx.clip(path32, "evenodd");
69684
69684
  } else {
69685
- ctx.clip(path31);
69685
+ ctx.clip(path32);
69686
69686
  }
69687
69687
  }
69688
69688
  this.pendingClip = null;
@@ -69755,7 +69755,7 @@ var init_pdf = __esm({
69755
69755
  }
69756
69756
  return this._cachedScaleForStroking;
69757
69757
  }
69758
- rescaleAndStroke(path31, saveRestore) {
69758
+ rescaleAndStroke(path32, saveRestore) {
69759
69759
  const {
69760
69760
  ctx,
69761
69761
  current: {
@@ -69765,7 +69765,7 @@ var init_pdf = __esm({
69765
69765
  const [scaleX, scaleY] = this.getScaleForStroking();
69766
69766
  if (scaleX === scaleY) {
69767
69767
  ctx.lineWidth = (lineWidth || 1) * scaleX;
69768
- ctx.stroke(path31);
69768
+ ctx.stroke(path32);
69769
69769
  return;
69770
69770
  }
69771
69771
  const dashes = ctx.getLineDash();
@@ -69776,7 +69776,7 @@ var init_pdf = __esm({
69776
69776
  SCALE_MATRIX.a = 1 / scaleX;
69777
69777
  SCALE_MATRIX.d = 1 / scaleY;
69778
69778
  const newPath = new Path2D();
69779
- newPath.addPath(path31, SCALE_MATRIX);
69779
+ newPath.addPath(path32, SCALE_MATRIX);
69780
69780
  if (dashes.length > 0) {
69781
69781
  const scale = Math.max(scaleX, scaleY);
69782
69782
  ctx.setLineDash(dashes.map((x) => x / scale));
@@ -70992,10 +70992,10 @@ var init_pdf = __esm({
70992
70992
  this._readableStream = null;
70993
70993
  this._readCapability = Promise.withResolvers();
70994
70994
  this._headersCapability = Promise.withResolvers();
70995
- const fs29 = process.getBuiltinModule("fs");
70996
- fs29.promises.lstat(this._url).then((stat) => {
70995
+ const fs30 = process.getBuiltinModule("fs");
70996
+ fs30.promises.lstat(this._url).then((stat) => {
70997
70997
  this._contentLength = stat.size;
70998
- this._setReadableStream(fs29.createReadStream(this._url));
70998
+ this._setReadableStream(fs30.createReadStream(this._url));
70999
70999
  this._headersCapability.resolve();
71000
71000
  }, (error2) => {
71001
71001
  if (error2.code === "ENOENT") {
@@ -71090,8 +71090,8 @@ var init_pdf = __esm({
71090
71090
  this._readCapability = Promise.withResolvers();
71091
71091
  const source = stream.source;
71092
71092
  this._isStreamingSupported = !source.disableStream;
71093
- const fs29 = process.getBuiltinModule("fs");
71094
- this._setReadableStream(fs29.createReadStream(this._url, {
71093
+ const fs30 = process.getBuiltinModule("fs");
71094
+ this._setReadableStream(fs30.createReadStream(this._url, {
71095
71095
  start,
71096
71096
  end: end2 - 1
71097
71097
  }));
@@ -72068,14 +72068,14 @@ var init_pdf = __esm({
72068
72068
  return this.getXfa().then((xfa) => XfaText.textContent(xfa));
72069
72069
  }
72070
72070
  const readableStream = this.streamTextContent(params);
72071
- return new Promise(function(resolve15, reject) {
72071
+ return new Promise(function(resolve16, reject) {
72072
72072
  function pump() {
72073
72073
  reader.read().then(function({
72074
72074
  value,
72075
72075
  done
72076
72076
  }) {
72077
72077
  if (done) {
72078
- resolve15(textContent2);
72078
+ resolve16(textContent2);
72079
72079
  return;
72080
72080
  }
72081
72081
  textContent2.lang ??= value.lang;
@@ -80402,11 +80402,11 @@ var init_pdf = __esm({
80402
80402
  };
80403
80403
  ContourDrawOutline = class extends InkDrawOutline {
80404
80404
  toSVGPath() {
80405
- let path31 = super.toSVGPath();
80406
- if (!path31.endsWith("Z")) {
80407
- path31 += "Z";
80405
+ let path32 = super.toSVGPath();
80406
+ if (!path32.endsWith("Z")) {
80407
+ path32 += "Z";
80408
80408
  }
80409
- return path31;
80409
+ return path32;
80410
80410
  }
80411
80411
  };
80412
80412
  BASE_HEADER_LENGTH = 8;
@@ -81558,7 +81558,7 @@ var init_pdf = __esm({
81558
81558
  input2.type = "file";
81559
81559
  input2.accept = SupportedImageMimeTypes.join(",");
81560
81560
  const signal = this._uiManager._signal;
81561
- this.#bitmapPromise = new Promise((resolve15) => {
81561
+ this.#bitmapPromise = new Promise((resolve16) => {
81562
81562
  input2.addEventListener("change", async () => {
81563
81563
  if (!input2.files || input2.files.length === 0) {
81564
81564
  this.remove();
@@ -81573,13 +81573,13 @@ var init_pdf = __esm({
81573
81573
  });
81574
81574
  this.#getBitmapFetched(data2);
81575
81575
  }
81576
- resolve15();
81576
+ resolve16();
81577
81577
  }, {
81578
81578
  signal
81579
81579
  });
81580
81580
  input2.addEventListener("cancel", () => {
81581
81581
  this.remove();
81582
- resolve15();
81582
+ resolve16();
81583
81583
  }, {
81584
81584
  signal
81585
81585
  });
@@ -82863,13 +82863,13 @@ var init_pdf = __esm({
82863
82863
  const root3 = this.#createSVG();
82864
82864
  const defs = _DrawLayer._svgFactory.createElement("defs");
82865
82865
  root3.append(defs);
82866
- const path31 = _DrawLayer._svgFactory.createElement("path");
82867
- defs.append(path31);
82866
+ const path32 = _DrawLayer._svgFactory.createElement("path");
82867
+ defs.append(path32);
82868
82868
  const pathId = `path_p${this.pageIndex}_${id}`;
82869
- path31.setAttribute("id", pathId);
82870
- path31.setAttribute("vector-effect", "non-scaling-stroke");
82869
+ path32.setAttribute("id", pathId);
82870
+ path32.setAttribute("vector-effect", "non-scaling-stroke");
82871
82871
  if (isPathUpdatable) {
82872
- this.#toUpdate.set(id, path31);
82872
+ this.#toUpdate.set(id, path32);
82873
82873
  }
82874
82874
  const clipPathId = hasClip ? this.#createClipPath(defs, pathId) : null;
82875
82875
  const use = _DrawLayer._svgFactory.createElement("use");
@@ -82887,11 +82887,11 @@ var init_pdf = __esm({
82887
82887
  const root3 = this.#createSVG();
82888
82888
  const defs = _DrawLayer._svgFactory.createElement("defs");
82889
82889
  root3.append(defs);
82890
- const path31 = _DrawLayer._svgFactory.createElement("path");
82891
- defs.append(path31);
82890
+ const path32 = _DrawLayer._svgFactory.createElement("path");
82891
+ defs.append(path32);
82892
82892
  const pathId = `path_p${this.pageIndex}_${id}`;
82893
- path31.setAttribute("id", pathId);
82894
- path31.setAttribute("vector-effect", "non-scaling-stroke");
82893
+ path32.setAttribute("id", pathId);
82894
+ path32.setAttribute("vector-effect", "non-scaling-stroke");
82895
82895
  let maskId;
82896
82896
  if (mustRemoveSelfIntersections) {
82897
82897
  const mask = _DrawLayer._svgFactory.createElement("mask");
@@ -82938,7 +82938,7 @@ var init_pdf = __esm({
82938
82938
  root: root3,
82939
82939
  bbox,
82940
82940
  rootClass,
82941
- path: path31
82941
+ path: path32
82942
82942
  } = properties;
82943
82943
  const element = typeof elementOrId === "number" ? this.#mapping.get(elementOrId) : elementOrId;
82944
82944
  if (!element) {
@@ -82958,10 +82958,10 @@ var init_pdf = __esm({
82958
82958
  classList.toggle(className, value);
82959
82959
  }
82960
82960
  }
82961
- if (path31) {
82961
+ if (path32) {
82962
82962
  const defs = element.firstChild;
82963
82963
  const pathElement = defs.firstChild;
82964
- this.#updateProperties(pathElement, path31);
82964
+ this.#updateProperties(pathElement, path32);
82965
82965
  }
82966
82966
  }
82967
82967
  updateParent(id, layer) {
@@ -83338,8 +83338,8 @@ var init_event_stream = __esm({
83338
83338
  constructor(isComplete, extractResult) {
83339
83339
  this.isComplete = isComplete;
83340
83340
  this.extractResult = extractResult;
83341
- this.finalResultPromise = new Promise((resolve15) => {
83342
- this.resolveFinalResult = resolve15;
83341
+ this.finalResultPromise = new Promise((resolve16) => {
83342
+ this.resolveFinalResult = resolve16;
83343
83343
  });
83344
83344
  }
83345
83345
  push(event) {
@@ -83372,7 +83372,7 @@ var init_event_stream = __esm({
83372
83372
  } else if (this.done) {
83373
83373
  return;
83374
83374
  } else {
83375
- const result = await new Promise((resolve15) => this.waiting.push(resolve15));
83375
+ const result = await new Promise((resolve16) => this.waiting.push(resolve16));
83376
83376
  if (result.done) return;
83377
83377
  yield result.value;
83378
83378
  }
@@ -83635,8 +83635,8 @@ var init_agent = __esm({
83635
83635
  async runWithLifecycle(run) {
83636
83636
  const abortController = new AbortController();
83637
83637
  let resolveRun;
83638
- const promise = new Promise((resolve15) => {
83639
- resolveRun = resolve15;
83638
+ const promise = new Promise((resolve16) => {
83639
+ resolveRun = resolve16;
83640
83640
  });
83641
83641
  this.activeRun = { promise, resolve: resolveRun, abortController };
83642
83642
  this.steeringQueue.open();
@@ -83988,7 +83988,7 @@ var init_flow_runner = __esm({
83988
83988
 
83989
83989
  // src/wsl-agent-host.ts
83990
83990
  var readline2 = __toESM(require("readline"));
83991
- var fs28 = __toESM(require("fs"));
83991
+ var fs29 = __toESM(require("fs"));
83992
83992
 
83993
83993
  // src/core/modelResponseHealth.ts
83994
83994
  var fs = __toESM(require("fs"));
@@ -86126,9 +86126,11 @@ var ChatCompletionsAdapter = class {
86126
86126
  const body = {
86127
86127
  model: request.model,
86128
86128
  messages,
86129
- temperature: request.temperature,
86130
- max_tokens: request.maxOutputTokens
86129
+ temperature: request.temperature
86131
86130
  };
86131
+ if (Number.isFinite(request.maxOutputTokens) && request.maxOutputTokens > 0) {
86132
+ body.max_tokens = request.maxOutputTokens;
86133
+ }
86132
86134
  if (tools.length) {
86133
86135
  body.tools = tools;
86134
86136
  body.tool_choice = "auto";
@@ -86436,9 +86438,11 @@ var ResponsesAdapter = class {
86436
86438
  const body = {
86437
86439
  model: request.model,
86438
86440
  input: input2.length ? input2 : [{ role: "user", content: "" }],
86439
- temperature: request.temperature,
86440
- max_output_tokens: request.maxOutputTokens
86441
+ temperature: request.temperature
86441
86442
  };
86443
+ if (Number.isFinite(request.maxOutputTokens) && request.maxOutputTokens > 0) {
86444
+ body.max_output_tokens = request.maxOutputTokens;
86445
+ }
86442
86446
  if (request.reasoningEffort) body.reasoning = { effort: request.reasoningEffort, summary: "auto" };
86443
86447
  if (request.systemPrompt) body.instructions = request.systemPrompt;
86444
86448
  const tools = this.serializeTools(request.tools);
@@ -86793,10 +86797,10 @@ function abortFailure(signal) {
86793
86797
  function abortable(promise, signal) {
86794
86798
  if (!signal) return promise;
86795
86799
  if (signal.aborted) return Promise.reject(abortFailure(signal));
86796
- return new Promise((resolve15, reject) => {
86800
+ return new Promise((resolve16, reject) => {
86797
86801
  const onAbort = () => reject(abortFailure(signal));
86798
86802
  signal.addEventListener("abort", onAbort, { once: true });
86799
- promise.then(resolve15, reject).finally(() => signal.removeEventListener("abort", onAbort));
86803
+ promise.then(resolve16, reject).finally(() => signal.removeEventListener("abort", onAbort));
86800
86804
  });
86801
86805
  }
86802
86806
  function parseProviderSse(raw) {
@@ -87161,7 +87165,7 @@ var LLMProvider = class _LLMProvider {
87161
87165
  throw error2;
87162
87166
  });
87163
87167
  }
87164
- return new Promise((resolve15, reject) => {
87168
+ return new Promise((resolve16, reject) => {
87165
87169
  const parsed = new URL(urlValue);
87166
87170
  const client = parsed.protocol === "http:" ? http2 : https;
87167
87171
  const requestHeaders = { ...headers };
@@ -87185,7 +87189,7 @@ var LLMProvider = class _LLMProvider {
87185
87189
  const finish = () => {
87186
87190
  if (settled) return;
87187
87191
  settled = true;
87188
- resolve15({ status: res.statusCode || 0, body: responseBody, headers: res.headers });
87192
+ resolve16({ status: res.statusCode || 0, body: responseBody, headers: res.headers });
87189
87193
  };
87190
87194
  const fail2 = (error2) => {
87191
87195
  if (settled) return;
@@ -87230,7 +87234,7 @@ var LLMProvider = class _LLMProvider {
87230
87234
  if (_LLMProvider.powershellTransport) {
87231
87235
  return this.withRequestTimeout(_LLMProvider.powershellTransport(method, urlValue, headers, body), effectiveTimeout, signal);
87232
87236
  }
87233
- return new Promise((resolve15, reject) => {
87237
+ return new Promise((resolve16, reject) => {
87234
87238
  const headerJson = JSON.stringify(headers);
87235
87239
  const tempDir = fs5.mkdtempSync(path5.join(os.tmpdir(), "newmark-llm-"));
87236
87240
  const bodyPath = path5.join(tempDir, "body.json");
@@ -87321,7 +87325,7 @@ var LLMProvider = class _LLMProvider {
87321
87325
  const statusText = stdout.trim().split(/\r?\n/).pop() || "0";
87322
87326
  const bodyText = fs5.readFileSync(responsePath, "utf8");
87323
87327
  cleanup();
87324
- resolve15({ status: Number(statusText) || 0, body: bodyText });
87328
+ resolve16({ status: Number(statusText) || 0, body: bodyText });
87325
87329
  });
87326
87330
  child.stdin.end(`${urlValue}
87327
87331
  ${method}
@@ -87884,12 +87888,13 @@ ${responsePath}
87884
87888
  }
87885
87889
  async *chatStreamWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal, reasoningTier, sessionId) {
87886
87890
  if (signal?.aborted) throw abortFailure(signal);
87891
+ const requiredMaxTokens = maxTokens > 0 ? maxTokens : this.intelligenceConfig(reasoningTier || "medium").maxTokens;
87887
87892
  if (this.protocol() === "anthropic") {
87888
- yield* this.anthropicChatWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal);
87893
+ yield* this.anthropicChatWithTools(model, messages, systemPrompt, temperature, requiredMaxTokens, tools, signal);
87889
87894
  return;
87890
87895
  }
87891
87896
  if (this.protocol() === "github_models") {
87892
- yield* this.githubModelsChatStreamWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal);
87897
+ yield* this.githubModelsChatStreamWithTools(model, messages, systemPrompt, temperature, requiredMaxTokens, tools, signal);
87893
87898
  return;
87894
87899
  }
87895
87900
  if (this.useProviderAdaptersV2) {
@@ -88445,10 +88450,10 @@ function candidateBaseUrls(rawBaseUrl) {
88445
88450
  }
88446
88451
  function endpointBaseFromSuffix(inputBaseUrl, suffix) {
88447
88452
  const base = inputBaseUrl.replace(/\/+$/g, "");
88448
- const path31 = suffix.replace(/\/+$/g, "");
88453
+ const path32 = suffix.replace(/\/+$/g, "");
88449
88454
  for (const terminal of ["/chat/completions", "/completions", "/responses", "/messages", "/models"]) {
88450
- if (path31.endsWith(terminal)) {
88451
- const prefix = path31.slice(0, -terminal.length).replace(/\/+$/g, "");
88455
+ if (path32.endsWith(terminal)) {
88456
+ const prefix = path32.slice(0, -terminal.length).replace(/\/+$/g, "");
88452
88457
  return `${base}${prefix}`;
88453
88458
  }
88454
88459
  }
@@ -107545,14 +107550,14 @@ var PowerShellWorker = class {
107545
107550
  const child = this.ensureChild();
107546
107551
  const id = crypto5.randomUUID();
107547
107552
  const startedAt = Date.now();
107548
- return await new Promise((resolve15, reject) => {
107553
+ return await new Promise((resolve16, reject) => {
107549
107554
  const timer = setTimeout(() => {
107550
107555
  this.pending.delete(id);
107551
107556
  reject(new Error(`Computer Use ${this.lane} helper timed out after ${timeoutMs} ms.`));
107552
107557
  }, Math.max(100, timeoutMs));
107553
107558
  this.pending.set(id, {
107554
107559
  timer,
107555
- resolve: (result) => resolve15({ ...result, elapsedMs: Date.now() - startedAt })
107560
+ resolve: (result) => resolve16({ ...result, elapsedMs: Date.now() - startedAt })
107556
107561
  });
107557
107562
  const request = JSON.stringify({
107558
107563
  id,
@@ -108521,7 +108526,7 @@ async function screenshot(workspacePath, ownerId, allowEphemeralVisionImage, inc
108521
108526
  async function wait(durationMs) {
108522
108527
  const ms = Math.min(Math.max(Math.floor(durationMs || 1e3), 0), 6e4);
108523
108528
  const start = Date.now();
108524
- await new Promise((resolve15) => setTimeout(resolve15, ms));
108529
+ await new Promise((resolve16) => setTimeout(resolve16, ms));
108525
108530
  return { ok: true, action: "wait", duration_ms: Date.now() - start };
108526
108531
  }
108527
108532
  async function moveOrClick(action, x, y, button, dryRun, target) {
@@ -108911,7 +108916,7 @@ function runAsyncProcess(command, args, options = {}) {
108911
108916
  overflowed: false
108912
108917
  });
108913
108918
  }
108914
- return new Promise((resolve15) => {
108919
+ return new Promise((resolve16) => {
108915
108920
  let child;
108916
108921
  try {
108917
108922
  child = (0, import_child_process4.spawn)(command, args, {
@@ -108922,7 +108927,7 @@ function runAsyncProcess(command, args, options = {}) {
108922
108927
  stdio: ["ignore", "pipe", "pipe"]
108923
108928
  });
108924
108929
  } catch (error2) {
108925
- resolve15({
108930
+ resolve16({
108926
108931
  status: null,
108927
108932
  stdout: "",
108928
108933
  stderr: "",
@@ -108950,7 +108955,7 @@ function runAsyncProcess(command, args, options = {}) {
108950
108955
  if (stopSettlementWatchdog) clearTimeout(stopSettlementWatchdog);
108951
108956
  options.signal?.removeEventListener("abort", abortListener);
108952
108957
  const error2 = spawnError || (stopReason === "abort" ? signalMessage(options.signal) : "") || (stopReason === "timeout" ? `Timed out after ${timeoutMs} ms` : "") || (stopReason === "maxBuffer" ? `Output exceeded ${maxBuffer2} byte limit` : "");
108953
- resolve15({
108958
+ resolve16({
108954
108959
  status,
108955
108960
  stdout: Buffer.concat(stdout).toString("utf8"),
108956
108961
  stderr: Buffer.concat(stderr).toString("utf8"),
@@ -110141,7 +110146,7 @@ function requestWindowsHostTool(tool, args, context, timeoutMs = 3e4, signal) {
110141
110146
  if (signal?.aborted) return Promise.reject(abortError(signal));
110142
110147
  const requestId = `host-tool-${process.pid}-${(0, import_crypto7.randomUUID)()}`;
110143
110148
  request.requestId = requestId;
110144
- return new Promise((resolve15, reject) => {
110149
+ return new Promise((resolve16, reject) => {
110145
110150
  const timer = setTimeout(() => {
110146
110151
  const active = pending.get(requestId);
110147
110152
  if (!active) return;
@@ -110164,7 +110169,7 @@ function requestWindowsHostTool(tool, args, context, timeoutMs = 3e4, signal) {
110164
110169
  }
110165
110170
  reject(abortError(signal));
110166
110171
  } : void 0;
110167
- pending.set(requestId, { resolve: resolve15, reject, timer, signal, abortListener });
110172
+ pending.set(requestId, { resolve: resolve16, reject, timer, signal, abortListener });
110168
110173
  if (abortListener) signal.addEventListener("abort", abortListener, { once: true });
110169
110174
  if (signal?.aborted) {
110170
110175
  abortListener?.();
@@ -110257,7 +110262,7 @@ function requestUtilityHostTool(tool, args, context, timeoutMs = 12e4, signal) {
110257
110262
  runtimeKey: target.runtimeKey
110258
110263
  } : void 0;
110259
110264
  const request = tool === "browser_control" ? { requestId, tool, args, target } : { requestId, tool, args, context: trustedContext, target };
110260
- return new Promise((resolve15, reject) => {
110265
+ return new Promise((resolve16, reject) => {
110261
110266
  const timer = setTimeout(() => {
110262
110267
  const active = pending2.get(requestId);
110263
110268
  if (!active) return;
@@ -110280,7 +110285,7 @@ function requestUtilityHostTool(tool, args, context, timeoutMs = 12e4, signal) {
110280
110285
  }
110281
110286
  reject(abortError2(signal));
110282
110287
  } : void 0;
110283
- pending2.set(requestId, { resolve: resolve15, reject, timer, signal, abortListener });
110288
+ pending2.set(requestId, { resolve: resolve16, reject, timer, signal, abortListener });
110284
110289
  if (abortListener) signal.addEventListener("abort", abortListener, { once: true });
110285
110290
  if (signal?.aborted) {
110286
110291
  abortListener?.();
@@ -110415,13 +110420,13 @@ function combineAbortSignals(signal, timeoutMs) {
110415
110420
  function createBash(workspaceRoot, timeoutMs) {
110416
110421
  const justBash = loadJustBash();
110417
110422
  if (!justBash) throw new Error("Native Bash runtime unavailable");
110418
- const fs29 = new justBash.ReadWriteFs({
110423
+ const fs30 = new justBash.ReadWriteFs({
110419
110424
  root: path15.resolve(workspaceRoot),
110420
110425
  maxFileReadSize: MAX_OUTPUT_BYTES * 8,
110421
110426
  allowSymlinks: false
110422
110427
  });
110423
110428
  return new justBash.Bash({
110424
- fs: fs29,
110429
+ fs: fs30,
110425
110430
  cwd: "/",
110426
110431
  env: {
110427
110432
  HOME: "/",
@@ -110582,17 +110587,17 @@ var ToolArgumentValidatorRegistry = class {
110582
110587
  };
110583
110588
  function formatValidationErrors(name, errors2) {
110584
110589
  const details = errors2.slice(0, 5).map((error2) => {
110585
- const path31 = String(error2.instancePath || "").replace(/^\//, "").replaceAll("/", ".");
110590
+ const path32 = String(error2.instancePath || "").replace(/^\//, "").replaceAll("/", ".");
110586
110591
  if (error2.keyword === "required") {
110587
- const required2 = String(error2.params?.requiredProperty || error2.params?.required || path31 || "property");
110592
+ const required2 = String(error2.params?.requiredProperty || error2.params?.required || path32 || "property");
110588
110593
  return `${required2} is required`;
110589
110594
  }
110590
110595
  if (error2.keyword === "additionalProperties") {
110591
110596
  const values = error2.params?.additionalProperties;
110592
- const fields2 = Array.isArray(values) ? values.map(String).join(", ") : String(values || path31 || "unknown");
110597
+ const fields2 = Array.isArray(values) ? values.map(String).join(", ") : String(values || path32 || "unknown");
110593
110598
  return `additional field(s) not allowed: ${fields2}`;
110594
110599
  }
110595
- const location = path31 || "arguments";
110600
+ const location = path32 || "arguments";
110596
110601
  const message = String(error2.message || error2.keyword || "is invalid");
110597
110602
  return `${location} ${message}`;
110598
110603
  });
@@ -111020,10 +111025,10 @@ function mergeDefs(...defs) {
111020
111025
  function cloneDef(schema) {
111021
111026
  return mergeDefs(schema._zod.def);
111022
111027
  }
111023
- function getElementAtPath(obj, path31) {
111024
- if (!path31)
111028
+ function getElementAtPath(obj, path32) {
111029
+ if (!path32)
111025
111030
  return obj;
111026
- return path31.reduce((acc, key3) => acc?.[key3], obj);
111031
+ return path32.reduce((acc, key3) => acc?.[key3], obj);
111027
111032
  }
111028
111033
  function promiseAllObject(promisesObj) {
111029
111034
  const keys = Object.keys(promisesObj);
@@ -111435,11 +111440,11 @@ function explicitlyAborted(x, startIndex = 0) {
111435
111440
  }
111436
111441
  return false;
111437
111442
  }
111438
- function prefixIssues(path31, issues) {
111443
+ function prefixIssues(path32, issues) {
111439
111444
  return issues.map((iss) => {
111440
111445
  var _a9;
111441
111446
  (_a9 = iss).path ?? (_a9.path = []);
111442
- iss.path.unshift(path31);
111447
+ iss.path.unshift(path32);
111443
111448
  return iss;
111444
111449
  });
111445
111450
  }
@@ -111871,16 +111876,16 @@ function flattenError(error2, mapper = (issue2) => issue2.message) {
111871
111876
  }
111872
111877
  function formatError(error2, mapper = (issue2) => issue2.message) {
111873
111878
  const fieldErrors = { _errors: [] };
111874
- const processError = (error3, path31 = []) => {
111879
+ const processError = (error3, path32 = []) => {
111875
111880
  for (const issue2 of error3.issues) {
111876
111881
  if (issue2.code === "invalid_union" && issue2.errors.length) {
111877
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
111882
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
111878
111883
  } else if (issue2.code === "invalid_key") {
111879
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
111884
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
111880
111885
  } else if (issue2.code === "invalid_element") {
111881
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
111886
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
111882
111887
  } else {
111883
- const fullpath = [...path31, ...issue2.path];
111888
+ const fullpath = [...path32, ...issue2.path];
111884
111889
  if (fullpath.length === 0) {
111885
111890
  fieldErrors._errors.push(mapper(issue2));
111886
111891
  } else {
@@ -119346,7 +119351,7 @@ var Protocol = class {
119346
119351
  return;
119347
119352
  }
119348
119353
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
119349
- await new Promise((resolve15) => setTimeout(resolve15, pollInterval));
119354
+ await new Promise((resolve16) => setTimeout(resolve16, pollInterval));
119350
119355
  options?.signal?.throwIfAborted();
119351
119356
  }
119352
119357
  } catch (error2) {
@@ -119363,7 +119368,7 @@ var Protocol = class {
119363
119368
  */
119364
119369
  request(request, resultSchema, options) {
119365
119370
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
119366
- return new Promise((resolve15, reject) => {
119371
+ return new Promise((resolve16, reject) => {
119367
119372
  const earlyReject = (error2) => {
119368
119373
  reject(error2);
119369
119374
  };
@@ -119441,7 +119446,7 @@ var Protocol = class {
119441
119446
  if (!parseResult.success) {
119442
119447
  reject(parseResult.error);
119443
119448
  } else {
119444
- resolve15(parseResult.data);
119449
+ resolve16(parseResult.data);
119445
119450
  }
119446
119451
  } catch (error2) {
119447
119452
  reject(error2);
@@ -119702,12 +119707,12 @@ var Protocol = class {
119702
119707
  }
119703
119708
  } catch {
119704
119709
  }
119705
- return new Promise((resolve15, reject) => {
119710
+ return new Promise((resolve16, reject) => {
119706
119711
  if (signal.aborted) {
119707
119712
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
119708
119713
  return;
119709
119714
  }
119710
- const timeoutId = setTimeout(resolve15, interval);
119715
+ const timeoutId = setTimeout(resolve16, interval);
119711
119716
  signal.addEventListener("abort", () => {
119712
119717
  clearTimeout(timeoutId);
119713
119718
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -121970,7 +121975,7 @@ var SSEClientTransport = class {
121970
121975
  }
121971
121976
  _startOrAuth() {
121972
121977
  const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
121973
- return new Promise((resolve15, reject) => {
121978
+ return new Promise((resolve16, reject) => {
121974
121979
  this._eventSource = new EventSource(this._url.href, {
121975
121980
  ...this._eventSourceInit,
121976
121981
  fetch: async (url2, init) => {
@@ -121991,7 +121996,7 @@ var SSEClientTransport = class {
121991
121996
  this._abortController = new AbortController();
121992
121997
  this._eventSource.onerror = (event) => {
121993
121998
  if (event.code === 401 && this._authProvider) {
121994
- this._authThenStart().then(resolve15, reject);
121999
+ this._authThenStart().then(resolve16, reject);
121995
122000
  return;
121996
122001
  }
121997
122002
  const error2 = new SseError(event.code, event.message, event);
@@ -122013,7 +122018,7 @@ var SSEClientTransport = class {
122013
122018
  void this.close();
122014
122019
  return;
122015
122020
  }
122016
- resolve15();
122021
+ resolve16();
122017
122022
  });
122018
122023
  this._eventSource.onmessage = (event) => {
122019
122024
  const messageEvent = event;
@@ -122192,7 +122197,7 @@ var StdioClientTransport = class {
122192
122197
  if (this._process) {
122193
122198
  throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
122194
122199
  }
122195
- return new Promise((resolve15, reject) => {
122200
+ return new Promise((resolve16, reject) => {
122196
122201
  this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
122197
122202
  // merge default env with server env because mcp server needs some env vars
122198
122203
  env: {
@@ -122209,7 +122214,7 @@ var StdioClientTransport = class {
122209
122214
  this.onerror?.(error2);
122210
122215
  });
122211
122216
  this._process.on("spawn", () => {
122212
- resolve15();
122217
+ resolve16();
122213
122218
  });
122214
122219
  this._process.on("close", (_code) => {
122215
122220
  this._process = void 0;
@@ -122274,22 +122279,22 @@ var StdioClientTransport = class {
122274
122279
  if (this._process) {
122275
122280
  const processToClose = this._process;
122276
122281
  this._process = void 0;
122277
- const closePromise = new Promise((resolve15) => {
122282
+ const closePromise = new Promise((resolve16) => {
122278
122283
  processToClose.once("close", () => {
122279
- resolve15();
122284
+ resolve16();
122280
122285
  });
122281
122286
  });
122282
122287
  try {
122283
122288
  processToClose.stdin?.end();
122284
122289
  } catch {
122285
122290
  }
122286
- await Promise.race([closePromise, new Promise((resolve15) => setTimeout(resolve15, 2e3).unref())]);
122291
+ await Promise.race([closePromise, new Promise((resolve16) => setTimeout(resolve16, 2e3).unref())]);
122287
122292
  if (processToClose.exitCode === null) {
122288
122293
  try {
122289
122294
  processToClose.kill("SIGTERM");
122290
122295
  } catch {
122291
122296
  }
122292
- await Promise.race([closePromise, new Promise((resolve15) => setTimeout(resolve15, 2e3).unref())]);
122297
+ await Promise.race([closePromise, new Promise((resolve16) => setTimeout(resolve16, 2e3).unref())]);
122293
122298
  }
122294
122299
  if (processToClose.exitCode === null) {
122295
122300
  try {
@@ -122301,15 +122306,15 @@ var StdioClientTransport = class {
122301
122306
  this._readBuffer.clear();
122302
122307
  }
122303
122308
  send(message) {
122304
- return new Promise((resolve15) => {
122309
+ return new Promise((resolve16) => {
122305
122310
  if (!this._process?.stdin) {
122306
122311
  throw new Error("Not connected");
122307
122312
  }
122308
122313
  const json = serializeMessage(message);
122309
122314
  if (this._process.stdin.write(json)) {
122310
- resolve15();
122315
+ resolve16();
122311
122316
  } else {
122312
- this._process.stdin.once("drain", resolve15);
122317
+ this._process.stdin.once("drain", resolve16);
122313
122318
  }
122314
122319
  });
122315
122320
  }
@@ -123246,11 +123251,11 @@ async function extractPdfTextLayer(buffer, maxChars, signal) {
123246
123251
  }
123247
123252
  async function abortableToolDelay(durationMs, signal) {
123248
123253
  if (signal?.aborted) throw abortReason2(signal);
123249
- await new Promise((resolve15, reject) => {
123254
+ await new Promise((resolve16, reject) => {
123250
123255
  const timer = setTimeout(finish, Math.max(0, durationMs));
123251
123256
  function finish() {
123252
123257
  signal?.removeEventListener("abort", abort);
123253
- resolve15();
123258
+ resolve16();
123254
123259
  }
123255
123260
  function abort() {
123256
123261
  clearTimeout(timer);
@@ -123736,7 +123741,7 @@ var ToolExecutor = class {
123736
123741
  const value = args[k];
123737
123742
  return value === void 0 || value === null ? "" : String(value);
123738
123743
  };
123739
- const resolve15 = (relPath) => normalizeCrossEnvPath(relPath, wsPath);
123744
+ const resolve16 = (relPath) => normalizeCrossEnvPath(relPath, wsPath);
123740
123745
  const targetForTool = () => {
123741
123746
  switch (tool) {
123742
123747
  case "read":
@@ -123746,11 +123751,11 @@ var ToolExecutor = class {
123746
123751
  case "grep":
123747
123752
  case "file_audit":
123748
123753
  case "pdf_read":
123749
- return resolve15(g("path"));
123754
+ return resolve16(g("path"));
123750
123755
  case "web_catch":
123751
- return resolve15(g("destination"));
123756
+ return resolve16(g("destination"));
123752
123757
  case "git_clone":
123753
- return resolve15(g("path"));
123758
+ return resolve16(g("path"));
123754
123759
  case "ssh_workspace":
123755
123760
  return wsPath;
123756
123761
  default:
@@ -123773,23 +123778,23 @@ var ToolExecutor = class {
123773
123778
  case "pwd":
123774
123779
  return `Current directory: ${wsPath}`;
123775
123780
  case "read":
123776
- return this.fread(resolve15(g("path")));
123781
+ return this.fread(resolve16(g("path")));
123777
123782
  case "write":
123778
- return this.fwrite(resolve15(g("path")), g("content"));
123783
+ return this.fwrite(resolve16(g("path")), g("content"));
123779
123784
  case "edit":
123780
- return this.fedit(resolve15(g("path")), g("old_str"), g("new_str"));
123785
+ return this.fedit(resolve16(g("path")), g("old_str"), g("new_str"));
123781
123786
  case "delete_file":
123782
- return this.fdelete(resolve15(g("path")));
123787
+ return this.fdelete(resolve16(g("path")));
123783
123788
  case "glob":
123784
123789
  return this.glob(g("pattern"), wsPath);
123785
123790
  case "grep":
123786
- return this.grep(g("pattern"), resolve15(g("path")));
123791
+ return this.grep(g("pattern"), resolve16(g("path")));
123787
123792
  case "web_search":
123788
123793
  return await this.wsearch(g("query"), context.signal);
123789
123794
  case "web_fetch":
123790
123795
  return await this.wfetch(g("url"), context.signal);
123791
123796
  case "web_catch":
123792
- return await this.wcatch(args, resolve15(g("destination")), context.signal);
123797
+ return await this.wcatch(args, resolve16(g("destination")), context.signal);
123793
123798
  case "browser_open":
123794
123799
  return await this.browserRun({ action: "open", url: g("url") }, context.signal, context, wsPath);
123795
123800
  case "browser_snapshot":
@@ -123883,12 +123888,12 @@ var ToolExecutor = class {
123883
123888
  return JSON.stringify(await this.localOcr.recognizeDataUrl(fallback.dataUrl, context.signal), null, 2);
123884
123889
  }
123885
123890
  if (source === "image") {
123886
- return JSON.stringify(await this.localOcr.recognizeFile(resolve15(g("path")), context.signal), null, 2);
123891
+ return JSON.stringify(await this.localOcr.recognizeFile(resolve16(g("path")), context.signal), null, 2);
123887
123892
  }
123888
123893
  return "[ocr fallback blocked] source must be browser or image.";
123889
123894
  }
123890
123895
  case "pdf_read": {
123891
- const pdfPath = resolve15(g("path"));
123896
+ const pdfPath = resolve16(g("path"));
123892
123897
  if (path19.extname(pdfPath).toLowerCase() !== ".pdf") return "[pdf_read error] path must end in .pdf.";
123893
123898
  const maxChars = Math.max(500, Math.min(1e5, Number(args.max_chars || 5e4)));
123894
123899
  const page = Math.max(1, Math.min(100, Math.floor(Number(args.page || 1))));
@@ -124168,15 +124173,15 @@ var ToolExecutor = class {
124168
124173
  case "git_status":
124169
124174
  return await this.gstat(wsPath, context.signal);
124170
124175
  case "file_audit":
124171
- return await this.fileAudit(resolve15(g("path") || "."), wsPath, args.include_remote !== false, g("base_ref"), context.signal);
124176
+ return await this.fileAudit(resolve16(g("path") || "."), wsPath, args.include_remote !== false, g("base_ref"), context.signal);
124172
124177
  case "repo_security_audit":
124173
- return await this.repoSecurityAudit(resolve15(g("path") || "."), wsPath, g("base_ref"), context.signal);
124178
+ return await this.repoSecurityAudit(resolve16(g("path") || "."), wsPath, g("base_ref"), context.signal);
124174
124179
  case "git_pull":
124175
124180
  return await this.gpull(wsPath, context.signal);
124176
124181
  case "git_push":
124177
124182
  return await this.withRemoteSecurityPreamble(wsPath, () => this.gpush(g("message"), wsPath, context.signal), context.signal, args.security_review_confirmed === true);
124178
124183
  case "git_clone":
124179
- return await this.gclone(g("url"), resolve15(g("path")), context.signal);
124184
+ return await this.gclone(g("url"), resolve16(g("path")), context.signal);
124180
124185
  case "git_branch":
124181
124186
  return await this.gbranch(g("action"), g("name"), g("start_point"), wsPath, context.signal);
124182
124187
  case "gh_auth_status":
@@ -125716,7 +125721,7 @@ var SubagentManager = class {
125716
125721
  waitForSettlement(idOrName, timeoutMs = 12e4) {
125717
125722
  const record3 = this.get(idOrName);
125718
125723
  if (!record3 || !["queued", "working"].includes(record3.status)) return Promise.resolve(record3 ? cloneRecord(record3) : void 0);
125719
- return new Promise((resolve15) => {
125724
+ return new Promise((resolve16) => {
125720
125725
  const waiters = this.settledWaiters.get(record3.id) || [];
125721
125726
  let done = false;
125722
125727
  let timer;
@@ -125724,7 +125729,7 @@ var SubagentManager = class {
125724
125729
  if (done) return;
125725
125730
  done = true;
125726
125731
  if (timer) clearTimeout(timer);
125727
- resolve15(value ? cloneRecord(value) : void 0);
125732
+ resolve16(value ? cloneRecord(value) : void 0);
125728
125733
  };
125729
125734
  waiters.push(finish);
125730
125735
  this.settledWaiters.set(record3.id, waiters);
@@ -126130,7 +126135,7 @@ ${prompt}`;
126130
126135
  resolveSettledWaiters(record3) {
126131
126136
  const waiters = this.settledWaiters.get(record3.id) || [];
126132
126137
  this.settledWaiters.delete(record3.id);
126133
- for (const resolve15 of waiters) resolve15(record3);
126138
+ for (const resolve16 of waiters) resolve16(record3);
126134
126139
  }
126135
126140
  pump() {
126136
126141
  if (!this.executor || this.schedulingPaused) return;
@@ -128043,6 +128048,16 @@ var HIDDEN_LINE_PREFIXES = [
128043
128048
  "analysis:",
128044
128049
  "analysis\uFF1A"
128045
128050
  ];
128051
+ function providerSessionIdentity(agent) {
128052
+ const conversationId = String(agent.activeConversationId || "default");
128053
+ try {
128054
+ const snapshot2 = agent.getConversationSnapshot(conversationId);
128055
+ const branchId = String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || "");
128056
+ return branchId ? `${conversationId}::branch:${branchId}` : conversationId;
128057
+ } catch {
128058
+ return conversationId;
128059
+ }
128060
+ }
128046
128061
  function partialMarkerSuffix(value, marker) {
128047
128062
  const lower = value.toLowerCase();
128048
128063
  const target = marker.toLowerCase();
@@ -128544,7 +128559,8 @@ async function runAgentKernel(agent) {
128544
128559
  currentAgent.checkpointPeerInput();
128545
128560
  peerInputCheckpointed = true;
128546
128561
  }
128547
- const { temperature, maxTokens, reasoningEffort } = currentProvider.intelligenceConfig(currentAgent.intelligence);
128562
+ const { temperature, reasoningEffort } = currentProvider.intelligenceConfig(currentAgent.intelligence);
128563
+ const maxTokens = 0;
128548
128564
  const newmarkMessages = fromKernelMessages(context.messages).map((message) => message.role === "assistant" ? { ...message, content: currentAgent.sanitizeAssistantOutput(String(message.content || "")) } : message);
128549
128565
  buildTaskFocusSnapshot ??= buildRequestTaskFocus(currentAgent, context.messages, {
128550
128566
  activeTools: context.tools || [],
@@ -128580,7 +128596,7 @@ async function runAgentKernel(agent) {
128580
128596
  providerTools,
128581
128597
  options?.signal,
128582
128598
  reasoningEffort,
128583
- currentAgent.config.getBool("context", "provider_session_id") ? currentAgent.activeConversationId : void 0
128599
+ currentAgent.config.getBool("context", "provider_session_id") ? providerSessionIdentity(currentAgent) : void 0
128584
128600
  )) {
128585
128601
  if (!firstTokenRecorded && (token.type === "text" && token.text || token.type === "tool_call" && token.toolCall)) {
128586
128602
  firstTokenRecorded = true;
@@ -132522,7 +132538,7 @@ var Agent5 = class _Agent {
132522
132538
  const nodeIndex = {};
132523
132539
  const pathIndex = {};
132524
132540
  for (const node2 of Object.values(tree.nodes)) {
132525
- const path31 = this.treePath(tree, node2.id);
132541
+ const path32 = this.treePath(tree, node2.id);
132526
132542
  const branchGroupIds = Object.values(tree.branchGroups).filter((group) => group.nodeIds.includes(node2.id)).map((group) => group.id);
132527
132543
  const messageIds = node2.chatMessages.map((message) => String(message.messageId || "")).filter(Boolean);
132528
132544
  const guideIds = node2.chatMessages.map((message) => String(message.guideId || "")).filter(Boolean);
@@ -132532,7 +132548,7 @@ var Agent5 = class _Agent {
132532
132548
  nodeId: node2.id,
132533
132549
  parentId: node2.parentId,
132534
132550
  childIds: [...childIds.get(node2.id) || []],
132535
- path: path31,
132551
+ path: path32,
132536
132552
  sourceMessageId: node2.sourceMessageId,
132537
132553
  sourceGuideId: node2.sourceGuideId,
132538
132554
  branchGroupIds,
@@ -132541,7 +132557,7 @@ var Agent5 = class _Agent {
132541
132557
  workRunIds,
132542
132558
  runningWorkRunIds
132543
132559
  };
132544
- pathIndex[path31.join(">")] = node2.id;
132560
+ pathIndex[path32.join(">")] = node2.id;
132545
132561
  }
132546
132562
  tree.nodeIndex = nodeIndex;
132547
132563
  tree.pathIndex = pathIndex;
@@ -132579,14 +132595,14 @@ var Agent5 = class _Agent {
132579
132595
  }
132580
132596
  }
132581
132597
  resolveConversationTreePath(tree, requestedPath) {
132582
- const path31 = (Array.isArray(requestedPath) ? requestedPath : []).map(String).filter(Boolean);
132583
- if (!path31.length) return tree.activeNodeId;
132584
- if (path31[0] !== tree.rootNodeId) throw new Error("Conversation branch path does not start at the tree root.");
132585
- for (let index2 = 0; index2 < path31.length; index2++) {
132586
- const node2 = tree.nodes[path31[index2]];
132587
- if (!node2 || index2 > 0 && node2.parentId !== path31[index2 - 1]) throw new Error("Conversation branch path is stale or invalid.");
132598
+ const path32 = (Array.isArray(requestedPath) ? requestedPath : []).map(String).filter(Boolean);
132599
+ if (!path32.length) return tree.activeNodeId;
132600
+ if (path32[0] !== tree.rootNodeId) throw new Error("Conversation branch path does not start at the tree root.");
132601
+ for (let index2 = 0; index2 < path32.length; index2++) {
132602
+ const node2 = tree.nodes[path32[index2]];
132603
+ if (!node2 || index2 > 0 && node2.parentId !== path32[index2 - 1]) throw new Error("Conversation branch path is stale or invalid.");
132588
132604
  }
132589
- return path31[path31.length - 1];
132605
+ return path32[path32.length - 1];
132590
132606
  }
132591
132607
  storedConversationTreePath(tree, requestedPath, fallbackNodeId) {
132592
132608
  if (!tree) return [];
@@ -134266,8 +134282,15 @@ ${String(event.toolArgs || "")}`;
134266
134282
  deduped.set(key3, {
134267
134283
  content,
134268
134284
  queueMode,
134285
+ buildId: String(raw.buildId || "").trim() || void 0,
134269
134286
  clientMessageId,
134270
134287
  runId: String(raw.runId || "").trim() || void 0,
134288
+ branchNodeId: String(raw.branchNodeId || "").trim() || void 0,
134289
+ branchPath: Array.isArray(raw.branchPath) ? raw.branchPath.map((id) => String(id || "")).filter(Boolean) : void 0,
134290
+ ledgerBranchId: String(raw.ledgerBranchId || "").trim() || void 0,
134291
+ targetRuntimeKey: String(raw.targetRuntimeKey || "").trim() || void 0,
134292
+ workspaceKey: String(raw.workspaceKey || "").trim() || void 0,
134293
+ modelSelection: String(raw.modelSelection || "").trim() || void 0,
134271
134294
  images: images.length ? images : void 0,
134272
134295
  attachments: attachments.length ? attachments : void 0,
134273
134296
  hiddenUserInput: raw.hiddenUserInput === true,
@@ -135297,13 +135320,25 @@ Conversation title (a few words):`;
135297
135320
  if (error2 instanceof SyntaxError) return "provider returned invalid JSON";
135298
135321
  return "provider request failed";
135299
135322
  }
135323
+ /**
135324
+ * Deterministic provider rejections (bad key, forbidden endpoint, unknown
135325
+ * model, invalid request, payment required) cannot succeed by retrying the
135326
+ * identical title probe. Only transient transport, timeout, rate-limit and
135327
+ * provider-internal failures enter the bounded 5-stage backoff.
135328
+ */
135329
+ conversationTitleFailureIsRetryable(error2) {
135330
+ const message = error2 instanceof Error ? error2.message : "";
135331
+ const status = message.match(/^\[LLM Error:\s*([1-5]\d{2})\]/)?.[1];
135332
+ if (!status) return true;
135333
+ return status === "408" || status === "429" || status.startsWith("5");
135334
+ }
135300
135335
  async waitForConversationTitleRetry(delayMs, signal) {
135301
135336
  if (signal?.aborted || delayMs <= 0) return;
135302
- await new Promise((resolve15) => {
135337
+ await new Promise((resolve16) => {
135303
135338
  const finish = () => {
135304
135339
  clearTimeout(timer);
135305
135340
  signal?.removeEventListener("abort", finish);
135306
- resolve15();
135341
+ resolve16();
135307
135342
  };
135308
135343
  const timer = setTimeout(finish, delayMs);
135309
135344
  signal?.addEventListener("abort", finish, { once: true });
@@ -135320,21 +135355,25 @@ Conversation title (a few words):`;
135320
135355
  const retryDelaysMs = [0, 1e3, 2e3, 4e3, 8e3];
135321
135356
  if (!messageId || !firstUserInput.trim()) return false;
135322
135357
  let lastFailure = "provider returned an empty or unusable title";
135358
+ let terminalFailure = false;
135323
135359
  const requestTitle = async () => {
135324
135360
  lastFailure = "provider returned an empty or unusable title";
135361
+ terminalFailure = false;
135325
135362
  try {
135326
135363
  return await this.deriveConversationTitleFromProvider(firstUserInput, provider, modelName, intelligence, signal);
135327
135364
  } catch (error2) {
135328
135365
  lastFailure = this.conversationTitleFailureCause(error2, provider);
135366
+ terminalFailure = !this.conversationTitleFailureIsRetryable(error2);
135329
135367
  return "";
135330
135368
  }
135331
135369
  };
135332
135370
  const exhaustedFailure = () => new Error(
135333
- `Conversation title generation failed; ${lastFailure}. The first Agent request was not started. Retry the first input.`
135371
+ `Conversation title generation failed for ${provider.name}/${modelName}; ${lastFailure}. The first Agent request was not started. Retry the first input or switch the model.`
135334
135372
  );
135335
135373
  if (!stateKey2) {
135336
135374
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
135337
135375
  if (await requestTitle()) return true;
135376
+ if (terminalFailure) break;
135338
135377
  if (signal?.aborted) return false;
135339
135378
  if (attempt < maxAttempts - 1) await this.waitForConversationTitleRetry(retryDelaysMs[attempt], signal);
135340
135379
  }
@@ -135365,6 +135404,7 @@ Conversation title (a few words):`;
135365
135404
  this.publishConversationTitle(title, conversationId);
135366
135405
  return true;
135367
135406
  }
135407
+ if (terminalFailure) break;
135368
135408
  if (signal?.aborted) return false;
135369
135409
  if (attempt < maxAttempts - 1) await this.waitForConversationTitleRetry(retryDelaysMs[attempt], signal);
135370
135410
  }
@@ -137186,6 +137226,8 @@ ${summary}`, segment, "local-summarize", true);
137186
137226
  requestContext = {
137187
137227
  requestId: context.requestId,
137188
137228
  runId: context.runId,
137229
+ branchId: String(context.branchId || ""),
137230
+ contextHash: String(context.contextHash || ""),
137189
137231
  model: String(context.model || ""),
137190
137232
  at: context.at,
137191
137233
  estimatedTokens: 0,
@@ -137260,10 +137302,18 @@ ${summary}`, segment, "local-summarize", true);
137260
137302
  return request;
137261
137303
  }
137262
137304
  recordRequestContext(request, messages, system, tools, model) {
137305
+ const contextHash = crypto15.createHash("sha256").update(JSON.stringify({
137306
+ model,
137307
+ system,
137308
+ tools,
137309
+ messages
137310
+ })).digest("hex").slice(0, 24);
137263
137311
  const context = {
137264
137312
  ...estimateSubmittedContext(messages, system, tools, this.compressionBuildBlockStart(messages)),
137265
137313
  requestId: request.id,
137266
137314
  runId: this.currentWorkRunId(),
137315
+ branchId: this.currentBranchNodeId(),
137316
+ contextHash,
137267
137317
  model,
137268
137318
  at: (/* @__PURE__ */ new Date()).toISOString()
137269
137319
  };
@@ -138014,7 +138064,7 @@ ${msg.content}
138014
138064
  }
138015
138065
  for (const entry of entries) {
138016
138066
  if (!entry.endsWith(".md")) continue;
138017
- await new Promise((resolve15) => setImmediate(resolve15));
138067
+ await new Promise((resolve16) => setImmediate(resolve16));
138018
138068
  const archivePath = path30.join(archiveDir, entry);
138019
138069
  const firstLine = await this.readArchiveFirstLine(archivePath);
138020
138070
  const id = `archive|${Buffer.from(path30.resolve(archiveDir), "utf-8").toString("base64")}|${Buffer.from(entry, "utf-8").toString("base64")}`;
@@ -139112,6 +139162,10 @@ ${persisted.map((guide, index2) => `Guide ${index2 + 1}: ${guide.text}`).join("\
139112
139162
  if (!titleProvider || !titleModelName) {
139113
139163
  throw new Error("Conversation title generation failed; no resolved model deployment is available. No LLM configured. Add provider in Settings > Models.");
139114
139164
  }
139165
+ this.emitWorkEvent({
139166
+ type: "status",
139167
+ content: `Preparing the first response: checking ${titleProvider.name}/${titleModelName} and generating the conversation title.`
139168
+ });
139115
139169
  const titled = await this.startFirstInputConversationTitle(
139116
139170
  firstResponseTitleInput.messageId,
139117
139171
  firstResponseTitleInput.input,
@@ -141378,8 +141432,943 @@ var GoalStateImpl = class {
141378
141432
  }
141379
141433
  };
141380
141434
 
141381
- // src/core/conversationKernel.ts
141435
+ // src/core/continuation/store.ts
141436
+ var fs28 = __toESM(require("fs"));
141437
+ var path31 = __toESM(require("path"));
141382
141438
  var import_crypto18 = require("crypto");
141439
+
141440
+ // src/core/continuation/contracts.ts
141441
+ var CONTINUATION_SCHEMA_VERSION = 1;
141442
+ var ContinuationError = class extends Error {
141443
+ constructor(code, message, detail) {
141444
+ super(message);
141445
+ this.code = code;
141446
+ this.detail = detail;
141447
+ this.name = "ContinuationError";
141448
+ }
141449
+ code;
141450
+ detail;
141451
+ };
141452
+ function stableJson(value) {
141453
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
141454
+ if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
141455
+ const record3 = value;
141456
+ return `{${Object.keys(record3).sort().map((key3) => `${JSON.stringify(key3)}:${stableJson(record3[key3])}`).join(",")}}`;
141457
+ }
141458
+ function emptyLedger(workspaceId) {
141459
+ return {
141460
+ version: CONTINUATION_SCHEMA_VERSION,
141461
+ workspaceId,
141462
+ roots: {},
141463
+ branches: {},
141464
+ builds: {},
141465
+ attempts: {},
141466
+ guards: {},
141467
+ commands: {},
141468
+ finals: {},
141469
+ events: [],
141470
+ nextEventCursor: 1,
141471
+ nextQueueSequence: 1
141472
+ };
141473
+ }
141474
+ function defaultGuard(branchId) {
141475
+ return { branchId, activeBuildId: null, activeAttemptId: null, fence: 0, leaseUntil: 0, workerCapability: "" };
141476
+ }
141477
+ function commandKey(actorId, commandId) {
141478
+ return `${actorId}\0${commandId}`;
141479
+ }
141480
+ function buildInputHash(input2) {
141481
+ return require("crypto").createHash("sha256").update(stableJson(input2)).digest("hex").slice(0, 24);
141482
+ }
141483
+ function requestHash(command) {
141484
+ return require("crypto").createHash("sha256").update(stableJson({
141485
+ type: command.type,
141486
+ target: command.target,
141487
+ expectedTailBuildId: command.expectedTailBuildId,
141488
+ expectedQueueRevision: command.expectedQueueRevision,
141489
+ input: command.input,
141490
+ recipeSnapshotId: command.recipeSnapshotId
141491
+ })).digest("hex");
141492
+ }
141493
+
141494
+ // src/core/continuation/store.ts
141495
+ var GuardedContinuationStore = class {
141496
+ constructor(workspacePath, workspaceId, options = {}) {
141497
+ this.workspacePath = workspacePath;
141498
+ this.workspaceId = workspaceId;
141499
+ this.ledgerPath = path31.join(path31.resolve(workspacePath), "conversations", "continuation-ledger.json");
141500
+ this.lockPath = `${this.ledgerPath}.lock`;
141501
+ this.leaseMs = Math.max(5e3, Math.floor(options.leaseMs || 6e4));
141502
+ this.eventRetention = Math.max(200, Math.floor(options.eventRetention || 5e3));
141503
+ }
141504
+ workspacePath;
141505
+ workspaceId;
141506
+ ledgerPath;
141507
+ lockPath;
141508
+ leaseMs;
141509
+ eventRetention;
141510
+ fingerprint = "";
141511
+ cached = null;
141512
+ get filePath() {
141513
+ return this.ledgerPath;
141514
+ }
141515
+ ensureRoot(rootId, defaultBranchId) {
141516
+ this.mutate((ledger) => {
141517
+ if (!ledger.roots[rootId]) {
141518
+ ledger.roots[rootId] = {
141519
+ rootId,
141520
+ workspaceId: this.workspaceId,
141521
+ defaultBranchId,
141522
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
141523
+ };
141524
+ }
141525
+ this.ensureBranchRecord(ledger, { rootId, branchId: defaultBranchId, parentAnchorBuildId: null });
141526
+ });
141527
+ }
141528
+ ensureBranch(input2) {
141529
+ return this.mutate((ledger) => this.ensureBranchRecord(ledger, input2));
141530
+ }
141531
+ getReceipt(actorId, commandId) {
141532
+ return this.readLedger().commands[commandKey(actorId, commandId)];
141533
+ }
141534
+ enqueueBuild(command) {
141535
+ if (!command.target?.workspaceId || !command.target.expectedRootId || !command.target.branchId) {
141536
+ throw new ContinuationError("TARGET_REQUIRED", "workspaceId, expectedRootId and branchId are required");
141537
+ }
141538
+ if (command.target.workspaceId !== this.workspaceId) {
141539
+ throw new ContinuationError("ROUTE_MISMATCH", `Command workspace ${command.target.workspaceId} does not match ledger workspace ${this.workspaceId}`);
141540
+ }
141541
+ const hash = requestHash(command);
141542
+ return this.mutate((ledger) => {
141543
+ const key3 = commandKey(command.actorId, command.commandId);
141544
+ const existing = ledger.commands[key3];
141545
+ if (existing) {
141546
+ if (existing.requestHash !== hash) {
141547
+ throw new ContinuationError("IDEMPOTENCY_KEY_REUSE", `Command ${command.commandId} was already used with a different request`, { commandId: command.commandId });
141548
+ }
141549
+ return { ...existing, duplicate: true };
141550
+ }
141551
+ const branch = this.requireBranch(ledger, {
141552
+ workspaceId: command.target.workspaceId,
141553
+ rootId: command.target.expectedRootId,
141554
+ branchId: command.target.branchId
141555
+ });
141556
+ if (branch.queueRevision !== command.expectedQueueRevision) {
141557
+ throw new ContinuationError("QUEUE_REVISION_CONFLICT", `Queue revision ${command.expectedQueueRevision} is stale; authoritative revision is ${branch.queueRevision}`, {
141558
+ expected: command.expectedQueueRevision,
141559
+ actual: branch.queueRevision
141560
+ });
141561
+ }
141562
+ if ((branch.tailBuildId || null) !== (command.expectedTailBuildId || null)) {
141563
+ throw new ContinuationError("QUEUE_REVISION_CONFLICT", `Expected tail ${command.expectedTailBuildId || "null"} does not match authoritative tail ${branch.tailBuildId || "null"}`, {
141564
+ expected: command.expectedTailBuildId,
141565
+ actual: branch.tailBuildId
141566
+ });
141567
+ }
141568
+ const parentBuildId = branch.tailBuildId;
141569
+ const parent2 = parentBuildId ? ledger.builds[parentBuildId] : null;
141570
+ if (parentBuildId && (!parent2 || parent2.branchId !== branch.branchId)) {
141571
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch tail ${parentBuildId} is not owned by branch ${branch.branchId}`);
141572
+ }
141573
+ const buildId = `build-${(0, import_crypto18.randomUUID)()}`;
141574
+ const queueSequence = ledger.nextQueueSequence++;
141575
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
141576
+ const build2 = {
141577
+ buildId,
141578
+ workspaceId: this.workspaceId,
141579
+ rootId: branch.rootId,
141580
+ branchId: branch.branchId,
141581
+ parentBuildId,
141582
+ inputHash: buildInputHash(command.input),
141583
+ input: cloneInput(command.input),
141584
+ recipeSnapshotId: command.recipeSnapshotId,
141585
+ status: "QUEUED",
141586
+ queueSequence,
141587
+ createdAt: now2,
141588
+ updatedAt: now2
141589
+ };
141590
+ ledger.builds[buildId] = build2;
141591
+ branch.tailBuildId = buildId;
141592
+ branch.queueRevision += 1;
141593
+ branch.lifecycleRevision += 1;
141594
+ branch.updatedAt = now2;
141595
+ const receipt = {
141596
+ schemaVersion: 1,
141597
+ commandId: command.commandId,
141598
+ requestHash: hash,
141599
+ workspaceId: this.workspaceId,
141600
+ rootId: branch.rootId,
141601
+ branchId: branch.branchId,
141602
+ buildId,
141603
+ parentBuildId,
141604
+ queueSequence,
141605
+ queueRevision: branch.queueRevision,
141606
+ lifecycleRevision: branch.lifecycleRevision,
141607
+ acceptedAt: now2
141608
+ };
141609
+ ledger.commands[key3] = receipt;
141610
+ this.appendEvent(ledger, {
141611
+ type: "BuildAccepted",
141612
+ workspaceId: this.workspaceId,
141613
+ rootId: branch.rootId,
141614
+ branchId: branch.branchId,
141615
+ buildId,
141616
+ attemptId: null,
141617
+ fence: null,
141618
+ payload: { parentBuildId, queueSequence, inputHash: build2.inputHash }
141619
+ });
141620
+ return receipt;
141621
+ });
141622
+ }
141623
+ claimBuild(input2) {
141624
+ return this.mutate((ledger) => {
141625
+ const branch = this.requireBranch(ledger, input2);
141626
+ if (branch.paused) throw new ContinuationError("BRANCH_PAUSED", `Branch ${branch.branchId} is paused`);
141627
+ const now2 = input2.now ?? Date.now();
141628
+ const guard = this.ensureGuard(ledger, branch.branchId);
141629
+ if (guard.activeBuildId && guard.leaseUntil > now2) {
141630
+ return null;
141631
+ }
141632
+ if (guard.activeBuildId) this.releaseExpiredGuard(ledger, branch, guard, now2);
141633
+ const candidate = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence).find((build2) => {
141634
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) return false;
141635
+ const parent2 = build2.parentBuildId ? ledger.builds[build2.parentBuildId] : null;
141636
+ return !parent2 || parent2.status === "SUCCEEDED";
141637
+ });
141638
+ if (!candidate) return null;
141639
+ const attemptId = `attempt-${(0, import_crypto18.randomUUID)()}`;
141640
+ const fence = guard.fence + 1;
141641
+ const leaseUntil = now2 + this.leaseMs;
141642
+ const attempt = {
141643
+ attemptId,
141644
+ buildId: candidate.buildId,
141645
+ branchId: branch.branchId,
141646
+ fence,
141647
+ status: "RUNNING",
141648
+ leaseUntil,
141649
+ workerCapability: String(input2.workerCapability || "unknown"),
141650
+ startedAt: new Date(now2).toISOString()
141651
+ };
141652
+ ledger.attempts[attemptId] = attempt;
141653
+ ledger.guards[branch.branchId] = {
141654
+ branchId: branch.branchId,
141655
+ activeBuildId: candidate.buildId,
141656
+ activeAttemptId: attemptId,
141657
+ fence,
141658
+ leaseUntil,
141659
+ workerCapability: attempt.workerCapability
141660
+ };
141661
+ candidate.status = "RUNNING";
141662
+ candidate.updatedAt = attempt.startedAt;
141663
+ candidate.waitingReason = void 0;
141664
+ branch.lifecycleRevision += 1;
141665
+ branch.updatedAt = attempt.startedAt;
141666
+ this.appendEvent(ledger, {
141667
+ type: "AttemptStarted",
141668
+ workspaceId: this.workspaceId,
141669
+ rootId: branch.rootId,
141670
+ branchId: branch.branchId,
141671
+ buildId: candidate.buildId,
141672
+ attemptId,
141673
+ fence,
141674
+ payload: { parentBuildId: candidate.parentBuildId, workerCapability: attempt.workerCapability }
141675
+ });
141676
+ return {
141677
+ workspaceId: this.workspaceId,
141678
+ rootId: branch.rootId,
141679
+ branchId: branch.branchId,
141680
+ buildId: candidate.buildId,
141681
+ attemptId,
141682
+ fence,
141683
+ parentBuildId: candidate.parentBuildId,
141684
+ baseContextSnapshotId: candidate.recipeSnapshotId,
141685
+ environmentSnapshotId: candidate.recipeSnapshotId,
141686
+ workerCapability: attempt.workerCapability
141687
+ };
141688
+ });
141689
+ }
141690
+ updateQueuedBuild(input2) {
141691
+ return this.mutate((ledger) => {
141692
+ const build2 = ledger.builds[input2.buildId];
141693
+ if (!build2) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} does not exist`);
141694
+ if (build2.workspaceId !== this.workspaceId || input2.rootId && build2.rootId !== input2.rootId) {
141695
+ throw new ContinuationError("ROUTE_MISMATCH", `Build ${input2.buildId} does not belong to workspace/root ${this.workspaceId}/${input2.rootId}`);
141696
+ }
141697
+ const branch = ledger.branches[build2.branchId];
141698
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Build ${input2.buildId} references missing branch ${build2.branchId}`);
141699
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only QUEUED builds can be edited`);
141700
+ build2.input = cloneInput(input2.input);
141701
+ build2.inputHash = buildInputHash(build2.input);
141702
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141703
+ branch.queueRevision += 1;
141704
+ branch.lifecycleRevision += 1;
141705
+ branch.updatedAt = build2.updatedAt;
141706
+ return { ...build2, input: cloneInput(build2.input) };
141707
+ });
141708
+ }
141709
+ deleteQueuedBuild(input2) {
141710
+ this.mutate((ledger) => {
141711
+ const build2 = ledger.builds[input2.buildId];
141712
+ if (!build2) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} does not exist`);
141713
+ if (build2.workspaceId !== this.workspaceId || input2.rootId && build2.rootId !== input2.rootId) {
141714
+ throw new ContinuationError("ROUTE_MISMATCH", `Build ${input2.buildId} does not belong to workspace/root ${this.workspaceId}/${input2.rootId}`);
141715
+ }
141716
+ const branch = ledger.branches[build2.branchId];
141717
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Build ${input2.buildId} references missing branch ${build2.branchId}`);
141718
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only QUEUED builds can be deleted`);
141719
+ if (Object.values(ledger.builds).some((item) => item.parentBuildId === build2.buildId)) {
141720
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} still has queued successors; delete them from the tail first`);
141721
+ }
141722
+ if (branch.tailBuildId === build2.buildId) branch.tailBuildId = build2.parentBuildId;
141723
+ delete ledger.builds[build2.buildId];
141724
+ branch.queueRevision += 1;
141725
+ branch.lifecycleRevision += 1;
141726
+ branch.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141727
+ });
141728
+ }
141729
+ reorderQueuedBuilds(input2) {
141730
+ return this.mutate((ledger) => {
141731
+ const branch = this.requireBranch(ledger, input2);
141732
+ const queued = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence);
141733
+ throw new ContinuationError(
141734
+ "ANCHOR_NOT_COMMITTED",
141735
+ `Branch ${branch.branchId} has ${queued.length} admitted queued build(s); reordering would change their fixed parents. Cancel the suffix and submit it as new commands.`,
141736
+ { branchId: branch.branchId, queuedBuildIds: queued.map((build2) => build2.buildId) }
141737
+ );
141738
+ });
141739
+ }
141740
+ heartbeat(scope, now2 = Date.now()) {
141741
+ return this.mutate((ledger) => {
141742
+ const guard = ledger.guards[scope.branchId];
141743
+ const attempt = ledger.attempts[scope.attemptId];
141744
+ if (!guard || !attempt || guard.activeBuildId !== scope.buildId || guard.activeAttemptId !== scope.attemptId || guard.fence !== scope.fence || attempt.fence !== scope.fence || attempt.status !== "RUNNING" || guard.leaseUntil <= now2) {
141745
+ this.appendEvent(ledger, {
141746
+ type: "StaleWriteRejected",
141747
+ workspaceId: this.workspaceId,
141748
+ rootId: ledger.builds[scope.buildId]?.rootId || "",
141749
+ branchId: scope.branchId,
141750
+ buildId: scope.buildId,
141751
+ attemptId: scope.attemptId,
141752
+ fence: scope.fence,
141753
+ payload: { operation: "heartbeat" }
141754
+ });
141755
+ return false;
141756
+ }
141757
+ const leaseUntil = now2 + this.leaseMs;
141758
+ attempt.leaseUntil = leaseUntil;
141759
+ guard.leaseUntil = leaseUntil;
141760
+ this.appendEvent(ledger, {
141761
+ type: "AttemptHeartbeat",
141762
+ workspaceId: this.workspaceId,
141763
+ rootId: ledger.builds[scope.buildId]?.rootId || "",
141764
+ branchId: scope.branchId,
141765
+ buildId: scope.buildId,
141766
+ attemptId: scope.attemptId,
141767
+ fence: scope.fence,
141768
+ payload: { leaseUntil }
141769
+ });
141770
+ return true;
141771
+ });
141772
+ }
141773
+ commitFinal(input2) {
141774
+ return this.mutate((ledger) => {
141775
+ const { scope } = input2;
141776
+ const branch = this.requireBranch(ledger, scope);
141777
+ const build2 = ledger.builds[scope.buildId];
141778
+ const attempt = ledger.attempts[scope.attemptId];
141779
+ const guard = ledger.guards[scope.branchId];
141780
+ const now2 = input2.now ?? Date.now();
141781
+ if (!build2 || build2.branchId !== scope.branchId || build2.rootId !== scope.rootId) {
141782
+ throw new ContinuationError("UNKNOWN_BUILD", `Build ${scope.buildId} does not belong to branch ${scope.branchId}`);
141783
+ }
141784
+ if (ledger.finals[build2.buildId]) {
141785
+ throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already has an immutable final`, { final: ledger.finals[build2.buildId] });
141786
+ }
141787
+ if (!attempt || !guard || guard.activeBuildId !== scope.buildId || guard.activeAttemptId !== scope.attemptId || guard.fence !== scope.fence || attempt.fence !== scope.fence || attempt.status !== "RUNNING" || guard.leaseUntil <= now2) {
141788
+ this.appendEvent(ledger, {
141789
+ type: "StaleWriteRejected",
141790
+ workspaceId: this.workspaceId,
141791
+ rootId: branch.rootId,
141792
+ branchId: branch.branchId,
141793
+ buildId: build2.buildId,
141794
+ attemptId: scope.attemptId,
141795
+ fence: scope.fence,
141796
+ payload: { operation: "commit_final" }
141797
+ });
141798
+ throw new ContinuationError("STALE_EXECUTION", `Attempt ${scope.attemptId} no longer owns branch ${branch.branchId}`);
141799
+ }
141800
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) {
141801
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} parent ${build2.parentBuildId || "null"} is not the current head ${branch.headBuildId || "null"}`);
141802
+ }
141803
+ const final = {
141804
+ finalId: `final-${(0, import_crypto18.randomUUID)()}`,
141805
+ buildId: build2.buildId,
141806
+ branchId: branch.branchId,
141807
+ finalHash: String(input2.finalHash || (0, import_crypto18.createHash)("sha256").update(String(input2.text || "")).digest("hex").slice(0, 24)),
141808
+ stateSnapshotId: String(input2.stateSnapshotId || build2.recipeSnapshotId),
141809
+ text: String(input2.text || ""),
141810
+ committedAt: new Date(now2).toISOString()
141811
+ };
141812
+ ledger.finals[build2.buildId] = final;
141813
+ build2.status = "SUCCEEDED";
141814
+ build2.finalId = final.finalId;
141815
+ build2.updatedAt = final.committedAt;
141816
+ attempt.status = "COMPLETED";
141817
+ attempt.endedAt = final.committedAt;
141818
+ branch.headBuildId = build2.buildId;
141819
+ branch.lifecycleRevision += 1;
141820
+ branch.updatedAt = final.committedAt;
141821
+ this.releaseGuard(ledger, branch.branchId, attempt.fence);
141822
+ this.appendEvent(ledger, {
141823
+ type: "BuildCommitted",
141824
+ workspaceId: this.workspaceId,
141825
+ rootId: branch.rootId,
141826
+ branchId: branch.branchId,
141827
+ buildId: build2.buildId,
141828
+ attemptId: attempt.attemptId,
141829
+ fence: attempt.fence,
141830
+ payload: { finalId: final.finalId, finalHash: final.finalHash, headBuildId: branch.headBuildId }
141831
+ });
141832
+ return final;
141833
+ });
141834
+ }
141835
+ /**
141836
+ * Trusted external-owner completion.
141837
+ *
141838
+ * A Flow is a kernel-owned external run, not a leased model worker. It still
141839
+ * has to be a durable build so queued Goal/Next successors have a committed
141840
+ * parent. This path validates the parent/head relation transactionally but
141841
+ * does not require a BranchGuard attempt; the kernel owns the Flow lifetime.
141842
+ * If the build is not the next ready build, it stays QUEUED and the caller
141843
+ * must retry after the predecessor commits.
141844
+ */
141845
+ commitExternalBuild(input2) {
141846
+ return this.mutate((ledger) => {
141847
+ const branch = this.requireBranch(ledger, input2);
141848
+ const build2 = ledger.builds[input2.buildId];
141849
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} is not in branch ${branch.branchId}`);
141850
+ if (build2.status === "SUCCEEDED") return true;
141851
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `External build ${build2.buildId} is ${build2.status}`);
141852
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) return false;
141853
+ const now2 = input2.now ?? Date.now();
141854
+ const committedAt = new Date(now2).toISOString();
141855
+ const final = {
141856
+ finalId: `final-${(0, import_crypto18.randomUUID)()}`,
141857
+ buildId: build2.buildId,
141858
+ branchId: branch.branchId,
141859
+ finalHash: (0, import_crypto18.createHash)("sha256").update(String(input2.text || "")).digest("hex").slice(0, 24),
141860
+ stateSnapshotId: build2.recipeSnapshotId,
141861
+ text: String(input2.text || ""),
141862
+ committedAt
141863
+ };
141864
+ ledger.finals[build2.buildId] = final;
141865
+ build2.status = "SUCCEEDED";
141866
+ build2.finalId = final.finalId;
141867
+ build2.updatedAt = committedAt;
141868
+ branch.headBuildId = build2.buildId;
141869
+ branch.lifecycleRevision += 1;
141870
+ branch.updatedAt = committedAt;
141871
+ this.appendEvent(ledger, {
141872
+ type: "BuildCommitted",
141873
+ workspaceId: this.workspaceId,
141874
+ rootId: branch.rootId,
141875
+ branchId: branch.branchId,
141876
+ buildId: build2.buildId,
141877
+ attemptId: null,
141878
+ fence: null,
141879
+ payload: { finalId: final.finalId, finalHash: final.finalHash, externalOwner: true, headBuildId: branch.headBuildId }
141880
+ });
141881
+ return true;
141882
+ });
141883
+ }
141884
+ /**
141885
+ * Claim a new attempt for an existing external Flow build (suspend/resume).
141886
+ * The build identity and fixed parent are preserved; only the attempt/fence
141887
+ * advance. This is the external-owner equivalent of retryBuild.
141888
+ */
141889
+ claimExternalBuild(input2) {
141890
+ return this.mutate((ledger) => {
141891
+ const branch = this.requireBranch(ledger, input2);
141892
+ const build2 = ledger.builds[input2.buildId];
141893
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} is not in branch ${branch.branchId}`);
141894
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already committed`);
141895
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `External build ${build2.buildId} is ${build2.status}`);
141896
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) {
141897
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `External build ${build2.buildId} parent is not the current head`);
141898
+ }
141899
+ const now2 = input2.now ?? Date.now();
141900
+ const guard = this.ensureGuard(ledger, branch.branchId);
141901
+ const attemptId = `attempt-${(0, import_crypto18.randomUUID)()}`;
141902
+ const fence = guard.fence + 1;
141903
+ const leaseUntil = now2 + this.leaseMs;
141904
+ const attempt = {
141905
+ attemptId,
141906
+ buildId: build2.buildId,
141907
+ branchId: branch.branchId,
141908
+ fence,
141909
+ status: "RUNNING",
141910
+ leaseUntil,
141911
+ workerCapability: String(input2.workerCapability || "flow-external"),
141912
+ startedAt: new Date(now2).toISOString()
141913
+ };
141914
+ ledger.attempts[attemptId] = attempt;
141915
+ ledger.guards[branch.branchId] = {
141916
+ branchId: branch.branchId,
141917
+ activeBuildId: build2.buildId,
141918
+ activeAttemptId: attemptId,
141919
+ fence,
141920
+ leaseUntil,
141921
+ workerCapability: attempt.workerCapability
141922
+ };
141923
+ build2.status = "RUNNING";
141924
+ build2.updatedAt = attempt.startedAt;
141925
+ branch.lifecycleRevision += 1;
141926
+ this.appendEvent(ledger, {
141927
+ type: "AttemptStarted",
141928
+ workspaceId: this.workspaceId,
141929
+ rootId: branch.rootId,
141930
+ branchId: branch.branchId,
141931
+ buildId: build2.buildId,
141932
+ attemptId,
141933
+ fence,
141934
+ payload: { externalOwner: true, workerCapability: attempt.workerCapability }
141935
+ });
141936
+ return {
141937
+ workspaceId: this.workspaceId,
141938
+ rootId: branch.rootId,
141939
+ branchId: branch.branchId,
141940
+ buildId: build2.buildId,
141941
+ attemptId,
141942
+ fence,
141943
+ parentBuildId: build2.parentBuildId,
141944
+ baseContextSnapshotId: build2.recipeSnapshotId,
141945
+ environmentSnapshotId: build2.recipeSnapshotId,
141946
+ workerCapability: attempt.workerCapability
141947
+ };
141948
+ });
141949
+ }
141950
+ failBuild(input2) {
141951
+ this.terminateAttempt(input2.scope, "FAILED", input2.reason, input2.now);
141952
+ }
141953
+ cancelBuild(input2) {
141954
+ this.mutate((ledger) => {
141955
+ const branch = this.requireBranch(ledger, input2);
141956
+ const build2 = ledger.builds[input2.buildId];
141957
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} is not in branch ${branch.branchId}`);
141958
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${input2.buildId} already committed`);
141959
+ const guard = this.ensureGuard(ledger, branch.branchId);
141960
+ if (guard.activeBuildId === build2.buildId) {
141961
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
141962
+ if (attempt) {
141963
+ attempt.status = "CANCELLED";
141964
+ attempt.endedAt = new Date(input2.now ?? Date.now()).toISOString();
141965
+ }
141966
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
141967
+ }
141968
+ build2.status = "CANCELLED";
141969
+ build2.updatedAt = new Date(input2.now ?? Date.now()).toISOString();
141970
+ branch.lifecycleRevision += 1;
141971
+ this.markDependentsBlocked(ledger, branch, build2.buildId);
141972
+ this.appendEvent(ledger, {
141973
+ type: "BuildCancelled",
141974
+ workspaceId: this.workspaceId,
141975
+ rootId: branch.rootId,
141976
+ branchId: branch.branchId,
141977
+ buildId: build2.buildId,
141978
+ attemptId: null,
141979
+ fence: null
141980
+ });
141981
+ });
141982
+ }
141983
+ retryBuild(input2) {
141984
+ return this.mutate((ledger) => {
141985
+ const branch = this.requireBranch(ledger, input2);
141986
+ const build2 = ledger.builds[input2.buildId];
141987
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} is not in branch ${branch.branchId}`);
141988
+ if (build2.status !== "FAILED" && build2.status !== "CANCELLED") {
141989
+ throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only FAILED/CANCELLED builds can be retried`);
141990
+ }
141991
+ if (this.hasCommittedDescendant(ledger, build2.buildId)) {
141992
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} already has a committed descendant`);
141993
+ }
141994
+ build2.status = "QUEUED";
141995
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141996
+ branch.lifecycleRevision += 1;
141997
+ return { ...build2, input: cloneInput(build2.input) };
141998
+ });
141999
+ }
142000
+ /**
142001
+ * Idempotent failure recovery for an input that was never accepted.
142002
+ *
142003
+ * Stop/archive may release the branch guard before the runtime reports the
142004
+ * failure. In that case the build is still the same durable row and must be
142005
+ * returned to QUEUED for an explicit resume instead of being stranded in
142006
+ * RUNNING (or permanently FAILED). A committed build is never requeued.
142007
+ */
142008
+ requeueBuild(input2) {
142009
+ return this.mutate((ledger) => {
142010
+ const branch = this.requireBranch(ledger, input2);
142011
+ const build2 = ledger.builds[input2.buildId];
142012
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input2.buildId} is not in branch ${branch.branchId}`);
142013
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already committed and cannot be requeued`);
142014
+ const guard = this.ensureGuard(ledger, branch.branchId);
142015
+ if (guard.activeBuildId === build2.buildId) {
142016
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142017
+ if (attempt && attempt.status === "RUNNING") {
142018
+ attempt.status = "EXPIRED";
142019
+ attempt.endedAt = (/* @__PURE__ */ new Date()).toISOString();
142020
+ }
142021
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
142022
+ }
142023
+ build2.status = "QUEUED";
142024
+ build2.waitingReason = void 0;
142025
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
142026
+ branch.lifecycleRevision += 1;
142027
+ branch.updatedAt = build2.updatedAt;
142028
+ return { ...build2, input: cloneInput(build2.input) };
142029
+ });
142030
+ }
142031
+ forkBranch(input2) {
142032
+ const hash = (0, import_crypto18.createHash)("sha256").update(JSON.stringify(input2)).digest("hex");
142033
+ return this.mutate((ledger) => {
142034
+ const key3 = commandKey(input2.actorId, input2.commandId);
142035
+ const existing = ledger.commands[key3];
142036
+ if (existing) {
142037
+ if (existing.requestHash !== hash) throw new ContinuationError("IDEMPOTENCY_KEY_REUSE", `Command ${input2.commandId} was already used with a different fork request`);
142038
+ return { ...ledger.branches[existing.branchId] };
142039
+ }
142040
+ const source = this.requireBranch(ledger, { workspaceId: input2.workspaceId, rootId: "", branchId: input2.sourceBranchId });
142041
+ const anchor2 = ledger.builds[input2.anchorBuildId];
142042
+ if (!anchor2 || anchor2.branchId !== source.branchId || anchor2.status !== "SUCCEEDED") {
142043
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Anchor ${input2.anchorBuildId} is not a committed build of source branch ${source.branchId}`);
142044
+ }
142045
+ if (!this.isAncestorOfHead(ledger, source, anchor2.buildId)) {
142046
+ throw new ContinuationError("ANCHOR_NOT_IN_LINEAGE", `Anchor ${anchor2.buildId} is not on the source branch lineage`);
142047
+ }
142048
+ const branch = this.ensureBranchRecord(ledger, {
142049
+ rootId: source.rootId,
142050
+ branchId: input2.newBranchId,
142051
+ parentAnchorBuildId: anchor2.buildId
142052
+ });
142053
+ branch.headBuildId = anchor2.buildId;
142054
+ branch.tailBuildId = anchor2.buildId;
142055
+ branch.queueRevision = 0;
142056
+ branch.lifecycleRevision += 1;
142057
+ const receipt = {
142058
+ schemaVersion: 1,
142059
+ commandId: input2.commandId,
142060
+ requestHash: hash,
142061
+ workspaceId: this.workspaceId,
142062
+ rootId: source.rootId,
142063
+ branchId: branch.branchId,
142064
+ buildId: anchor2.buildId,
142065
+ parentBuildId: anchor2.buildId,
142066
+ queueSequence: 0,
142067
+ queueRevision: branch.queueRevision,
142068
+ lifecycleRevision: branch.lifecycleRevision,
142069
+ acceptedAt: (/* @__PURE__ */ new Date()).toISOString()
142070
+ };
142071
+ ledger.commands[key3] = receipt;
142072
+ this.appendEvent(ledger, {
142073
+ type: "BranchForked",
142074
+ workspaceId: this.workspaceId,
142075
+ rootId: source.rootId,
142076
+ branchId: branch.branchId,
142077
+ buildId: anchor2.buildId,
142078
+ attemptId: null,
142079
+ fence: null,
142080
+ payload: { sourceBranchId: source.branchId, anchorBuildId: anchor2.buildId }
142081
+ });
142082
+ return { ...branch };
142083
+ });
142084
+ }
142085
+ setPaused(input2) {
142086
+ return this.mutate((ledger) => {
142087
+ const branch = this.requireBranch(ledger, input2);
142088
+ branch.paused = input2.paused === true;
142089
+ branch.lifecycleRevision += 1;
142090
+ branch.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
142091
+ this.appendEvent(ledger, {
142092
+ type: branch.paused ? "BranchPaused" : "BranchResumed",
142093
+ workspaceId: this.workspaceId,
142094
+ rootId: branch.rootId,
142095
+ branchId: branch.branchId,
142096
+ buildId: null,
142097
+ attemptId: null,
142098
+ fence: null
142099
+ });
142100
+ return branch.paused;
142101
+ });
142102
+ }
142103
+ snapshot(input2) {
142104
+ const ledger = this.readLedger();
142105
+ const branch = this.requireBranch(ledger, input2);
142106
+ return this.snapshotUnlocked(ledger, branch);
142107
+ }
142108
+ snapshotUnlocked(ledger, branch) {
142109
+ const guard = ledger.guards[branch.branchId] || defaultGuard(branch.branchId);
142110
+ const builds = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId).sort((a, b) => a.queueSequence - b.queueSequence).map((build2) => ({ ...build2, input: cloneInput(build2.input) }));
142111
+ return {
142112
+ workspaceId: this.workspaceId,
142113
+ rootId: branch.rootId,
142114
+ branchId: branch.branchId,
142115
+ headBuildId: branch.headBuildId,
142116
+ tailBuildId: branch.tailBuildId,
142117
+ queueRevision: branch.queueRevision,
142118
+ lifecycleRevision: branch.lifecycleRevision,
142119
+ paused: branch.paused,
142120
+ activeBuildId: guard.activeBuildId,
142121
+ guard: { ...guard },
142122
+ builds
142123
+ };
142124
+ }
142125
+ events(afterCursor = 0, limit = 500) {
142126
+ return this.readLedger().events.filter((event) => event.cursor > afterCursor).slice(0, Math.max(1, Math.min(5e3, limit))).map((event) => ({ ...event, payload: event.payload ? { ...event.payload } : void 0 }));
142127
+ }
142128
+ recoverExpiredLeases(now2 = Date.now()) {
142129
+ return this.mutate((ledger) => {
142130
+ let recovered = 0;
142131
+ for (const guard of Object.values(ledger.guards)) {
142132
+ if (!guard.activeBuildId || guard.leaseUntil > now2) continue;
142133
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142134
+ const build2 = ledger.builds[guard.activeBuildId];
142135
+ if (attempt && attempt.status === "RUNNING") {
142136
+ attempt.status = "EXPIRED";
142137
+ attempt.endedAt = new Date(now2).toISOString();
142138
+ }
142139
+ if (build2 && build2.status === "RUNNING") {
142140
+ build2.status = "QUEUED";
142141
+ build2.updatedAt = new Date(now2).toISOString();
142142
+ }
142143
+ this.releaseGuard(ledger, guard.branchId, guard.fence);
142144
+ recovered += 1;
142145
+ }
142146
+ return recovered;
142147
+ });
142148
+ }
142149
+ terminateAttempt(scope, status, reason, now2 = Date.now()) {
142150
+ this.mutate((ledger) => {
142151
+ const branch = this.requireBranch(ledger, scope);
142152
+ const build2 = ledger.builds[scope.buildId];
142153
+ const attempt = ledger.attempts[scope.attemptId];
142154
+ const guard = ledger.guards[scope.branchId];
142155
+ if (!build2 || !attempt || !guard || guard.activeAttemptId !== scope.attemptId || guard.fence !== scope.fence || attempt.fence !== scope.fence) {
142156
+ throw new ContinuationError("STALE_EXECUTION", `Attempt ${scope.attemptId} cannot terminate branch ${scope.branchId}`);
142157
+ }
142158
+ build2.status = status;
142159
+ build2.updatedAt = new Date(now2).toISOString();
142160
+ attempt.status = status === "FAILED" ? "FAILED" : "CANCELLED";
142161
+ attempt.endedAt = build2.updatedAt;
142162
+ branch.lifecycleRevision += 1;
142163
+ this.releaseGuard(ledger, branch.branchId, attempt.fence);
142164
+ this.markDependentsBlocked(ledger, branch, build2.buildId);
142165
+ this.appendEvent(ledger, {
142166
+ type: status === "FAILED" ? "BuildFailed" : "BuildCancelled",
142167
+ workspaceId: this.workspaceId,
142168
+ rootId: branch.rootId,
142169
+ branchId: branch.branchId,
142170
+ buildId: build2.buildId,
142171
+ attemptId: attempt.attemptId,
142172
+ fence: attempt.fence,
142173
+ payload: { reason: String(reason || "") }
142174
+ });
142175
+ });
142176
+ }
142177
+ releaseExpiredGuard(ledger, branch, guard, now2) {
142178
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142179
+ const build2 = guard.activeBuildId ? ledger.builds[guard.activeBuildId] : void 0;
142180
+ if (attempt && attempt.status === "RUNNING") {
142181
+ attempt.status = "EXPIRED";
142182
+ attempt.endedAt = new Date(now2).toISOString();
142183
+ }
142184
+ if (build2 && build2.status === "RUNNING") {
142185
+ build2.status = "QUEUED";
142186
+ build2.updatedAt = new Date(now2).toISOString();
142187
+ }
142188
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
142189
+ }
142190
+ markDependentsBlocked(ledger, branch, failedBuildId) {
142191
+ for (const build2 of Object.values(ledger.builds)) {
142192
+ if (build2.branchId !== branch.branchId || build2.status !== "QUEUED") continue;
142193
+ if (build2.parentBuildId === failedBuildId) build2.waitingReason = "DEPENDENCY_FAILED";
142194
+ }
142195
+ }
142196
+ hasCommittedDescendant(ledger, buildId) {
142197
+ return Object.values(ledger.builds).some((build2) => build2.parentBuildId === buildId && build2.status === "SUCCEEDED");
142198
+ }
142199
+ isAncestorOfHead(ledger, branch, anchorBuildId) {
142200
+ let cursor = branch.headBuildId;
142201
+ const seen = /* @__PURE__ */ new Set();
142202
+ while (cursor) {
142203
+ if (seen.has(cursor)) return false;
142204
+ seen.add(cursor);
142205
+ if (cursor === anchorBuildId) return true;
142206
+ cursor = ledger.builds[cursor]?.parentBuildId || null;
142207
+ }
142208
+ return false;
142209
+ }
142210
+ ensureBranchRecord(ledger, input2) {
142211
+ const existing = ledger.branches[input2.branchId];
142212
+ if (existing) return existing;
142213
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
142214
+ const branch = {
142215
+ branchId: input2.branchId,
142216
+ workspaceId: this.workspaceId,
142217
+ rootId: input2.rootId,
142218
+ parentAnchorBuildId: input2.parentAnchorBuildId,
142219
+ headBuildId: input2.parentAnchorBuildId,
142220
+ tailBuildId: input2.parentAnchorBuildId,
142221
+ queueRevision: 0,
142222
+ lifecycleRevision: 0,
142223
+ paused: false,
142224
+ createdAt: now2,
142225
+ updatedAt: now2
142226
+ };
142227
+ ledger.branches[branch.branchId] = branch;
142228
+ ledger.guards[branch.branchId] = defaultGuard(branch.branchId);
142229
+ if (!ledger.roots[branch.rootId]) {
142230
+ ledger.roots[branch.rootId] = { rootId: branch.rootId, workspaceId: this.workspaceId, defaultBranchId: branch.branchId, createdAt: now2 };
142231
+ }
142232
+ return branch;
142233
+ }
142234
+ requireBranch(ledger, target) {
142235
+ const branch = ledger.branches[target.branchId];
142236
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Branch ${target.branchId} does not exist`);
142237
+ if (branch.workspaceId !== this.workspaceId) {
142238
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch ${target.branchId} belongs to workspace ${branch.workspaceId}`);
142239
+ }
142240
+ if (target.rootId && branch.rootId !== target.rootId) {
142241
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch ${target.branchId} belongs to root ${branch.rootId}, not ${target.rootId}`);
142242
+ }
142243
+ return branch;
142244
+ }
142245
+ ensureGuard(ledger, branchId) {
142246
+ if (!ledger.guards[branchId]) ledger.guards[branchId] = defaultGuard(branchId);
142247
+ return ledger.guards[branchId];
142248
+ }
142249
+ /**
142250
+ * Release the active attempt without ever moving the branch fence backward.
142251
+ * A recovered/completed attempt's fence stays as the monotonic high-water
142252
+ * mark; the next claim increments it again.
142253
+ */
142254
+ releaseGuard(ledger, branchId, fence) {
142255
+ ledger.guards[branchId] = {
142256
+ ...defaultGuard(branchId),
142257
+ fence: Math.max(0, Math.floor(Number(fence) || 0))
142258
+ };
142259
+ }
142260
+ appendEvent(ledger, input2) {
142261
+ const event = {
142262
+ ...input2,
142263
+ eventId: `event-${(0, import_crypto18.randomUUID)()}`,
142264
+ cursor: ledger.nextEventCursor++,
142265
+ at: input2.at || (/* @__PURE__ */ new Date()).toISOString()
142266
+ };
142267
+ ledger.events.push(event);
142268
+ if (ledger.events.length > this.eventRetention) ledger.events = ledger.events.slice(-this.eventRetention);
142269
+ return event;
142270
+ }
142271
+ mutate(apply) {
142272
+ fs28.mkdirSync(path31.dirname(this.ledgerPath), { recursive: true });
142273
+ const lockHandle = this.acquireLock();
142274
+ try {
142275
+ this.invalidateCache();
142276
+ const ledger = this.readLedgerUnlocked();
142277
+ const result = apply(ledger);
142278
+ this.writeLedgerUnlocked(ledger);
142279
+ return result;
142280
+ } finally {
142281
+ try {
142282
+ fs28.closeSync(lockHandle);
142283
+ } catch {
142284
+ }
142285
+ try {
142286
+ fs28.unlinkSync(this.lockPath);
142287
+ } catch {
142288
+ }
142289
+ }
142290
+ }
142291
+ acquireLock() {
142292
+ for (let attempt = 0; attempt < 400; attempt += 1) {
142293
+ try {
142294
+ return fs28.openSync(this.lockPath, "wx");
142295
+ } catch (error2) {
142296
+ const code = error2 && typeof error2 === "object" && "code" in error2 ? String(error2.code || "") : "";
142297
+ if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(code)) throw error2;
142298
+ if (code === "EEXIST") {
142299
+ try {
142300
+ if (Date.now() - fs28.statSync(this.lockPath).mtimeMs > 3e4) fs28.unlinkSync(this.lockPath);
142301
+ } catch {
142302
+ }
142303
+ }
142304
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5 + attempt);
142305
+ }
142306
+ }
142307
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Timed out acquiring continuation ledger lock: ${this.lockPath}`);
142308
+ }
142309
+ readLedger() {
142310
+ this.ensureLedgerExists();
142311
+ const stat = fs28.statSync(this.ledgerPath, { bigint: true });
142312
+ const fingerprint2 = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}`;
142313
+ if (this.cached && this.fingerprint === fingerprint2) return this.cached;
142314
+ const ledger = this.readLedgerUnlocked();
142315
+ this.cached = ledger;
142316
+ this.fingerprint = fingerprint2;
142317
+ return ledger;
142318
+ }
142319
+ readLedgerUnlocked() {
142320
+ this.ensureLedgerExists();
142321
+ try {
142322
+ const raw = fs28.readFileSync(this.ledgerPath, "utf-8").replace(/^\uFEFF/, "");
142323
+ const parsed = JSON.parse(raw);
142324
+ if (!parsed || parsed.version !== 1 || !parsed.branches || !parsed.builds) {
142325
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Continuation ledger ${this.ledgerPath} has an unsupported shape`);
142326
+ }
142327
+ parsed.attempts = parsed.attempts || {};
142328
+ parsed.guards = parsed.guards || {};
142329
+ parsed.commands = parsed.commands || {};
142330
+ parsed.finals = parsed.finals || {};
142331
+ parsed.events = Array.isArray(parsed.events) ? parsed.events : [];
142332
+ parsed.nextEventCursor = Math.max(1, Number(parsed.nextEventCursor) || (parsed.events.at(-1)?.cursor || 0) + 1);
142333
+ parsed.nextQueueSequence = Math.max(1, Number(parsed.nextQueueSequence) || Object.values(parsed.builds).reduce((max, build2) => Math.max(max, build2.queueSequence || 0), 0) + 1);
142334
+ return parsed;
142335
+ } catch (error2) {
142336
+ if (error2 instanceof ContinuationError) throw error2;
142337
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Continuation ledger ${this.ledgerPath} is unreadable: ${error2 instanceof Error ? error2.message : String(error2)}`);
142338
+ }
142339
+ }
142340
+ writeLedgerUnlocked(ledger) {
142341
+ const temp = `${this.ledgerPath}.${process.pid}.${(0, import_crypto18.randomUUID)()}.tmp`;
142342
+ fs28.writeFileSync(temp, `${JSON.stringify(ledger, null, 2)}
142343
+ `, "utf-8");
142344
+ fs28.renameSync(temp, this.ledgerPath);
142345
+ this.invalidateCache();
142346
+ }
142347
+ ensureLedgerExists() {
142348
+ if (fs28.existsSync(this.ledgerPath)) return;
142349
+ fs28.mkdirSync(path31.dirname(this.ledgerPath), { recursive: true });
142350
+ const ledger = emptyLedger(this.workspaceId);
142351
+ const temp = `${this.ledgerPath}.${process.pid}.${(0, import_crypto18.randomUUID)()}.tmp`;
142352
+ fs28.writeFileSync(temp, `${JSON.stringify(ledger, null, 2)}
142353
+ `, "utf-8");
142354
+ fs28.renameSync(temp, this.ledgerPath);
142355
+ }
142356
+ invalidateCache() {
142357
+ this.cached = null;
142358
+ this.fingerprint = "";
142359
+ }
142360
+ };
142361
+ function cloneInput(input2) {
142362
+ return {
142363
+ ...input2,
142364
+ images: input2.images?.map((image) => ({ ...image })),
142365
+ attachments: input2.attachments?.map((attachment) => ({ ...attachment })),
142366
+ branchPath: input2.branchPath?.slice()
142367
+ };
142368
+ }
142369
+
142370
+ // src/core/conversationKernel.ts
142371
+ var import_crypto19 = require("crypto");
141383
142372
  function changedLineCount(value) {
141384
142373
  if (!value) return 0;
141385
142374
  return value.split(/\r?\n/).length;
@@ -141437,25 +142426,168 @@ var ConversationKernel = class {
141437
142426
  return runtimes.map((runtime) => runtime.runtimeKey);
141438
142427
  }
141439
142428
  /** A Flow and its queue share one Agent; no second history writer is created. */
141440
- beginExternalRun(targetInput, options, createOwner, previousQueuePaused) {
142429
+ beginExternalRun(targetInput, options, createOwner, previousQueuePaused, buildInput) {
141441
142430
  const target = this.normalizeTarget(targetInput);
141442
142431
  const existing = this.findRuntime(target);
141443
142432
  if (existing?.activePromise || existing?.externalOwner?.active) throw new Error("Target conversation is already running");
141444
142433
  const runtime = existing || this.runtime(target, options, createOwner());
142434
+ this.reconcilePendingContinuations(runtime);
141445
142435
  runtime.options = { ...options };
141446
142436
  runtime.externalOwner = { active: true, wasPaused: runtime.externalOwner?.wasPaused ?? previousQueuePaused ?? runtime.queuePaused };
141447
142437
  runtime.queuePaused = true;
141448
- runtime.runId ||= (0, import_crypto18.randomUUID)();
142438
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141449
142439
  runtime.stopRequestedRunId = "";
142440
+ if (buildInput) {
142441
+ const continuation = this.continuationStore(runtime);
142442
+ if (continuation) {
142443
+ if (buildInput.existingBuildId) {
142444
+ runtime.externalBuildId = buildInput.existingBuildId;
142445
+ runtime.externalScope = continuation.store.claimExternalBuild({
142446
+ workspaceId: continuation.workspaceId,
142447
+ rootId: continuation.rootId,
142448
+ branchId: continuation.branchId,
142449
+ buildId: buildInput.existingBuildId,
142450
+ workerCapability: "flow-external"
142451
+ });
142452
+ } else if (buildInput.resume && runtime.externalBuildId) {
142453
+ runtime.externalScope = continuation.store.claimExternalBuild({
142454
+ workspaceId: continuation.workspaceId,
142455
+ rootId: continuation.rootId,
142456
+ branchId: continuation.branchId,
142457
+ buildId: runtime.externalBuildId,
142458
+ workerCapability: "flow-external"
142459
+ });
142460
+ } else {
142461
+ const authoritative = continuation.store.snapshot({
142462
+ workspaceId: continuation.workspaceId,
142463
+ rootId: continuation.rootId,
142464
+ branchId: continuation.branchId
142465
+ });
142466
+ const receipt = continuation.store.enqueueBuild({
142467
+ schemaVersion: 1,
142468
+ type: "ENQUEUE_BUILD",
142469
+ commandId: buildInput.commandId || (0, import_crypto19.randomUUID)(),
142470
+ actorId: "flow",
142471
+ target: {
142472
+ workspaceId: continuation.workspaceId,
142473
+ expectedRootId: continuation.rootId,
142474
+ branchId: continuation.branchId
142475
+ },
142476
+ expectedTailBuildId: authoritative.tailBuildId,
142477
+ expectedQueueRevision: authoritative.queueRevision,
142478
+ input: {
142479
+ text: buildInput.text,
142480
+ requestedMode: buildInput.requestedMode || "flow",
142481
+ goalObjective: buildInput.goalObjective,
142482
+ modelSelection: buildInput.modelSelection || runtime.options.model,
142483
+ branchNodeId: buildInput.branchNodeId,
142484
+ branchPath: buildInput.branchPath
142485
+ },
142486
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:flow`,
142487
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
142488
+ });
142489
+ runtime.externalBuildId = receipt.buildId;
142490
+ runtime.externalScope = continuation.store.claimExternalBuild({
142491
+ workspaceId: continuation.workspaceId,
142492
+ rootId: continuation.rootId,
142493
+ branchId: continuation.branchId,
142494
+ buildId: receipt.buildId,
142495
+ workerCapability: "flow-external"
142496
+ });
142497
+ }
142498
+ }
142499
+ }
141450
142500
  this.emitQueueUpdate(runtime);
141451
142501
  return runtime.runner;
141452
142502
  }
142503
+ /**
142504
+ * Admit a Flow build at command-acceptance time. The Flow may wait behind a
142505
+ * running Build, but its queue position (and therefore the parent of every
142506
+ * later Next item) is fixed now, not when the Flow finally starts.
142507
+ */
142508
+ admitExternalBuild(targetInput, buildInput) {
142509
+ const target = this.normalizeTarget(targetInput);
142510
+ const existing = this.findRuntime(target);
142511
+ const runtime = existing || this.runtime(target, {
142512
+ mode: "flow",
142513
+ model: buildInput.modelSelection || this.host.modelSelectionValue(),
142514
+ intelligence: this.host.intelligence,
142515
+ inputMode: this.host.inputMode,
142516
+ engine: this.host.engine
142517
+ }, this.createRunner(target));
142518
+ const continuation = this.continuationStore(runtime);
142519
+ if (!continuation) return null;
142520
+ const authoritative = continuation.store.snapshot({
142521
+ workspaceId: continuation.workspaceId,
142522
+ rootId: continuation.rootId,
142523
+ branchId: continuation.branchId
142524
+ });
142525
+ const receipt = continuation.store.enqueueBuild({
142526
+ schemaVersion: 1,
142527
+ type: "ENQUEUE_BUILD",
142528
+ commandId: buildInput.commandId,
142529
+ actorId: "flow",
142530
+ target: {
142531
+ workspaceId: continuation.workspaceId,
142532
+ expectedRootId: continuation.rootId,
142533
+ branchId: continuation.branchId
142534
+ },
142535
+ expectedTailBuildId: authoritative.tailBuildId,
142536
+ expectedQueueRevision: authoritative.queueRevision,
142537
+ input: {
142538
+ text: buildInput.text,
142539
+ requestedMode: buildInput.requestedMode || "flow",
142540
+ goalObjective: buildInput.goalObjective,
142541
+ modelSelection: buildInput.modelSelection || runtime.options.model,
142542
+ branchNodeId: buildInput.branchNodeId,
142543
+ branchPath: buildInput.branchPath
142544
+ },
142545
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:flow`,
142546
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
142547
+ });
142548
+ return receipt.buildId;
142549
+ }
141453
142550
  settleExternalRun(target, completed) {
141454
142551
  const runtime = this.findRuntime(target);
141455
142552
  if (!runtime?.externalOwner) return;
141456
142553
  const wasPaused = runtime.externalOwner.wasPaused;
141457
142554
  if (completed) runtime.externalOwner = void 0;
141458
142555
  else runtime.externalOwner.active = false;
142556
+ if (runtime.externalBuildId) {
142557
+ const continuation = this.continuationStore(runtime);
142558
+ if (continuation) {
142559
+ if (completed) {
142560
+ if (runtime.externalScope) {
142561
+ continuation.store.commitFinal({
142562
+ scope: runtime.externalScope,
142563
+ text: runtime.externalFinalText || ""
142564
+ });
142565
+ } else {
142566
+ continuation.store.commitExternalBuild({
142567
+ workspaceId: continuation.workspaceId,
142568
+ rootId: continuation.rootId,
142569
+ branchId: continuation.branchId,
142570
+ buildId: runtime.externalBuildId,
142571
+ text: runtime.externalFinalText || ""
142572
+ });
142573
+ }
142574
+ runtime.externalBuildId = void 0;
142575
+ runtime.externalScope = void 0;
142576
+ runtime.externalFinalText = void 0;
142577
+ } else {
142578
+ try {
142579
+ continuation.store.requeueBuild({
142580
+ workspaceId: continuation.workspaceId,
142581
+ rootId: continuation.rootId,
142582
+ branchId: continuation.branchId,
142583
+ buildId: runtime.externalBuildId
142584
+ });
142585
+ } catch {
142586
+ }
142587
+ runtime.externalScope = void 0;
142588
+ }
142589
+ }
142590
+ }
141459
142591
  runtime.queuePaused = completed && !runtime.preparingArchive ? wasPaused : true;
141460
142592
  runtime.runner.saveWorkspaceConversationState(true);
141461
142593
  this.emitQueueUpdate(runtime);
@@ -141465,6 +142597,24 @@ var ConversationKernel = class {
141465
142597
  const runtime = this.findRuntime(target);
141466
142598
  if (!runtime) return;
141467
142599
  if (runtime.externalOwner?.active) throw new Error("Wait for the Flow to stop before releasing its queue");
142600
+ if (runtime.externalBuildId) {
142601
+ const continuation = this.continuationStore(runtime);
142602
+ if (continuation) {
142603
+ try {
142604
+ continuation.store.commitExternalBuild({
142605
+ workspaceId: continuation.workspaceId,
142606
+ rootId: continuation.rootId,
142607
+ branchId: continuation.branchId,
142608
+ buildId: runtime.externalBuildId,
142609
+ text: "Flow exited by the user; the conversation queue resumed."
142610
+ });
142611
+ } catch {
142612
+ }
142613
+ }
142614
+ runtime.externalBuildId = void 0;
142615
+ runtime.externalScope = void 0;
142616
+ runtime.externalFinalText = void 0;
142617
+ }
141468
142618
  runtime.externalOwner = void 0;
141469
142619
  this.setQueuePaused(target, paused);
141470
142620
  }
@@ -141567,20 +142717,59 @@ var ConversationKernel = class {
141567
142717
  if (!id) return [];
141568
142718
  return [{
141569
142719
  id,
142720
+ buildId: item.message.buildId,
141570
142721
  text: String(item.message.visibleUserInput || item.message.text || "").replace(/^\[Next queued while current turn is running\]\n/, ""),
141571
142722
  queueMode: item.queueMode,
141572
142723
  requestedMode: item.message.visibleMode,
141573
142724
  goalObjective: item.message.goalObjective,
141574
142725
  runId: item.message.runId,
141575
142726
  createdAt: String(item.message.createdAt || ""),
141576
- images: item.message.images?.map((image) => ({ ...image }))
142727
+ images: item.message.images?.map((image) => ({ ...image })),
142728
+ branchNodeId: item.message.branchNodeId,
142729
+ branchPath: item.message.branchPath?.slice(),
142730
+ modelSelection: item.message.modelSelection
141577
142731
  }];
141578
142732
  });
141579
142733
  }
142734
+ /**
142735
+ * Capture the exact runtime branch that owns a queued user turn. A queued
142736
+ * Next is a new user turn, but it must still land on the branch the user was
142737
+ * viewing when they enqueued it, not on whatever branch happens to be active
142738
+ * when the previous Build settles.
142739
+ */
142740
+ runtimeBranchIdentity(runtime) {
142741
+ try {
142742
+ const snapshot2 = runtime.runner.getConversationSnapshot(runtime.id);
142743
+ const path32 = Array.isArray(snapshot2.runtimeBranchNodePath) ? snapshot2.runtimeBranchNodePath.map((id) => String(id || "")).filter(Boolean) : [];
142744
+ const branchNodeId = String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || path32[path32.length - 1] || "");
142745
+ return {
142746
+ branchNodeId,
142747
+ branchPath: path32.length ? path32 : branchNodeId ? [branchNodeId] : []
142748
+ };
142749
+ } catch {
142750
+ return { branchNodeId: "", branchPath: [] };
142751
+ }
142752
+ }
142753
+ /**
142754
+ * Map the current conversation/branch model onto the continuation-v1
142755
+ * Root/Branch identity. The ledger is workspace-scoped and shared by the
142756
+ * PC GUI, hosted mobile API and isolated runtimes.
142757
+ */
142758
+ continuationStore(runtime, branchNodeIdOverride = "") {
142759
+ const workspace = runtime.target.workspace;
142760
+ if (!workspace?.path) return null;
142761
+ const workspaceId = String(workspace.id || workspace.path);
142762
+ const branchIdentity = this.runtimeBranchIdentity(runtime);
142763
+ const rootId = runtime.target.conversationId;
142764
+ const branchId = branchNodeIdOverride.includes("::") ? branchNodeIdOverride : `${rootId}::${branchNodeIdOverride || branchIdentity.branchNodeId || "main"}`;
142765
+ const store = new GuardedContinuationStore(workspace.path, workspaceId);
142766
+ store.ensureRoot(rootId, branchId);
142767
+ return { store, workspaceId, rootId, branchId };
142768
+ }
141580
142769
  enqueueNext(target, input2) {
141581
142770
  const runtime = this.findRuntime(target);
141582
142771
  if (!runtime) throw new Error("Target conversation runtime is unavailable");
141583
- runtime.runId ||= (0, import_crypto18.randomUUID)();
142772
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141584
142773
  const id = String(input2.id || "").trim().slice(0, 200);
141585
142774
  const text3 = String(input2.text || "").trim();
141586
142775
  if (!id || !text3) throw new Error("Queue item id and text are required");
@@ -141589,8 +142778,50 @@ var ConversationKernel = class {
141589
142778
  const prompt = `[Next queued while current turn is running]
141590
142779
  ${text3}`;
141591
142780
  const createdAt = String(input2.createdAt || (/* @__PURE__ */ new Date()).toISOString());
142781
+ const capturedBranch = this.runtimeBranchIdentity(runtime);
142782
+ const branchPath = Array.isArray(input2.branchPath) && input2.branchPath.length ? input2.branchPath.map((id2) => String(id2 || "")).filter(Boolean) : capturedBranch.branchPath;
142783
+ const branchNodeId = String(input2.branchNodeId || branchPath[branchPath.length - 1] || capturedBranch.branchNodeId || "");
142784
+ const targetRuntimeKey = String(input2.targetRuntimeKey || runtime.target.runtimeKey).trim() || runtime.target.runtimeKey;
142785
+ const workspaceKey = runtime.target.workspaceKey;
142786
+ const modelSelection = String(input2.modelSelection || runtime.options.model || "").trim() || void 0;
142787
+ const continuation = this.continuationStore(runtime, branchNodeId);
142788
+ const ledgerBranchId = continuation?.branchId;
142789
+ let buildId = "";
142790
+ if (continuation) {
142791
+ const authoritative = continuation.store.snapshot({
142792
+ workspaceId: continuation.workspaceId,
142793
+ rootId: continuation.rootId,
142794
+ branchId: continuation.branchId
142795
+ });
142796
+ const receipt = continuation.store.enqueueBuild({
142797
+ schemaVersion: 1,
142798
+ type: "ENQUEUE_BUILD",
142799
+ commandId: id,
142800
+ actorId: "kernel",
142801
+ target: {
142802
+ workspaceId: continuation.workspaceId,
142803
+ expectedRootId: continuation.rootId,
142804
+ branchId: continuation.branchId
142805
+ },
142806
+ expectedTailBuildId: authoritative.tailBuildId,
142807
+ expectedQueueRevision: authoritative.queueRevision,
142808
+ input: {
142809
+ text: text3,
142810
+ images: input2.images,
142811
+ requestedMode: input2.requestedMode,
142812
+ goalObjective: input2.goalObjective,
142813
+ modelSelection,
142814
+ branchNodeId: branchNodeId || void 0,
142815
+ branchPath: branchPath.length ? branchPath : void 0
142816
+ },
142817
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:${modelSelection || "auto"}`,
142818
+ createdAt
142819
+ });
142820
+ buildId = receipt.buildId;
142821
+ }
141592
142822
  runtime.pendingNextTurn.push({
141593
142823
  message: {
142824
+ buildId: buildId || void 0,
141594
142825
  text: prompt,
141595
142826
  visibleUserInput: text3,
141596
142827
  visibleMode: String(input2.requestedMode || "build"),
@@ -141598,11 +142829,18 @@ ${text3}`;
141598
142829
  images: Array.isArray(input2.images) ? input2.images.slice(0, 6).map((image) => ({ ...image })) : void 0,
141599
142830
  clientMessageId: id,
141600
142831
  runId: runtime.runId,
142832
+ branchNodeId: branchNodeId || void 0,
142833
+ branchPath: branchPath.length ? branchPath : void 0,
142834
+ ledgerBranchId,
142835
+ targetRuntimeKey,
142836
+ workspaceKey,
142837
+ modelSelection,
141601
142838
  createdAt
141602
142839
  },
141603
142840
  queueMode: "followUp"
141604
142841
  });
141605
142842
  runtime.runner.retainConversationContinuations([{
142843
+ buildId: buildId || void 0,
141606
142844
  content: prompt,
141607
142845
  queueMode: "followUp",
141608
142846
  clientMessageId: id,
@@ -141611,7 +142849,13 @@ ${text3}`;
141611
142849
  images: input2.images,
141612
142850
  visibleUserInput: text3,
141613
142851
  visibleMode: String(input2.requestedMode || "build"),
141614
- goalObjective: input2.goalObjective
142852
+ goalObjective: input2.goalObjective,
142853
+ branchNodeId: branchNodeId || void 0,
142854
+ branchPath: branchPath.length ? branchPath : void 0,
142855
+ ledgerBranchId,
142856
+ targetRuntimeKey,
142857
+ workspaceKey,
142858
+ modelSelection
141615
142859
  }]);
141616
142860
  this.trackQueuedMessage(runtime, prompt, "followUp");
141617
142861
  this.emitQueueUpdate(runtime);
@@ -141627,12 +142871,34 @@ ${text3}`;
141627
142871
  const pending3 = runtime.pendingNextTurn.find((item) => typeof item.message !== "string" && item.message.clientMessageId === id);
141628
142872
  if (!pending3 || typeof pending3.message === "string") throw new Error("Queue item is no longer editable");
141629
142873
  const previous = runtime.runner.conversationContinuations().find((item) => item.clientMessageId === id);
141630
- pending3.message.text = `[Next queued while current turn is running]
142874
+ const nextText = `[Next queued while current turn is running]
141631
142875
  ${text3}`;
142876
+ const nextVisibleMode = input2.requestedMode !== void 0 ? input2.requestedMode : pending3.message.visibleMode;
142877
+ const nextGoalObjective = input2.goalObjective !== void 0 ? input2.goalObjective : pending3.message.goalObjective;
142878
+ const nextImages = input2.images !== void 0 ? input2.images.map((image) => ({ ...image })) : pending3.message.images?.map((image) => ({ ...image }));
142879
+ const continuation = this.continuationStore(runtime, pending3.message.ledgerBranchId || pending3.message.branchNodeId);
142880
+ if (continuation && pending3.message.buildId) {
142881
+ continuation.store.updateQueuedBuild({
142882
+ workspaceId: continuation.workspaceId,
142883
+ rootId: continuation.rootId,
142884
+ branchId: continuation.branchId,
142885
+ buildId: pending3.message.buildId,
142886
+ input: {
142887
+ text: text3,
142888
+ images: nextImages,
142889
+ requestedMode: nextVisibleMode,
142890
+ goalObjective: nextGoalObjective,
142891
+ modelSelection: pending3.message.modelSelection,
142892
+ branchNodeId: pending3.message.branchNodeId,
142893
+ branchPath: pending3.message.branchPath
142894
+ }
142895
+ });
142896
+ }
142897
+ pending3.message.text = nextText;
141632
142898
  pending3.message.visibleUserInput = text3;
141633
- if (input2.requestedMode !== void 0) pending3.message.visibleMode = input2.requestedMode;
141634
- if (input2.goalObjective !== void 0) pending3.message.goalObjective = input2.goalObjective;
141635
- if (input2.images !== void 0) pending3.message.images = input2.images.map((image) => ({ ...image }));
142899
+ pending3.message.visibleMode = nextVisibleMode;
142900
+ pending3.message.goalObjective = nextGoalObjective;
142901
+ pending3.message.images = nextImages;
141636
142902
  runtime.runner.retainConversationContinuations([{
141637
142903
  ...previous,
141638
142904
  content: pending3.message.text,
@@ -141642,7 +142908,12 @@ ${text3}`;
141642
142908
  images: pending3.message.images,
141643
142909
  visibleUserInput: text3,
141644
142910
  visibleMode: pending3.message.visibleMode,
141645
- goalObjective: pending3.message.goalObjective
142911
+ goalObjective: pending3.message.goalObjective,
142912
+ branchNodeId: pending3.message.branchNodeId,
142913
+ branchPath: pending3.message.branchPath,
142914
+ targetRuntimeKey: pending3.message.targetRuntimeKey,
142915
+ workspaceKey: pending3.message.workspaceKey,
142916
+ modelSelection: pending3.message.modelSelection
141646
142917
  }]);
141647
142918
  this.emitQueueUpdate(runtime);
141648
142919
  return this.queueItems(runtime.target).find((item) => item.id === id);
@@ -141653,7 +142924,19 @@ ${text3}`;
141653
142924
  const id = String(idInput || "").trim();
141654
142925
  const index2 = runtime.pendingNextTurn.findIndex((item) => typeof item.message !== "string" && item.message.clientMessageId === id);
141655
142926
  if (index2 < 0) return false;
141656
- const [removed] = runtime.pendingNextTurn.splice(index2, 1);
142927
+ const removed = runtime.pendingNextTurn[index2];
142928
+ if (typeof removed.message !== "string") {
142929
+ const continuation = this.continuationStore(runtime, removed.message.ledgerBranchId || removed.message.branchNodeId);
142930
+ if (continuation && removed.message.buildId) {
142931
+ continuation.store.deleteQueuedBuild({
142932
+ workspaceId: continuation.workspaceId,
142933
+ rootId: continuation.rootId,
142934
+ branchId: continuation.branchId,
142935
+ buildId: removed.message.buildId
142936
+ });
142937
+ }
142938
+ }
142939
+ runtime.pendingNextTurn.splice(index2, 1);
141657
142940
  if (typeof removed.message !== "string") {
141658
142941
  runtime.runner.consumeConversationContinuation({ content: removed.message.text, queueMode: removed.queueMode, clientMessageId: id });
141659
142942
  }
@@ -141676,6 +142959,26 @@ ${text3}`;
141676
142959
  if (item.queueMode !== "followUp" || typeof item.message === "string" || !item.message.clientMessageId) return [];
141677
142960
  return [[String(item.message.clientMessageId), item]];
141678
142961
  }));
142962
+ const firstOrdered = pendingById.get(orderedIds[0] || "");
142963
+ const continuation = this.continuationStore(
142964
+ runtime,
142965
+ firstOrdered && typeof firstOrdered.message !== "string" ? firstOrdered.message.ledgerBranchId || firstOrdered.message.branchNodeId || "" : ""
142966
+ );
142967
+ if (continuation) {
142968
+ const orderedBuildIds = orderedIds.map((id) => {
142969
+ const item = pendingById.get(id);
142970
+ return item && typeof item.message !== "string" ? item.message.buildId : void 0;
142971
+ }).filter((id) => !!id);
142972
+ if (orderedBuildIds.length !== orderedIds.length) {
142973
+ throw new Error("A queued build id is missing from the authoritative ledger projection");
142974
+ }
142975
+ continuation.store.reorderQueuedBuilds({
142976
+ workspaceId: continuation.workspaceId,
142977
+ rootId: continuation.rootId,
142978
+ branchId: continuation.branchId,
142979
+ orderedBuildIds
142980
+ });
142981
+ }
141679
142982
  const reorderedPending = orderedIds.map((id) => pendingById.get(id));
141680
142983
  let nextIndex = 0;
141681
142984
  runtime.pendingNextTurn = runtime.pendingNextTurn.map((item) => {
@@ -141707,7 +143010,7 @@ ${text3}`;
141707
143010
  inputMode: this.host.inputMode,
141708
143011
  engine: this.host.engine
141709
143012
  });
141710
- runtime.runId ||= (0, import_crypto18.randomUUID)();
143013
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141711
143014
  let receipt;
141712
143015
  if (action === "enqueue") {
141713
143016
  this.enqueueNext(runtime.target, {
@@ -141716,7 +143019,11 @@ ${text3}`;
141716
143019
  requestedMode: input2.requestedMode,
141717
143020
  goalObjective: input2.goalObjective,
141718
143021
  createdAt: input2.createdAt,
141719
- images: input2.images
143022
+ images: input2.images,
143023
+ branchNodeId: input2.branchNodeId,
143024
+ branchPath: input2.branchPath,
143025
+ modelSelection: input2.modelSelection,
143026
+ targetRuntimeKey: input2.targetRuntimeKey
141720
143027
  });
141721
143028
  } else if (action === "update") {
141722
143029
  this.updateQueueItem(runtime.target, String(input2.id || ""), String(input2.text || ""), input2);
@@ -141734,7 +143041,7 @@ ${text3}`;
141734
143041
  if (!item) throw new Error("Queue item was not found");
141735
143042
  receipt = this.enqueueGuide({
141736
143043
  clientMessageId: item.id,
141737
- guideId: (0, import_crypto18.randomUUID)(),
143044
+ guideId: (0, import_crypto19.randomUUID)(),
141738
143045
  target: runtime.target,
141739
143046
  runId: runtime.runId,
141740
143047
  deliveryMode: "steer",
@@ -141786,7 +143093,7 @@ ${item.goalObjective}` : item.text,
141786
143093
  if (!runtime && runner.conversationContinuations().length) {
141787
143094
  runtime = this.runtime(normalized, { mode: runner.mode, model: runner.modelSelectionValue(), intelligence: runner.intelligence, inputMode: runner.inputMode, engine: runner.engine }, runner);
141788
143095
  runtime.queuePaused = true;
141789
- runtime.runId ||= (0, import_crypto18.randomUUID)();
143096
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141790
143097
  }
141791
143098
  const conversationSnapshot = runner.getConversationSnapshot(normalized.conversationId, options);
141792
143099
  return {
@@ -142212,7 +143519,7 @@ ${item.goalObjective}` : item.text,
142212
143519
  const active = this.findRuntime(normalized);
142213
143520
  if (active?.preparingArchive) throw new Error("This conversation is being archived");
142214
143521
  if (active?.activePromise) {
142215
- this.enqueueSameSession(active, message, queueMode);
143522
+ this.enqueueSameSession(active, message, queueMode, options.model);
142216
143523
  this.activateAcceptedGoal(active, typeof message === "string" ? "" : message.goalObjective);
142217
143524
  return active.activePromise;
142218
143525
  }
@@ -142222,7 +143529,7 @@ ${item.goalObjective}` : item.text,
142222
143529
  runtime.generation = (this.generations.get(runtime.runtimeKey) || runtime.generation || 0) + 1;
142223
143530
  this.generations.set(runtime.runtimeKey, runtime.generation);
142224
143531
  const requestedRunId = typeof message === "string" ? "" : String(message.runId || "").trim().slice(0, 200);
142225
- runtime.runId = requestedRunId || (0, import_crypto18.randomUUID)();
143532
+ runtime.runId = requestedRunId || (0, import_crypto19.randomUUID)();
142226
143533
  runtime.stopRequestedRunId = "";
142227
143534
  runtime.forceStopArmedRunId = "";
142228
143535
  runtime.stopCheckpointed = false;
@@ -142322,10 +143629,12 @@ ${item.goalObjective}` : item.text,
142322
143629
  return this.result(runtime, lastTokens);
142323
143630
  }
142324
143631
  for (; ; ) {
142325
- while (!runtime.queuePaused && runtime.pendingNextTurn.length > 0) {
143632
+ while (!runtime.queuePaused) {
142326
143633
  if (runtime.stopRequestedRunId === runtime.runId) return this.result(runtime, lastTokens);
142327
- const next2 = runtime.pendingNextTurn.shift();
142328
- if (next2.queueMode === "steer" && typeof next2.message !== "string" && !!next2.message.clientMessageId) {
143634
+ const steerIndex = runtime.pendingNextTurn.findIndex((item) => item.queueMode === "steer");
143635
+ if (steerIndex < 0) break;
143636
+ const next2 = runtime.pendingNextTurn.splice(steerIndex, 1)[0];
143637
+ if (typeof next2.message !== "string" && !!next2.message.clientMessageId) {
142329
143638
  const batchGuides = [];
142330
143639
  const pushGuide = (message2) => {
142331
143640
  batchGuides.push({
@@ -142337,8 +143646,10 @@ ${item.goalObjective}` : item.text,
142337
143646
  });
142338
143647
  };
142339
143648
  pushGuide(next2.message);
142340
- while (runtime.pendingNextTurn.length > 0 && runtime.pendingNextTurn[0].queueMode === "steer" && typeof runtime.pendingNextTurn[0].message !== "string" && !!runtime.pendingNextTurn[0].message.clientMessageId) {
142341
- const guide = runtime.pendingNextTurn.shift();
143649
+ while (true) {
143650
+ const guideIndex = runtime.pendingNextTurn.findIndex((item) => item.queueMode === "steer" && typeof item.message !== "string" && !!item.message.clientMessageId);
143651
+ if (guideIndex < 0) break;
143652
+ const guide = runtime.pendingNextTurn.splice(guideIndex, 1)[0];
142342
143653
  pushGuide(guide.message);
142343
143654
  }
142344
143655
  if (batchGuides.length === 1) {
@@ -142356,21 +143667,9 @@ ${batchText}`,
142356
143667
  lastTokens = await this.runSingle(runtime, batchMessage, "steer");
142357
143668
  if (this.repeatedAutomaticAssistant(runtime, batchMessage, "steer")) break;
142358
143669
  } else {
142359
- const drained = this.drainQueuedFollowUpMessage(next2.message);
142360
- lastTokens = await this.runPendingQueueItem(runtime, next2, async () => {
142361
- if (typeof drained !== "string" && drained.visibleMode && ["build", "chat", "plan", "goal"].includes(drained.visibleMode)) {
142362
- runtime.runner.setMode(drained.visibleMode);
142363
- runtime.options.mode = drained.visibleMode;
142364
- }
142365
- this.activateAcceptedGoal(runtime, typeof drained === "string" ? "" : drained.goalObjective);
142366
- return this.runSingle(
142367
- runtime,
142368
- drained,
142369
- next2.queueMode,
142370
- typeof next2.message === "string" ? void 0 : next2.message.clientMessageId
142371
- );
142372
- });
142373
- if (this.repeatedAutomaticAssistant(runtime, drained, next2.queueMode)) break;
143670
+ lastTokens = await this.runSingle(runtime, next2.message, next2.queueMode);
143671
+ if (this.repeatedAutomaticAssistant(runtime, next2.message, next2.queueMode)) break;
143672
+ continue;
142374
143673
  }
142375
143674
  }
142376
143675
  const rootMessage = runtime.runner.subagents.readRootInbox()[0];
@@ -142383,8 +143682,8 @@ ${batchText}`,
142383
143682
  if (!runtime.pendingNextTurn.length) this.clearQueued(runtime);
142384
143683
  const completedRunId = runtime.runId;
142385
143684
  runtime.runner.finishConversationWorkRun(completedRunId, "completed");
142386
- await new Promise((resolve15) => setImmediate(resolve15));
142387
- if (runtime.runId === completedRunId && runtime.stopRequestedRunId !== completedRunId && !runtime.queuePaused && runtime.pendingNextTurn.length > 0) {
143685
+ await new Promise((resolve16) => setImmediate(resolve16));
143686
+ if (runtime.runId === completedRunId && runtime.stopRequestedRunId !== completedRunId && !runtime.queuePaused && runtime.pendingNextTurn.some((item) => item.queueMode === "steer")) {
142388
143687
  runtime.guideAcceptanceClosedRunId = "";
142389
143688
  if (!runtime.runner.resumeConversationWorkRun(completedRunId)) {
142390
143689
  throw new Error(`Unable to resume deferred Guide work run ${completedRunId}`);
@@ -142555,6 +143854,12 @@ Review this persisted peer result and summarize or continue the parent task as n
142555
143854
  visibleUserInput: continuation.visibleUserInput,
142556
143855
  visibleMode: continuation.visibleMode,
142557
143856
  goalObjective: continuation.goalObjective,
143857
+ buildId: continuation.buildId,
143858
+ modelSelection: continuation.modelSelection,
143859
+ branchNodeId: continuation.branchNodeId,
143860
+ branchPath: continuation.branchPath?.slice(),
143861
+ targetRuntimeKey: continuation.targetRuntimeKey,
143862
+ workspaceKey: continuation.workspaceKey,
142558
143863
  createdAt: continuation.createdAt,
142559
143864
  hiddenUserInput: continuation.hiddenUserInput
142560
143865
  } : continuation.content,
@@ -142641,10 +143946,90 @@ Review this persisted peer result and summarize or continue the parent task as n
142641
143946
  setImmediate(() => {
142642
143947
  runtime.pendingContinuationRunId = void 0;
142643
143948
  if (runtime.preparingArchive || runtime.runId !== runId || runtime.activePromise || runtime.externalOwner || runtime.stopRequestedRunId === runId || runtime.queuePaused) return;
142644
- const next2 = runtime.pendingNextTurn.shift();
143949
+ const next2 = runtime.pendingNextTurn[0];
142645
143950
  if (!next2) return;
142646
- const delivery = next2.queueMode === "followUp" ? this.drainQueuedFollowUpMessage(next2.message) : next2.message;
142647
- const message = typeof delivery === "string" ? { text: delivery, runId } : { ...delivery, runId: delivery.runId || runId };
143951
+ const queued = typeof next2.message === "string" ? null : next2.message;
143952
+ if (queued?.targetRuntimeKey && queued.targetRuntimeKey !== runtime.target.runtimeKey) {
143953
+ runtime.queuePaused = true;
143954
+ runtime.runner.recordWorkStatus("Queued turn target mismatch; the queue is paused instead of running in another conversation.");
143955
+ this.emitQueueUpdate(runtime);
143956
+ return;
143957
+ }
143958
+ runtime.pendingNextTurn.shift();
143959
+ if (next2.queueMode === "followUp") {
143960
+ const delivery = this.drainQueuedFollowUpMessage(next2.message);
143961
+ const message2 = typeof delivery === "string" ? { text: delivery } : { ...delivery, runId: void 0 };
143962
+ const continuation = this.continuationStore(runtime);
143963
+ let scope = null;
143964
+ void this.runPendingQueueItem(runtime, next2, async () => {
143965
+ this.bindQueuedTurnBranch(runtime, queued);
143966
+ if (queued?.modelSelection) runtime.options.model = queued.modelSelection;
143967
+ if (message2.visibleMode && ["build", "chat", "plan", "goal"].includes(message2.visibleMode)) {
143968
+ this.setMode(runtime.target, message2.visibleMode);
143969
+ }
143970
+ this.activateAcceptedGoal(runtime, message2.goalObjective || "");
143971
+ if (continuation && queued?.buildId) {
143972
+ const authoritative = continuation.store.snapshot({
143973
+ workspaceId: continuation.workspaceId,
143974
+ rootId: continuation.rootId,
143975
+ branchId: continuation.branchId
143976
+ });
143977
+ const ready = authoritative.builds.filter((build2) => build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence)[0];
143978
+ if (ready && ready.buildId !== queued.buildId) {
143979
+ runtime.pendingNextTurn.unshift(next2);
143980
+ runtime.runner.recordWorkStatus("Queued turn is waiting for the authoritative predecessor.");
143981
+ this.emitQueueUpdate(runtime);
143982
+ return this.result(runtime, []);
143983
+ }
143984
+ scope = continuation.store.claimBuild({
143985
+ workspaceId: continuation.workspaceId,
143986
+ rootId: continuation.rootId,
143987
+ branchId: continuation.branchId,
143988
+ workerCapability: `kernel:${process.pid}`
143989
+ });
143990
+ if (scope && scope.buildId !== queued.buildId) {
143991
+ continuation.store.failBuild({ scope, reason: "Authoritative build mismatch during claim" });
143992
+ scope = null;
143993
+ }
143994
+ if (!scope) {
143995
+ runtime.pendingNextTurn.unshift(next2);
143996
+ runtime.runner.recordWorkStatus("Queued turn is not ready for execution yet.");
143997
+ this.emitQueueUpdate(runtime);
143998
+ return this.result(runtime, []);
143999
+ }
144000
+ }
144001
+ const result = await this.prompt(message2, runtime.target, runtime.options, "followUp");
144002
+ if (continuation && scope) {
144003
+ continuation.store.commitFinal({
144004
+ scope,
144005
+ text: result.tokens.map((token) => token.text || "").join("")
144006
+ });
144007
+ }
144008
+ return result;
144009
+ }, (accepted, error2) => {
144010
+ if (!continuation || !scope) return;
144011
+ const reason = error2 instanceof Error ? error2.message : String(error2);
144012
+ if (accepted) {
144013
+ try {
144014
+ continuation.store.failBuild({ scope, reason });
144015
+ } catch {
144016
+ }
144017
+ } else {
144018
+ try {
144019
+ continuation.store.requeueBuild({
144020
+ workspaceId: continuation.workspaceId,
144021
+ rootId: continuation.rootId,
144022
+ branchId: continuation.branchId,
144023
+ buildId: scope.buildId
144024
+ });
144025
+ } catch {
144026
+ }
144027
+ }
144028
+ }).catch(() => {
144029
+ });
144030
+ return;
144031
+ }
144032
+ const message = typeof next2.message === "string" ? { text: next2.message, runId } : { ...next2.message, runId: next2.message.runId || runId };
142648
144033
  void this.runPendingQueueItem(runtime, next2, async () => {
142649
144034
  if (message.visibleMode && ["build", "chat", "plan", "goal"].includes(message.visibleMode)) {
142650
144035
  this.setMode(runtime.target, message.visibleMode);
@@ -142654,7 +144039,24 @@ Review this persisted peer result and summarize or continue the parent task as n
142654
144039
  });
142655
144040
  });
142656
144041
  }
142657
- async runPendingQueueItem(runtime, next2, execute) {
144042
+ /**
144043
+ * Restore the runtime branch captured by a queued user turn. If the branch
144044
+ * disappeared (manual deletion/rewind), fail the queued item into the
144045
+ * existing pause/retry path instead of appending it to a different branch.
144046
+ */
144047
+ bindQueuedTurnBranch(runtime, message) {
144048
+ const branchNodeId = String(message?.branchNodeId || "").trim();
144049
+ if (!branchNodeId) return;
144050
+ const snapshot2 = runtime.runner.getConversationSnapshot(runtime.id);
144051
+ const currentBranch = String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || "");
144052
+ if (currentBranch === branchNodeId) return;
144053
+ try {
144054
+ runtime.runner.switchConversationBranch(runtime.id, branchNodeId);
144055
+ } catch (error2) {
144056
+ throw new Error(`Queued turn branch ${branchNodeId} is unavailable: ${error2 instanceof Error ? error2.message : String(error2)}`);
144057
+ }
144058
+ }
144059
+ async runPendingQueueItem(runtime, next2, execute, onFailure) {
142658
144060
  const queuedMessage = typeof next2.message === "string" ? void 0 : next2.message;
142659
144061
  const id = queuedMessage?.clientMessageId;
142660
144062
  if (next2.queueMode !== "followUp" || !id) return execute();
@@ -142666,6 +144068,10 @@ Review this persisted peer result and summarize or continue the parent task as n
142666
144068
  return await execute();
142667
144069
  } catch (error2) {
142668
144070
  runtime.queuePaused = true;
144071
+ try {
144072
+ onFailure?.(accepted, error2);
144073
+ } catch {
144074
+ }
142669
144075
  throw error2;
142670
144076
  } finally {
142671
144077
  unsubscribe();
@@ -142824,14 +144230,27 @@ Review this persisted peer result and summarize or continue the parent task as n
142824
144230
  guides: (run.guides || []).map(bindGuide)
142825
144231
  }));
142826
144232
  }
142827
- enqueueSameSession(runtime, message, queueMode) {
144233
+ enqueueSameSession(runtime, message, queueMode, requestedModel = "") {
142828
144234
  const isSteer = queueMode === "steer";
142829
144235
  const text3 = typeof message === "string" ? message : message.text;
142830
144236
  const prompt = isSteer ? text3 : `[Next queued while current turn is running]
142831
144237
  ${text3}`;
142832
144238
  if (!isSteer) {
142833
144239
  const structured = typeof message === "string" ? null : message;
142834
- const clientMessageId = String(structured?.clientMessageId || (0, import_crypto18.randomUUID)());
144240
+ const requestedRuntimeKey = String(structured?.targetRuntimeKey || "").trim();
144241
+ if (requestedRuntimeKey && requestedRuntimeKey !== runtime.target.runtimeKey) {
144242
+ throw new Error(`Queued message target mismatch: expected ${requestedRuntimeKey}, received ${runtime.target.runtimeKey}`);
144243
+ }
144244
+ const clientMessageId = String(structured?.clientMessageId || (0, import_crypto19.randomUUID)());
144245
+ const capturedBranch = this.runtimeBranchIdentity(runtime);
144246
+ const branchPath = Array.isArray(structured?.branchPath) && structured.branchPath.length ? structured.branchPath.map((id) => String(id || "")).filter(Boolean) : capturedBranch.branchPath;
144247
+ const branchNodeId = String(structured?.branchNodeId || branchPath[branchPath.length - 1] || capturedBranch.branchNodeId || "");
144248
+ const targetRuntimeKey = runtime.target.runtimeKey;
144249
+ const workspaceKey = runtime.target.workspaceKey;
144250
+ const modelSelection = String(
144251
+ structured?.modelSelection || requestedModel || runtime.options.model || ""
144252
+ ).trim() || void 0;
144253
+ const ledgerBranchId = this.continuationStore(runtime, branchNodeId)?.branchId;
142835
144254
  const queuedMessage = {
142836
144255
  ...structured || {},
142837
144256
  text: prompt,
@@ -142839,6 +144258,12 @@ ${text3}`;
142839
144258
  visibleMode: structured?.visibleMode || runtime.options.mode,
142840
144259
  clientMessageId,
142841
144260
  runId: structured?.runId || runtime.runId,
144261
+ branchNodeId: branchNodeId || void 0,
144262
+ branchPath: branchPath.length ? branchPath : void 0,
144263
+ ledgerBranchId,
144264
+ targetRuntimeKey,
144265
+ workspaceKey,
144266
+ modelSelection,
142842
144267
  createdAt: String(structured?.createdAt || (/* @__PURE__ */ new Date()).toISOString())
142843
144268
  };
142844
144269
  if (!runtime.pendingNextTurn.some((item) => typeof item.message !== "string" && item.message.clientMessageId === clientMessageId)) {
@@ -142854,7 +144279,13 @@ ${text3}`;
142854
144279
  createdAt: queuedMessage.createdAt,
142855
144280
  visibleUserInput: queuedMessage.visibleUserInput,
142856
144281
  visibleMode: queuedMessage.visibleMode,
142857
- goalObjective: queuedMessage.goalObjective
144282
+ goalObjective: queuedMessage.goalObjective,
144283
+ branchNodeId: queuedMessage.branchNodeId,
144284
+ branchPath: queuedMessage.branchPath,
144285
+ ledgerBranchId: queuedMessage.ledgerBranchId,
144286
+ targetRuntimeKey,
144287
+ workspaceKey,
144288
+ modelSelection
142858
144289
  }]);
142859
144290
  this.trackQueuedMessage(runtime, prompt, "followUp");
142860
144291
  runtime.runner.recordWorkStatus(runtime.stopRequestedRunId === runtime.runId ? "Next message retained while stopping." : "Next message queued.");
@@ -142932,6 +144363,52 @@ ${text3}`;
142932
144363
  runtime.queued.followUp = runtime.pendingNextTurn.filter((item) => item.queueMode === "followUp" && (typeof item.message === "string" || item.message.hiddenUserInput !== true || !!item.message.clientMessageId)).map((item) => typeof item.message === "string" ? item.message : item.message.text);
142933
144364
  return runtime;
142934
144365
  }
144366
+ /**
144367
+ * Merge queue continuations persisted by another owner/kernel into this
144368
+ * runtime's in-memory projection. Flow takeover, cold restore and a pool
144369
+ * hand-off must not lose an already-admitted Next row. Deduplication is by
144370
+ * the stable clientMessageId, never by text.
144371
+ */
144372
+ reconcilePendingContinuations(runtime) {
144373
+ runtime.runner.setConversationFromStorage(runtime.id);
144374
+ const persisted = runtime.runner.conversationContinuations();
144375
+ const existingIds = /* @__PURE__ */ new Set();
144376
+ for (const item of runtime.pendingNextTurn) {
144377
+ if (typeof item.message === "string") continue;
144378
+ const id = String(item.message.clientMessageId || "").trim();
144379
+ if (id) existingIds.add(id);
144380
+ }
144381
+ let changed = false;
144382
+ for (const continuation of persisted) {
144383
+ if (continuation.queueMode !== "followUp" || !continuation.clientMessageId) continue;
144384
+ if (existingIds.has(continuation.clientMessageId)) continue;
144385
+ runtime.pendingNextTurn.push({
144386
+ message: {
144387
+ text: continuation.content,
144388
+ visibleUserInput: continuation.visibleUserInput,
144389
+ visibleMode: continuation.visibleMode,
144390
+ goalObjective: continuation.goalObjective,
144391
+ images: continuation.images?.map((image) => ({ ...image })),
144392
+ attachments: continuation.attachments?.map((attachment) => ({ ...attachment })),
144393
+ clientMessageId: continuation.clientMessageId,
144394
+ buildId: continuation.buildId,
144395
+ branchNodeId: continuation.branchNodeId,
144396
+ branchPath: continuation.branchPath?.slice(),
144397
+ targetRuntimeKey: continuation.targetRuntimeKey,
144398
+ workspaceKey: continuation.workspaceKey,
144399
+ modelSelection: continuation.modelSelection,
144400
+ createdAt: continuation.createdAt
144401
+ },
144402
+ queueMode: "followUp"
144403
+ });
144404
+ existingIds.add(continuation.clientMessageId);
144405
+ changed = true;
144406
+ }
144407
+ if (changed) {
144408
+ this.queueState(runtime);
144409
+ this.emitQueueUpdate(runtime);
144410
+ }
144411
+ }
142935
144412
  normalizeTarget(input2) {
142936
144413
  if (typeof input2 !== "string") {
142937
144414
  const withWorkspace = input2.workspace ? input2 : { ...input2, workspace: this.workspaceForId(input2.workspaceId) };
@@ -143164,14 +144641,14 @@ function write(value) {
143164
144641
  configureWslHostToolWriter(write);
143165
144642
  function runtimeIdentity() {
143166
144643
  const pid = process.pid;
143167
- const stat = fs28.readFileSync(`/proc/${pid}/stat`, "utf8");
144644
+ const stat = fs29.readFileSync(`/proc/${pid}/stat`, "utf8");
143168
144645
  const commandEnd = stat.lastIndexOf(")");
143169
144646
  if (commandEnd < 0) throw new Error(`Unable to read WSL runtime identity for pid ${pid}`);
143170
144647
  const fields2 = stat.slice(commandEnd + 2).trim().split(/\s+/);
143171
144648
  const pgid = Number(fields2[2] || 0);
143172
144649
  const sessionId = Number(fields2[3] || 0);
143173
144650
  const startTimeTicks = String(fields2[19] || "");
143174
- const bootId = fs28.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim().toLowerCase();
144651
+ const bootId = fs29.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim().toLowerCase();
143175
144652
  if (![pid, pgid, sessionId].every((value) => Number.isSafeInteger(value) && value > 1) || !/^\d+$/.test(startTimeTicks) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(bootId)) {
143176
144653
  throw new Error(`Invalid WSL runtime identity: pid=${pid} pgid=${pgid} session=${sessionId}`);
143177
144654
  }