newmark-agent 0.6.2 → 0.6.4

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 fs28 = require("fs");
43511
+ var fs29 = require("fs");
43512
43512
  var fetch3 = global.fetch || require_lib4();
43513
43513
  var isURL = require_is_url();
43514
- var readFile2 = util.promisify(fs28.readFile);
43514
+ var readFile2 = util.promisify(fs29.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 input = path31;
47125
+ function removeDotSegments(path32) {
47126
+ let input = 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, fs28, exportName) {
50798
+ function addFormats(ajv, list, fs29, 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, fs28[f]);
50803
+ ajv.addFormat(f, fs29[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 fs28 = require("fs");
50817
- function checkPathExt(path31, options) {
50816
+ var fs29 = 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
- fs28.stat(path31, function(er, stat) {
50842
- cb(er, er ? false : checkStat(stat, path31, options));
50840
+ function isexe(path32, options, cb) {
50841
+ fs29.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(fs28.statSync(path31), path31, options);
50845
+ function sync(path32, options) {
50846
+ return checkStat(fs29.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 fs28 = require("fs");
50857
- function isexe(path31, options, cb) {
50858
- fs28.stat(path31, function(er, stat) {
50856
+ var fs29 = require("fs");
50857
+ function isexe(path32, options, cb) {
50858
+ fs29.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(fs28.statSync(path31), options);
50862
+ function sync(path32, options) {
50863
+ return checkStat(fs29.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 fs28 = require("fs");
50887
+ var fs29 = 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 fs28 = require("fs");
51151
+ var fs29 = 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 = fs28.openSync(command, "r");
51159
- fs28.readSync(fd, buffer, 0, size, 0);
51160
- fs28.closeSync(fd);
51158
+ fd = fs29.openSync(command, "r");
51159
+ fs29.readSync(fd, buffer, 0, size, 0);
51160
+ fs29.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 fs28 = R((Wt) => {
52191
+ var fs29 = 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 = fs28(), 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 = 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) => {
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 fs28 = process.getBuiltinModule("fs");
55012
- const data2 = await fs28.promises.readFile(url2);
55011
+ const fs29 = process.getBuiltinModule("fs");
55012
+ const data2 = await fs29.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 fs28 = process.getBuiltinModule("fs");
70996
- fs28.promises.lstat(this._url).then((stat) => {
70995
+ const fs29 = process.getBuiltinModule("fs");
70996
+ fs29.promises.lstat(this._url).then((stat) => {
70997
70997
  this._contentLength = stat.size;
70998
- this._setReadableStream(fs28.createReadStream(this._url));
70998
+ this._setReadableStream(fs29.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 fs28 = process.getBuiltinModule("fs");
71094
- this._setReadableStream(fs28.createReadStream(this._url, {
71093
+ const fs29 = process.getBuiltinModule("fs");
71094
+ this._setReadableStream(fs29.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
  input.type = "file";
81559
81559
  input.accept = SupportedImageMimeTypes.join(",");
81560
81560
  const signal = this._uiManager._signal;
81561
- this.#bitmapPromise = new Promise((resolve15) => {
81561
+ this.#bitmapPromise = new Promise((resolve16) => {
81562
81562
  input.addEventListener("change", async () => {
81563
81563
  if (!input.files || input.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
  input.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();
@@ -86122,9 +86122,11 @@ var ChatCompletionsAdapter = class {
86122
86122
  const body = {
86123
86123
  model: request.model,
86124
86124
  messages,
86125
- temperature: request.temperature,
86126
- max_tokens: request.maxOutputTokens
86125
+ temperature: request.temperature
86127
86126
  };
86127
+ if (Number.isFinite(request.maxOutputTokens) && request.maxOutputTokens > 0) {
86128
+ body.max_tokens = request.maxOutputTokens;
86129
+ }
86128
86130
  if (tools.length) {
86129
86131
  body.tools = tools;
86130
86132
  body.tool_choice = "auto";
@@ -86432,9 +86434,11 @@ var ResponsesAdapter = class {
86432
86434
  const body = {
86433
86435
  model: request.model,
86434
86436
  input: input.length ? input : [{ role: "user", content: "" }],
86435
- temperature: request.temperature,
86436
- max_output_tokens: request.maxOutputTokens
86437
+ temperature: request.temperature
86437
86438
  };
86439
+ if (Number.isFinite(request.maxOutputTokens) && request.maxOutputTokens > 0) {
86440
+ body.max_output_tokens = request.maxOutputTokens;
86441
+ }
86438
86442
  if (request.reasoningEffort) body.reasoning = { effort: request.reasoningEffort, summary: "auto" };
86439
86443
  if (request.systemPrompt) body.instructions = request.systemPrompt;
86440
86444
  const tools = this.serializeTools(request.tools);
@@ -86789,10 +86793,10 @@ function abortFailure(signal) {
86789
86793
  function abortable(promise, signal) {
86790
86794
  if (!signal) return promise;
86791
86795
  if (signal.aborted) return Promise.reject(abortFailure(signal));
86792
- return new Promise((resolve15, reject) => {
86796
+ return new Promise((resolve16, reject) => {
86793
86797
  const onAbort = () => reject(abortFailure(signal));
86794
86798
  signal.addEventListener("abort", onAbort, { once: true });
86795
- promise.then(resolve15, reject).finally(() => signal.removeEventListener("abort", onAbort));
86799
+ promise.then(resolve16, reject).finally(() => signal.removeEventListener("abort", onAbort));
86796
86800
  });
86797
86801
  }
86798
86802
  function parseProviderSse(raw) {
@@ -87157,7 +87161,7 @@ var LLMProvider = class _LLMProvider {
87157
87161
  throw error2;
87158
87162
  });
87159
87163
  }
87160
- return new Promise((resolve15, reject) => {
87164
+ return new Promise((resolve16, reject) => {
87161
87165
  const parsed = new URL(urlValue);
87162
87166
  const client = parsed.protocol === "http:" ? http2 : https;
87163
87167
  const requestHeaders = { ...headers };
@@ -87181,7 +87185,7 @@ var LLMProvider = class _LLMProvider {
87181
87185
  const finish = () => {
87182
87186
  if (settled) return;
87183
87187
  settled = true;
87184
- resolve15({ status: res.statusCode || 0, body: responseBody, headers: res.headers });
87188
+ resolve16({ status: res.statusCode || 0, body: responseBody, headers: res.headers });
87185
87189
  };
87186
87190
  const fail2 = (error2) => {
87187
87191
  if (settled) return;
@@ -87226,7 +87230,7 @@ var LLMProvider = class _LLMProvider {
87226
87230
  if (_LLMProvider.powershellTransport) {
87227
87231
  return this.withRequestTimeout(_LLMProvider.powershellTransport(method, urlValue, headers, body), effectiveTimeout, signal);
87228
87232
  }
87229
- return new Promise((resolve15, reject) => {
87233
+ return new Promise((resolve16, reject) => {
87230
87234
  const headerJson = JSON.stringify(headers);
87231
87235
  const tempDir = fs5.mkdtempSync(path5.join(os.tmpdir(), "newmark-llm-"));
87232
87236
  const bodyPath = path5.join(tempDir, "body.json");
@@ -87317,7 +87321,7 @@ var LLMProvider = class _LLMProvider {
87317
87321
  const statusText = stdout.trim().split(/\r?\n/).pop() || "0";
87318
87322
  const bodyText = fs5.readFileSync(responsePath, "utf8");
87319
87323
  cleanup();
87320
- resolve15({ status: Number(statusText) || 0, body: bodyText });
87324
+ resolve16({ status: Number(statusText) || 0, body: bodyText });
87321
87325
  });
87322
87326
  child.stdin.end(`${urlValue}
87323
87327
  ${method}
@@ -87880,12 +87884,13 @@ ${responsePath}
87880
87884
  }
87881
87885
  async *chatStreamWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal, reasoningTier, sessionId) {
87882
87886
  if (signal?.aborted) throw abortFailure(signal);
87887
+ const requiredMaxTokens = maxTokens > 0 ? maxTokens : this.intelligenceConfig(reasoningTier || "medium").maxTokens;
87883
87888
  if (this.protocol() === "anthropic") {
87884
- yield* this.anthropicChatWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal);
87889
+ yield* this.anthropicChatWithTools(model, messages, systemPrompt, temperature, requiredMaxTokens, tools, signal);
87885
87890
  return;
87886
87891
  }
87887
87892
  if (this.protocol() === "github_models") {
87888
- yield* this.githubModelsChatStreamWithTools(model, messages, systemPrompt, temperature, maxTokens, tools, signal);
87893
+ yield* this.githubModelsChatStreamWithTools(model, messages, systemPrompt, temperature, requiredMaxTokens, tools, signal);
87889
87894
  return;
87890
87895
  }
87891
87896
  if (this.useProviderAdaptersV2) {
@@ -88441,10 +88446,10 @@ function candidateBaseUrls(rawBaseUrl) {
88441
88446
  }
88442
88447
  function endpointBaseFromSuffix(inputBaseUrl, suffix) {
88443
88448
  const base = inputBaseUrl.replace(/\/+$/g, "");
88444
- const path31 = suffix.replace(/\/+$/g, "");
88449
+ const path32 = suffix.replace(/\/+$/g, "");
88445
88450
  for (const terminal of ["/chat/completions", "/completions", "/responses", "/messages", "/models"]) {
88446
- if (path31.endsWith(terminal)) {
88447
- const prefix = path31.slice(0, -terminal.length).replace(/\/+$/g, "");
88451
+ if (path32.endsWith(terminal)) {
88452
+ const prefix = path32.slice(0, -terminal.length).replace(/\/+$/g, "");
88448
88453
  return `${base}${prefix}`;
88449
88454
  }
88450
88455
  }
@@ -107537,14 +107542,14 @@ var PowerShellWorker = class {
107537
107542
  const child = this.ensureChild();
107538
107543
  const id = crypto5.randomUUID();
107539
107544
  const startedAt = Date.now();
107540
- return await new Promise((resolve15, reject) => {
107545
+ return await new Promise((resolve16, reject) => {
107541
107546
  const timer = setTimeout(() => {
107542
107547
  this.pending.delete(id);
107543
107548
  reject(new Error(`Computer Use ${this.lane} helper timed out after ${timeoutMs} ms.`));
107544
107549
  }, Math.max(100, timeoutMs));
107545
107550
  this.pending.set(id, {
107546
107551
  timer,
107547
- resolve: (result) => resolve15({ ...result, elapsedMs: Date.now() - startedAt })
107552
+ resolve: (result) => resolve16({ ...result, elapsedMs: Date.now() - startedAt })
107548
107553
  });
107549
107554
  const request = JSON.stringify({
107550
107555
  id,
@@ -108513,7 +108518,7 @@ async function screenshot(workspacePath, ownerId, allowEphemeralVisionImage, inc
108513
108518
  async function wait(durationMs) {
108514
108519
  const ms = Math.min(Math.max(Math.floor(durationMs || 1e3), 0), 6e4);
108515
108520
  const start = Date.now();
108516
- await new Promise((resolve15) => setTimeout(resolve15, ms));
108521
+ await new Promise((resolve16) => setTimeout(resolve16, ms));
108517
108522
  return { ok: true, action: "wait", duration_ms: Date.now() - start };
108518
108523
  }
108519
108524
  async function moveOrClick(action, x, y, button, dryRun, target) {
@@ -108903,7 +108908,7 @@ function runAsyncProcess(command, args, options = {}) {
108903
108908
  overflowed: false
108904
108909
  });
108905
108910
  }
108906
- return new Promise((resolve15) => {
108911
+ return new Promise((resolve16) => {
108907
108912
  let child;
108908
108913
  try {
108909
108914
  child = (0, import_child_process4.spawn)(command, args, {
@@ -108914,7 +108919,7 @@ function runAsyncProcess(command, args, options = {}) {
108914
108919
  stdio: ["ignore", "pipe", "pipe"]
108915
108920
  });
108916
108921
  } catch (error2) {
108917
- resolve15({
108922
+ resolve16({
108918
108923
  status: null,
108919
108924
  stdout: "",
108920
108925
  stderr: "",
@@ -108942,7 +108947,7 @@ function runAsyncProcess(command, args, options = {}) {
108942
108947
  if (stopSettlementWatchdog) clearTimeout(stopSettlementWatchdog);
108943
108948
  options.signal?.removeEventListener("abort", abortListener);
108944
108949
  const error2 = spawnError || (stopReason === "abort" ? signalMessage(options.signal) : "") || (stopReason === "timeout" ? `Timed out after ${timeoutMs} ms` : "") || (stopReason === "maxBuffer" ? `Output exceeded ${maxBuffer2} byte limit` : "");
108945
- resolve15({
108950
+ resolve16({
108946
108951
  status,
108947
108952
  stdout: Buffer.concat(stdout).toString("utf8"),
108948
108953
  stderr: Buffer.concat(stderr).toString("utf8"),
@@ -110130,7 +110135,7 @@ function requestWindowsHostTool(tool, args, context, timeoutMs = 3e4, signal) {
110130
110135
  if (signal?.aborted) return Promise.reject(abortError(signal));
110131
110136
  const requestId = `host-tool-${process.pid}-${(0, import_crypto7.randomUUID)()}`;
110132
110137
  request.requestId = requestId;
110133
- return new Promise((resolve15, reject) => {
110138
+ return new Promise((resolve16, reject) => {
110134
110139
  const timer = setTimeout(() => {
110135
110140
  const active = pending.get(requestId);
110136
110141
  if (!active) return;
@@ -110153,7 +110158,7 @@ function requestWindowsHostTool(tool, args, context, timeoutMs = 3e4, signal) {
110153
110158
  }
110154
110159
  reject(abortError(signal));
110155
110160
  } : void 0;
110156
- pending.set(requestId, { resolve: resolve15, reject, timer, signal, abortListener });
110161
+ pending.set(requestId, { resolve: resolve16, reject, timer, signal, abortListener });
110157
110162
  if (abortListener) signal.addEventListener("abort", abortListener, { once: true });
110158
110163
  if (signal?.aborted) {
110159
110164
  abortListener?.();
@@ -110236,7 +110241,7 @@ function requestUtilityHostTool(tool, args, context, timeoutMs = 12e4, signal) {
110236
110241
  runtimeKey: target.runtimeKey
110237
110242
  } : void 0;
110238
110243
  const request = tool === "browser_control" ? { requestId, tool, args, target } : { requestId, tool, args, context: trustedContext, target };
110239
- return new Promise((resolve15, reject) => {
110244
+ return new Promise((resolve16, reject) => {
110240
110245
  const timer = setTimeout(() => {
110241
110246
  const active = pending2.get(requestId);
110242
110247
  if (!active) return;
@@ -110259,7 +110264,7 @@ function requestUtilityHostTool(tool, args, context, timeoutMs = 12e4, signal) {
110259
110264
  }
110260
110265
  reject(abortError2(signal));
110261
110266
  } : void 0;
110262
- pending2.set(requestId, { resolve: resolve15, reject, timer, signal, abortListener });
110267
+ pending2.set(requestId, { resolve: resolve16, reject, timer, signal, abortListener });
110263
110268
  if (abortListener) signal.addEventListener("abort", abortListener, { once: true });
110264
110269
  if (signal?.aborted) {
110265
110270
  abortListener?.();
@@ -110411,13 +110416,13 @@ function combineAbortSignals(signal, timeoutMs) {
110411
110416
  function createBash(workspaceRoot, timeoutMs) {
110412
110417
  const justBash = loadJustBash();
110413
110418
  if (!justBash) throw new Error("Native Bash runtime unavailable");
110414
- const fs28 = new justBash.ReadWriteFs({
110419
+ const fs29 = new justBash.ReadWriteFs({
110415
110420
  root: path15.resolve(workspaceRoot),
110416
110421
  maxFileReadSize: MAX_OUTPUT_BYTES * 8,
110417
110422
  allowSymlinks: false
110418
110423
  });
110419
110424
  return new justBash.Bash({
110420
- fs: fs28,
110425
+ fs: fs29,
110421
110426
  cwd: "/",
110422
110427
  env: {
110423
110428
  HOME: "/",
@@ -110578,17 +110583,17 @@ var ToolArgumentValidatorRegistry = class {
110578
110583
  };
110579
110584
  function formatValidationErrors(name, errors2) {
110580
110585
  const details = errors2.slice(0, 5).map((error2) => {
110581
- const path31 = String(error2.instancePath || "").replace(/^\//, "").replaceAll("/", ".");
110586
+ const path32 = String(error2.instancePath || "").replace(/^\//, "").replaceAll("/", ".");
110582
110587
  if (error2.keyword === "required") {
110583
- const required2 = String(error2.params?.requiredProperty || error2.params?.required || path31 || "property");
110588
+ const required2 = String(error2.params?.requiredProperty || error2.params?.required || path32 || "property");
110584
110589
  return `${required2} is required`;
110585
110590
  }
110586
110591
  if (error2.keyword === "additionalProperties") {
110587
110592
  const values = error2.params?.additionalProperties;
110588
- const fields2 = Array.isArray(values) ? values.map(String).join(", ") : String(values || path31 || "unknown");
110593
+ const fields2 = Array.isArray(values) ? values.map(String).join(", ") : String(values || path32 || "unknown");
110589
110594
  return `additional field(s) not allowed: ${fields2}`;
110590
110595
  }
110591
- const location = path31 || "arguments";
110596
+ const location = path32 || "arguments";
110592
110597
  const message = String(error2.message || error2.keyword || "is invalid");
110593
110598
  return `${location} ${message}`;
110594
110599
  });
@@ -111016,10 +111021,10 @@ function mergeDefs(...defs) {
111016
111021
  function cloneDef(schema) {
111017
111022
  return mergeDefs(schema._zod.def);
111018
111023
  }
111019
- function getElementAtPath(obj, path31) {
111020
- if (!path31)
111024
+ function getElementAtPath(obj, path32) {
111025
+ if (!path32)
111021
111026
  return obj;
111022
- return path31.reduce((acc, key3) => acc?.[key3], obj);
111027
+ return path32.reduce((acc, key3) => acc?.[key3], obj);
111023
111028
  }
111024
111029
  function promiseAllObject(promisesObj) {
111025
111030
  const keys = Object.keys(promisesObj);
@@ -111431,11 +111436,11 @@ function explicitlyAborted(x, startIndex = 0) {
111431
111436
  }
111432
111437
  return false;
111433
111438
  }
111434
- function prefixIssues(path31, issues) {
111439
+ function prefixIssues(path32, issues) {
111435
111440
  return issues.map((iss) => {
111436
111441
  var _a9;
111437
111442
  (_a9 = iss).path ?? (_a9.path = []);
111438
- iss.path.unshift(path31);
111443
+ iss.path.unshift(path32);
111439
111444
  return iss;
111440
111445
  });
111441
111446
  }
@@ -111867,16 +111872,16 @@ function flattenError(error2, mapper = (issue2) => issue2.message) {
111867
111872
  }
111868
111873
  function formatError(error2, mapper = (issue2) => issue2.message) {
111869
111874
  const fieldErrors = { _errors: [] };
111870
- const processError = (error3, path31 = []) => {
111875
+ const processError = (error3, path32 = []) => {
111871
111876
  for (const issue2 of error3.issues) {
111872
111877
  if (issue2.code === "invalid_union" && issue2.errors.length) {
111873
- issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
111878
+ issue2.errors.map((issues) => processError({ issues }, [...path32, ...issue2.path]));
111874
111879
  } else if (issue2.code === "invalid_key") {
111875
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
111880
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
111876
111881
  } else if (issue2.code === "invalid_element") {
111877
- processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
111882
+ processError({ issues: issue2.issues }, [...path32, ...issue2.path]);
111878
111883
  } else {
111879
- const fullpath = [...path31, ...issue2.path];
111884
+ const fullpath = [...path32, ...issue2.path];
111880
111885
  if (fullpath.length === 0) {
111881
111886
  fieldErrors._errors.push(mapper(issue2));
111882
111887
  } else {
@@ -119342,7 +119347,7 @@ var Protocol = class {
119342
119347
  return;
119343
119348
  }
119344
119349
  const pollInterval = task2.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1e3;
119345
- await new Promise((resolve15) => setTimeout(resolve15, pollInterval));
119350
+ await new Promise((resolve16) => setTimeout(resolve16, pollInterval));
119346
119351
  options?.signal?.throwIfAborted();
119347
119352
  }
119348
119353
  } catch (error2) {
@@ -119359,7 +119364,7 @@ var Protocol = class {
119359
119364
  */
119360
119365
  request(request, resultSchema, options) {
119361
119366
  const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};
119362
- return new Promise((resolve15, reject) => {
119367
+ return new Promise((resolve16, reject) => {
119363
119368
  const earlyReject = (error2) => {
119364
119369
  reject(error2);
119365
119370
  };
@@ -119437,7 +119442,7 @@ var Protocol = class {
119437
119442
  if (!parseResult.success) {
119438
119443
  reject(parseResult.error);
119439
119444
  } else {
119440
- resolve15(parseResult.data);
119445
+ resolve16(parseResult.data);
119441
119446
  }
119442
119447
  } catch (error2) {
119443
119448
  reject(error2);
@@ -119698,12 +119703,12 @@ var Protocol = class {
119698
119703
  }
119699
119704
  } catch {
119700
119705
  }
119701
- return new Promise((resolve15, reject) => {
119706
+ return new Promise((resolve16, reject) => {
119702
119707
  if (signal.aborted) {
119703
119708
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
119704
119709
  return;
119705
119710
  }
119706
- const timeoutId = setTimeout(resolve15, interval);
119711
+ const timeoutId = setTimeout(resolve16, interval);
119707
119712
  signal.addEventListener("abort", () => {
119708
119713
  clearTimeout(timeoutId);
119709
119714
  reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
@@ -121966,7 +121971,7 @@ var SSEClientTransport = class {
121966
121971
  }
121967
121972
  _startOrAuth() {
121968
121973
  const fetchImpl = this?._eventSourceInit?.fetch ?? this._fetch ?? fetch;
121969
- return new Promise((resolve15, reject) => {
121974
+ return new Promise((resolve16, reject) => {
121970
121975
  this._eventSource = new EventSource(this._url.href, {
121971
121976
  ...this._eventSourceInit,
121972
121977
  fetch: async (url2, init) => {
@@ -121987,7 +121992,7 @@ var SSEClientTransport = class {
121987
121992
  this._abortController = new AbortController();
121988
121993
  this._eventSource.onerror = (event) => {
121989
121994
  if (event.code === 401 && this._authProvider) {
121990
- this._authThenStart().then(resolve15, reject);
121995
+ this._authThenStart().then(resolve16, reject);
121991
121996
  return;
121992
121997
  }
121993
121998
  const error2 = new SseError(event.code, event.message, event);
@@ -122009,7 +122014,7 @@ var SSEClientTransport = class {
122009
122014
  void this.close();
122010
122015
  return;
122011
122016
  }
122012
- resolve15();
122017
+ resolve16();
122013
122018
  });
122014
122019
  this._eventSource.onmessage = (event) => {
122015
122020
  const messageEvent = event;
@@ -122188,7 +122193,7 @@ var StdioClientTransport = class {
122188
122193
  if (this._process) {
122189
122194
  throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
122190
122195
  }
122191
- return new Promise((resolve15, reject) => {
122196
+ return new Promise((resolve16, reject) => {
122192
122197
  this._process = (0, import_cross_spawn.default)(this._serverParams.command, this._serverParams.args ?? [], {
122193
122198
  // merge default env with server env because mcp server needs some env vars
122194
122199
  env: {
@@ -122205,7 +122210,7 @@ var StdioClientTransport = class {
122205
122210
  this.onerror?.(error2);
122206
122211
  });
122207
122212
  this._process.on("spawn", () => {
122208
- resolve15();
122213
+ resolve16();
122209
122214
  });
122210
122215
  this._process.on("close", (_code) => {
122211
122216
  this._process = void 0;
@@ -122270,22 +122275,22 @@ var StdioClientTransport = class {
122270
122275
  if (this._process) {
122271
122276
  const processToClose = this._process;
122272
122277
  this._process = void 0;
122273
- const closePromise = new Promise((resolve15) => {
122278
+ const closePromise = new Promise((resolve16) => {
122274
122279
  processToClose.once("close", () => {
122275
- resolve15();
122280
+ resolve16();
122276
122281
  });
122277
122282
  });
122278
122283
  try {
122279
122284
  processToClose.stdin?.end();
122280
122285
  } catch {
122281
122286
  }
122282
- await Promise.race([closePromise, new Promise((resolve15) => setTimeout(resolve15, 2e3).unref())]);
122287
+ await Promise.race([closePromise, new Promise((resolve16) => setTimeout(resolve16, 2e3).unref())]);
122283
122288
  if (processToClose.exitCode === null) {
122284
122289
  try {
122285
122290
  processToClose.kill("SIGTERM");
122286
122291
  } catch {
122287
122292
  }
122288
- await Promise.race([closePromise, new Promise((resolve15) => setTimeout(resolve15, 2e3).unref())]);
122293
+ await Promise.race([closePromise, new Promise((resolve16) => setTimeout(resolve16, 2e3).unref())]);
122289
122294
  }
122290
122295
  if (processToClose.exitCode === null) {
122291
122296
  try {
@@ -122297,15 +122302,15 @@ var StdioClientTransport = class {
122297
122302
  this._readBuffer.clear();
122298
122303
  }
122299
122304
  send(message) {
122300
- return new Promise((resolve15) => {
122305
+ return new Promise((resolve16) => {
122301
122306
  if (!this._process?.stdin) {
122302
122307
  throw new Error("Not connected");
122303
122308
  }
122304
122309
  const json = serializeMessage(message);
122305
122310
  if (this._process.stdin.write(json)) {
122306
- resolve15();
122311
+ resolve16();
122307
122312
  } else {
122308
- this._process.stdin.once("drain", resolve15);
122313
+ this._process.stdin.once("drain", resolve16);
122309
122314
  }
122310
122315
  });
122311
122316
  }
@@ -123242,11 +123247,11 @@ async function extractPdfTextLayer(buffer, maxChars, signal) {
123242
123247
  }
123243
123248
  async function abortableToolDelay(durationMs, signal) {
123244
123249
  if (signal?.aborted) throw abortReason2(signal);
123245
- await new Promise((resolve15, reject) => {
123250
+ await new Promise((resolve16, reject) => {
123246
123251
  const timer = setTimeout(finish, Math.max(0, durationMs));
123247
123252
  function finish() {
123248
123253
  signal?.removeEventListener("abort", abort);
123249
- resolve15();
123254
+ resolve16();
123250
123255
  }
123251
123256
  function abort() {
123252
123257
  clearTimeout(timer);
@@ -123732,7 +123737,7 @@ var ToolExecutor = class {
123732
123737
  const value = args[k];
123733
123738
  return value === void 0 || value === null ? "" : String(value);
123734
123739
  };
123735
- const resolve15 = (relPath) => normalizeCrossEnvPath(relPath, wsPath);
123740
+ const resolve16 = (relPath) => normalizeCrossEnvPath(relPath, wsPath);
123736
123741
  const targetForTool = () => {
123737
123742
  switch (tool) {
123738
123743
  case "read":
@@ -123742,11 +123747,11 @@ var ToolExecutor = class {
123742
123747
  case "grep":
123743
123748
  case "file_audit":
123744
123749
  case "pdf_read":
123745
- return resolve15(g("path"));
123750
+ return resolve16(g("path"));
123746
123751
  case "web_catch":
123747
- return resolve15(g("destination"));
123752
+ return resolve16(g("destination"));
123748
123753
  case "git_clone":
123749
- return resolve15(g("path"));
123754
+ return resolve16(g("path"));
123750
123755
  case "ssh_workspace":
123751
123756
  return wsPath;
123752
123757
  default:
@@ -123769,23 +123774,23 @@ var ToolExecutor = class {
123769
123774
  case "pwd":
123770
123775
  return `Current directory: ${wsPath}`;
123771
123776
  case "read":
123772
- return this.fread(resolve15(g("path")));
123777
+ return this.fread(resolve16(g("path")));
123773
123778
  case "write":
123774
- return this.fwrite(resolve15(g("path")), g("content"));
123779
+ return this.fwrite(resolve16(g("path")), g("content"));
123775
123780
  case "edit":
123776
- return this.fedit(resolve15(g("path")), g("old_str"), g("new_str"));
123781
+ return this.fedit(resolve16(g("path")), g("old_str"), g("new_str"));
123777
123782
  case "delete_file":
123778
- return this.fdelete(resolve15(g("path")));
123783
+ return this.fdelete(resolve16(g("path")));
123779
123784
  case "glob":
123780
123785
  return this.glob(g("pattern"), wsPath);
123781
123786
  case "grep":
123782
- return this.grep(g("pattern"), resolve15(g("path")));
123787
+ return this.grep(g("pattern"), resolve16(g("path")));
123783
123788
  case "web_search":
123784
123789
  return await this.wsearch(g("query"), context.signal);
123785
123790
  case "web_fetch":
123786
123791
  return await this.wfetch(g("url"), context.signal);
123787
123792
  case "web_catch":
123788
- return await this.wcatch(args, resolve15(g("destination")), context.signal);
123793
+ return await this.wcatch(args, resolve16(g("destination")), context.signal);
123789
123794
  case "browser_open":
123790
123795
  return await this.browserRun({ action: "open", url: g("url") }, context.signal, context, wsPath);
123791
123796
  case "browser_snapshot":
@@ -123879,12 +123884,12 @@ var ToolExecutor = class {
123879
123884
  return JSON.stringify(await this.localOcr.recognizeDataUrl(fallback.dataUrl, context.signal), null, 2);
123880
123885
  }
123881
123886
  if (source === "image") {
123882
- return JSON.stringify(await this.localOcr.recognizeFile(resolve15(g("path")), context.signal), null, 2);
123887
+ return JSON.stringify(await this.localOcr.recognizeFile(resolve16(g("path")), context.signal), null, 2);
123883
123888
  }
123884
123889
  return "[ocr fallback blocked] source must be browser or image.";
123885
123890
  }
123886
123891
  case "pdf_read": {
123887
- const pdfPath = resolve15(g("path"));
123892
+ const pdfPath = resolve16(g("path"));
123888
123893
  if (path19.extname(pdfPath).toLowerCase() !== ".pdf") return "[pdf_read error] path must end in .pdf.";
123889
123894
  const maxChars = Math.max(500, Math.min(1e5, Number(args.max_chars || 5e4)));
123890
123895
  const page = Math.max(1, Math.min(100, Math.floor(Number(args.page || 1))));
@@ -124164,15 +124169,15 @@ var ToolExecutor = class {
124164
124169
  case "git_status":
124165
124170
  return await this.gstat(wsPath, context.signal);
124166
124171
  case "file_audit":
124167
- return await this.fileAudit(resolve15(g("path") || "."), wsPath, args.include_remote !== false, g("base_ref"), context.signal);
124172
+ return await this.fileAudit(resolve16(g("path") || "."), wsPath, args.include_remote !== false, g("base_ref"), context.signal);
124168
124173
  case "repo_security_audit":
124169
- return await this.repoSecurityAudit(resolve15(g("path") || "."), wsPath, g("base_ref"), context.signal);
124174
+ return await this.repoSecurityAudit(resolve16(g("path") || "."), wsPath, g("base_ref"), context.signal);
124170
124175
  case "git_pull":
124171
124176
  return await this.gpull(wsPath, context.signal);
124172
124177
  case "git_push":
124173
124178
  return await this.withRemoteSecurityPreamble(wsPath, () => this.gpush(g("message"), wsPath, context.signal), context.signal, args.security_review_confirmed === true);
124174
124179
  case "git_clone":
124175
- return await this.gclone(g("url"), resolve15(g("path")), context.signal);
124180
+ return await this.gclone(g("url"), resolve16(g("path")), context.signal);
124176
124181
  case "git_branch":
124177
124182
  return await this.gbranch(g("action"), g("name"), g("start_point"), wsPath, context.signal);
124178
124183
  case "gh_auth_status":
@@ -125712,7 +125717,7 @@ var SubagentManager = class {
125712
125717
  waitForSettlement(idOrName, timeoutMs = 12e4) {
125713
125718
  const record3 = this.get(idOrName);
125714
125719
  if (!record3 || !["queued", "working"].includes(record3.status)) return Promise.resolve(record3 ? cloneRecord(record3) : void 0);
125715
- return new Promise((resolve15) => {
125720
+ return new Promise((resolve16) => {
125716
125721
  const waiters = this.settledWaiters.get(record3.id) || [];
125717
125722
  let done = false;
125718
125723
  let timer;
@@ -125720,7 +125725,7 @@ var SubagentManager = class {
125720
125725
  if (done) return;
125721
125726
  done = true;
125722
125727
  if (timer) clearTimeout(timer);
125723
- resolve15(value ? cloneRecord(value) : void 0);
125728
+ resolve16(value ? cloneRecord(value) : void 0);
125724
125729
  };
125725
125730
  waiters.push(finish);
125726
125731
  this.settledWaiters.set(record3.id, waiters);
@@ -126126,7 +126131,7 @@ ${prompt}`;
126126
126131
  resolveSettledWaiters(record3) {
126127
126132
  const waiters = this.settledWaiters.get(record3.id) || [];
126128
126133
  this.settledWaiters.delete(record3.id);
126129
- for (const resolve15 of waiters) resolve15(record3);
126134
+ for (const resolve16 of waiters) resolve16(record3);
126130
126135
  }
126131
126136
  pump() {
126132
126137
  if (!this.executor || this.schedulingPaused) return;
@@ -126961,6 +126966,23 @@ var SkillsManager = class {
126961
126966
  // src/core/agent.ts
126962
126967
  init_flow();
126963
126968
 
126969
+ // src/core/branchIdentity.ts
126970
+ var BRANCH_IDENTITY_SEPARATOR = "::branch:";
126971
+ function branchConversationIdentity(conversationId, branchNodeId) {
126972
+ const conversation = String(conversationId || "").trim() || "default";
126973
+ const branch = String(branchNodeId || "").trim();
126974
+ return branch ? `${conversation}${BRANCH_IDENTITY_SEPARATOR}${branch}` : conversation;
126975
+ }
126976
+ function assertFreshBranchIdentity(conversationId, branchNodeId, existing) {
126977
+ const branch = String(branchNodeId || "").trim();
126978
+ if (!branch) throw new Error("Branch conversation identity requires a branch node id.");
126979
+ for (const known of existing) {
126980
+ if (String(known || "") === branch) {
126981
+ throw new Error(`Branch conversation identity ${branchConversationIdentity(conversationId, branch)} is already in use.`);
126982
+ }
126983
+ }
126984
+ }
126985
+
126964
126986
  // src/core/agentKernelRunner.ts
126965
126987
  var fs19 = __toESM(require("fs"));
126966
126988
  var path21 = __toESM(require("path"));
@@ -128039,6 +128061,22 @@ var HIDDEN_LINE_PREFIXES = [
128039
128061
  "analysis:",
128040
128062
  "analysis\uFF1A"
128041
128063
  ];
128064
+ function providerSessionIdentity(agent) {
128065
+ const conversationId = String(agent.activeConversationId || "default");
128066
+ let runBranchId = "";
128067
+ try {
128068
+ runBranchId = String(agent.activeWorkRunBranchId() || "");
128069
+ } catch {
128070
+ runBranchId = "";
128071
+ }
128072
+ if (runBranchId) return branchConversationIdentity(conversationId, runBranchId);
128073
+ try {
128074
+ const snapshot2 = agent.getConversationSnapshot(conversationId);
128075
+ return branchConversationIdentity(conversationId, String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || ""));
128076
+ } catch {
128077
+ return conversationId;
128078
+ }
128079
+ }
128042
128080
  function partialMarkerSuffix(value, marker) {
128043
128081
  const lower = value.toLowerCase();
128044
128082
  const target = marker.toLowerCase();
@@ -128540,7 +128578,8 @@ async function runAgentKernel(agent) {
128540
128578
  currentAgent.checkpointPeerInput();
128541
128579
  peerInputCheckpointed = true;
128542
128580
  }
128543
- const { temperature, maxTokens, reasoningEffort } = currentProvider.intelligenceConfig(currentAgent.intelligence);
128581
+ const { temperature, reasoningEffort } = currentProvider.intelligenceConfig(currentAgent.intelligence);
128582
+ const maxTokens = 0;
128544
128583
  const newmarkMessages = fromKernelMessages(context.messages).map((message) => message.role === "assistant" ? { ...message, content: currentAgent.sanitizeAssistantOutput(String(message.content || "")) } : message);
128545
128584
  buildTaskFocusSnapshot ??= buildRequestTaskFocus(currentAgent, context.messages, {
128546
128585
  activeTools: context.tools || [],
@@ -128576,7 +128615,7 @@ async function runAgentKernel(agent) {
128576
128615
  providerTools,
128577
128616
  options?.signal,
128578
128617
  reasoningEffort,
128579
- currentAgent.config.getBool("context", "provider_session_id") ? currentAgent.activeConversationId : void 0
128618
+ currentAgent.config.getBool("context", "provider_session_id") ? providerSessionIdentity(currentAgent) : void 0
128580
128619
  )) {
128581
128620
  if (!firstTokenRecorded && (token.type === "text" && token.text || token.type === "tool_call" && token.toolCall)) {
128582
128621
  firstTokenRecorded = true;
@@ -132518,7 +132557,7 @@ var Agent5 = class _Agent {
132518
132557
  const nodeIndex = {};
132519
132558
  const pathIndex = {};
132520
132559
  for (const node2 of Object.values(tree.nodes)) {
132521
- const path31 = this.treePath(tree, node2.id);
132560
+ const path32 = this.treePath(tree, node2.id);
132522
132561
  const branchGroupIds = Object.values(tree.branchGroups).filter((group) => group.nodeIds.includes(node2.id)).map((group) => group.id);
132523
132562
  const messageIds = node2.chatMessages.map((message) => String(message.messageId || "")).filter(Boolean);
132524
132563
  const guideIds = node2.chatMessages.map((message) => String(message.guideId || "")).filter(Boolean);
@@ -132528,7 +132567,7 @@ var Agent5 = class _Agent {
132528
132567
  nodeId: node2.id,
132529
132568
  parentId: node2.parentId,
132530
132569
  childIds: [...childIds.get(node2.id) || []],
132531
- path: path31,
132570
+ path: path32,
132532
132571
  sourceMessageId: node2.sourceMessageId,
132533
132572
  sourceGuideId: node2.sourceGuideId,
132534
132573
  branchGroupIds,
@@ -132537,7 +132576,7 @@ var Agent5 = class _Agent {
132537
132576
  workRunIds,
132538
132577
  runningWorkRunIds
132539
132578
  };
132540
- pathIndex[path31.join(">")] = node2.id;
132579
+ pathIndex[path32.join(">")] = node2.id;
132541
132580
  }
132542
132581
  tree.nodeIndex = nodeIndex;
132543
132582
  tree.pathIndex = pathIndex;
@@ -132575,14 +132614,14 @@ var Agent5 = class _Agent {
132575
132614
  }
132576
132615
  }
132577
132616
  resolveConversationTreePath(tree, requestedPath) {
132578
- const path31 = (Array.isArray(requestedPath) ? requestedPath : []).map(String).filter(Boolean);
132579
- if (!path31.length) return tree.activeNodeId;
132580
- if (path31[0] !== tree.rootNodeId) throw new Error("Conversation branch path does not start at the tree root.");
132581
- for (let index2 = 0; index2 < path31.length; index2++) {
132582
- const node2 = tree.nodes[path31[index2]];
132583
- if (!node2 || index2 > 0 && node2.parentId !== path31[index2 - 1]) throw new Error("Conversation branch path is stale or invalid.");
132617
+ const path32 = (Array.isArray(requestedPath) ? requestedPath : []).map(String).filter(Boolean);
132618
+ if (!path32.length) return tree.activeNodeId;
132619
+ if (path32[0] !== tree.rootNodeId) throw new Error("Conversation branch path does not start at the tree root.");
132620
+ for (let index2 = 0; index2 < path32.length; index2++) {
132621
+ const node2 = tree.nodes[path32[index2]];
132622
+ if (!node2 || index2 > 0 && node2.parentId !== path32[index2 - 1]) throw new Error("Conversation branch path is stale or invalid.");
132584
132623
  }
132585
- return path31[path31.length - 1];
132624
+ return path32[path32.length - 1];
132586
132625
  }
132587
132626
  storedConversationTreePath(tree, requestedPath, fallbackNodeId) {
132588
132627
  if (!tree) return [];
@@ -132781,6 +132820,22 @@ var Agent5 = class _Agent {
132781
132820
  currentWorkRunId() {
132782
132821
  return this.activeWorkRunId || this.finalizingWorkRunId || "";
132783
132822
  }
132823
+ /**
132824
+ * The branch node that owns the currently active Build. Provider session ids
132825
+ * and branch-scoped caches must use this identity instead of "the branch that
132826
+ * happens to be active", otherwise a concurrently running sibling branch
132827
+ * (branch-communication mode) or a page switched mid-Build would read another
132828
+ * branch's remote session and folded history.
132829
+ */
132830
+ activeWorkRunBranchId() {
132831
+ const runId = this.currentWorkRunId();
132832
+ const run = runId ? this.workRuns.find((item) => String(item.runId || "") === runId) : void 0;
132833
+ return String(run?.branchNodeId || "") || this.currentBranchNodeId();
132834
+ }
132835
+ /** Full conversation identity of one branch node (shared by every branch kind). */
132836
+ branchConversationIdentity(branchNodeId) {
132837
+ return branchConversationIdentity(this.activeConversationId || "default", branchNodeId);
132838
+ }
132784
132839
  activeModelConfig() {
132785
132840
  const deployment = this.activeDeployment();
132786
132841
  return deployment ? this.config.findDeployment(deployment) : this.config.findModel(this.model);
@@ -134262,8 +134317,15 @@ ${String(event.toolArgs || "")}`;
134262
134317
  deduped.set(key3, {
134263
134318
  content,
134264
134319
  queueMode,
134320
+ buildId: String(raw.buildId || "").trim() || void 0,
134265
134321
  clientMessageId,
134266
134322
  runId: String(raw.runId || "").trim() || void 0,
134323
+ branchNodeId: String(raw.branchNodeId || "").trim() || void 0,
134324
+ branchPath: Array.isArray(raw.branchPath) ? raw.branchPath.map((id) => String(id || "")).filter(Boolean) : void 0,
134325
+ ledgerBranchId: String(raw.ledgerBranchId || "").trim() || void 0,
134326
+ targetRuntimeKey: String(raw.targetRuntimeKey || "").trim() || void 0,
134327
+ workspaceKey: String(raw.workspaceKey || "").trim() || void 0,
134328
+ modelSelection: String(raw.modelSelection || "").trim() || void 0,
134267
134329
  images: images.length ? images : void 0,
134268
134330
  attachments: attachments.length ? attachments : void 0,
134269
134331
  hiddenUserInput: raw.hiddenUserInput === true,
@@ -135012,6 +135074,7 @@ ${next2.body}`;
135012
135074
  });
135013
135075
  const reusableGroup = Object.values(tree.branchGroups).find((group) => group.sourceNodeId === parentNodeId && (targetGuideNodeId && group.sourceGuideId === targetGuideNodeId || !targetGuideNodeId && targetMessageId && group.sourceMessageId === targetMessageId || !group.sourceGuideId && !group.sourceMessageId && group.sourceMessageIndex === index2) || group.nodeIds.includes(parentNodeId) && group.sourceMessageIndex === index2 && (targetGuideNodeId && group.pageGuideIds?.[parentNodeId] === targetGuideNodeId || !targetGuideNodeId && targetMessageId && group.pageMessageIds?.[parentNodeId] === targetMessageId));
135014
135076
  const branchId = crypto15.randomUUID();
135077
+ assertFreshBranchIdentity(clean || this.activeConversationId || "default", branchId, Object.keys(tree.nodes));
135015
135078
  const branch = this.treeNodeFromEntry(branchId, parentNodeId, index2, text3, {
135016
135079
  ...entry,
135017
135080
  chatMessages: sourceNode.chatMessages.slice(0, index2),
@@ -135293,13 +135356,25 @@ Conversation title (a few words):`;
135293
135356
  if (error2 instanceof SyntaxError) return "provider returned invalid JSON";
135294
135357
  return "provider request failed";
135295
135358
  }
135359
+ /**
135360
+ * Deterministic provider rejections (bad key, forbidden endpoint, unknown
135361
+ * model, invalid request, payment required) cannot succeed by retrying the
135362
+ * identical title probe. Only transient transport, timeout, rate-limit and
135363
+ * provider-internal failures enter the bounded 5-stage backoff.
135364
+ */
135365
+ conversationTitleFailureIsRetryable(error2) {
135366
+ const message = error2 instanceof Error ? error2.message : "";
135367
+ const status = message.match(/^\[LLM Error:\s*([1-5]\d{2})\]/)?.[1];
135368
+ if (!status) return true;
135369
+ return status === "408" || status === "429" || status.startsWith("5");
135370
+ }
135296
135371
  async waitForConversationTitleRetry(delayMs, signal) {
135297
135372
  if (signal?.aborted || delayMs <= 0) return;
135298
- await new Promise((resolve15) => {
135373
+ await new Promise((resolve16) => {
135299
135374
  const finish = () => {
135300
135375
  clearTimeout(timer);
135301
135376
  signal?.removeEventListener("abort", finish);
135302
- resolve15();
135377
+ resolve16();
135303
135378
  };
135304
135379
  const timer = setTimeout(finish, delayMs);
135305
135380
  signal?.addEventListener("abort", finish, { once: true });
@@ -135316,21 +135391,25 @@ Conversation title (a few words):`;
135316
135391
  const retryDelaysMs = [0, 1e3, 2e3, 4e3, 8e3];
135317
135392
  if (!messageId || !firstUserInput.trim()) return false;
135318
135393
  let lastFailure = "provider returned an empty or unusable title";
135394
+ let terminalFailure = false;
135319
135395
  const requestTitle = async () => {
135320
135396
  lastFailure = "provider returned an empty or unusable title";
135397
+ terminalFailure = false;
135321
135398
  try {
135322
135399
  return await this.deriveConversationTitleFromProvider(firstUserInput, provider, modelName, intelligence, signal);
135323
135400
  } catch (error2) {
135324
135401
  lastFailure = this.conversationTitleFailureCause(error2, provider);
135402
+ terminalFailure = !this.conversationTitleFailureIsRetryable(error2);
135325
135403
  return "";
135326
135404
  }
135327
135405
  };
135328
135406
  const exhaustedFailure = () => new Error(
135329
- `Conversation title generation failed; ${lastFailure}. The first Agent request was not started. Retry the first input.`
135407
+ `Conversation title generation failed for ${provider.name}/${modelName}; ${lastFailure}. The first Agent request was not started. Retry the first input or switch the model.`
135330
135408
  );
135331
135409
  if (!stateKey2) {
135332
135410
  for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
135333
135411
  if (await requestTitle()) return true;
135412
+ if (terminalFailure) break;
135334
135413
  if (signal?.aborted) return false;
135335
135414
  if (attempt < maxAttempts - 1) await this.waitForConversationTitleRetry(retryDelaysMs[attempt], signal);
135336
135415
  }
@@ -135361,6 +135440,7 @@ Conversation title (a few words):`;
135361
135440
  this.publishConversationTitle(title, conversationId);
135362
135441
  return true;
135363
135442
  }
135443
+ if (terminalFailure) break;
135364
135444
  if (signal?.aborted) return false;
135365
135445
  if (attempt < maxAttempts - 1) await this.waitForConversationTitleRetry(retryDelaysMs[attempt], signal);
135366
135446
  }
@@ -135579,7 +135659,7 @@ Conversation title (a few words):`;
135579
135659
  chatMessages: [...this.chatMessages],
135580
135660
  history: [...this.history],
135581
135661
  providerUsage: this.conversationProviderUsage(),
135582
- compressionCache: [...this.compressionCache],
135662
+ compressionCache: this.mergedCompressionCacheForPersist(stored.conversations[stateKey2]),
135583
135663
  branchMailbox: [...this.branchMailbox],
135584
135664
  branchCommunication: this.branchCommunicationEnabled,
135585
135665
  plan: this.normalizeConversationPlan(this.conversationPlan),
@@ -135637,7 +135717,7 @@ Conversation title (a few words):`;
135637
135717
  if (saved) {
135638
135718
  this.restoreProviderUsage(saved.providerUsage);
135639
135719
  this.history = [...saved.history];
135640
- this.compressionCache = saved.compressionCache ? saved.compressionCache.map((entry) => ({ ...entry, messages: [...entry.messages] })) : [];
135720
+ this.compressionCache = this.compressionCacheForBranch(saved.compressionCache);
135641
135721
  this.nextCompressionCacheId = Math.max(1, ...this.compressionCache.map((entry) => Number(entry.id.replace(/^ctx-cache-/, "")) || 0)) + 1;
135642
135722
  this.branchMailbox = (saved.branchMailbox || []).map((message) => ({ ...message }));
135643
135723
  this.nextBranchMessageSequence = Math.max(1, ...this.branchMailbox.map((message) => Number(message.sequence) || 0)) + 1;
@@ -135666,7 +135746,7 @@ Conversation title (a few words):`;
135666
135746
  this.restoreProviderUsage(persisted?.providerUsage);
135667
135747
  const repairedHistory = this.repairDanglingToolCalls(persisted?.history ? [...persisted.history] : []);
135668
135748
  this.history = repairedHistory.messages;
135669
- this.compressionCache = persisted?.compressionCache ? persisted.compressionCache.map((entry) => ({ ...entry, messages: [...entry.messages] })) : [];
135749
+ this.compressionCache = this.compressionCacheForBranch(persisted?.compressionCache);
135670
135750
  this.nextCompressionCacheId = Math.max(1, ...this.compressionCache.map((entry) => Number(entry.id.replace(/^ctx-cache-/, "")) || 0)) + 1;
135671
135751
  this.branchMailbox = (persisted?.branchMailbox || []).map((message) => ({ ...message }));
135672
135752
  this.nextBranchMessageSequence = Math.max(1, ...this.branchMailbox.map((message) => Number(message.sequence) || 0)) + 1;
@@ -137182,6 +137262,8 @@ ${summary}`, segment, "local-summarize", true);
137182
137262
  requestContext = {
137183
137263
  requestId: context.requestId,
137184
137264
  runId: context.runId,
137265
+ branchId: String(context.branchId || ""),
137266
+ contextHash: String(context.contextHash || ""),
137185
137267
  model: String(context.model || ""),
137186
137268
  at: context.at,
137187
137269
  estimatedTokens: 0,
@@ -137256,10 +137338,18 @@ ${summary}`, segment, "local-summarize", true);
137256
137338
  return request;
137257
137339
  }
137258
137340
  recordRequestContext(request, messages, system, tools, model) {
137341
+ const contextHash = crypto15.createHash("sha256").update(JSON.stringify({
137342
+ model,
137343
+ system,
137344
+ tools,
137345
+ messages
137346
+ })).digest("hex").slice(0, 24);
137259
137347
  const context = {
137260
137348
  ...estimateSubmittedContext(messages, system, tools, this.compressionBuildBlockStart(messages)),
137261
137349
  requestId: request.id,
137262
137350
  runId: this.currentWorkRunId(),
137351
+ branchId: this.currentBranchNodeId(),
137352
+ contextHash,
137263
137353
  model,
137264
137354
  at: (/* @__PURE__ */ new Date()).toISOString()
137265
137355
  };
@@ -138010,7 +138100,7 @@ ${msg.content}
138010
138100
  }
138011
138101
  for (const entry of entries) {
138012
138102
  if (!entry.endsWith(".md")) continue;
138013
- await new Promise((resolve15) => setImmediate(resolve15));
138103
+ await new Promise((resolve16) => setImmediate(resolve16));
138014
138104
  const archivePath = path30.join(archiveDir, entry);
138015
138105
  const firstLine = await this.readArchiveFirstLine(archivePath);
138016
138106
  const id = `archive|${Buffer.from(path30.resolve(archiveDir), "utf-8").toString("base64")}|${Buffer.from(entry, "utf-8").toString("base64")}`;
@@ -139108,6 +139198,10 @@ ${persisted.map((guide, index2) => `Guide ${index2 + 1}: ${guide.text}`).join("\
139108
139198
  if (!titleProvider || !titleModelName) {
139109
139199
  throw new Error("Conversation title generation failed; no resolved model deployment is available. No LLM configured. Add provider in Settings > Models.");
139110
139200
  }
139201
+ this.emitWorkEvent({
139202
+ type: "status",
139203
+ content: `Preparing the first response: checking ${titleProvider.name}/${titleModelName} and generating the conversation title.`
139204
+ });
139111
139205
  const titled = await this.startFirstInputConversationTitle(
139112
139206
  firstResponseTitleInput.messageId,
139113
139207
  firstResponseTitleInput.input,
@@ -140504,7 +140598,36 @@ ${text3.slice(-tailChars).trimStart()}`;
140504
140598
  }
140505
140599
  compressionArchiveScopeKey() {
140506
140600
  if (this.isSubagentRuntime || !this.config.getBool("context", "compression_archive_enabled")) return null;
140507
- return this.workspaceConversationKey();
140601
+ const base = this.workspaceConversationKey();
140602
+ if (!base) return null;
140603
+ return branchConversationIdentity(base, this.currentBranchNodeId());
140604
+ }
140605
+ /**
140606
+ * The hot folded-history cache belongs to one branch node. Legacy entries
140607
+ * (created before branch scoping) belong to the root node, which is where
140608
+ * they were produced.
140609
+ */
140610
+ compressionCacheForBranch(entries) {
140611
+ const branch = String(this.currentBranchNodeId() || "");
140612
+ const root3 = String(this.conversationTree()?.rootNodeId || "");
140613
+ return (Array.isArray(entries) ? entries : []).flatMap((entry) => {
140614
+ const owner = String(entry.branchNodeId || root3 || "");
140615
+ if (branch && owner && owner !== branch) return [];
140616
+ if (branch && !owner) return [];
140617
+ return [{ ...entry, branchNodeId: owner || branch || void 0, messages: [...entry.messages] }];
140618
+ });
140619
+ }
140620
+ /**
140621
+ * Persist the union of every branch's folded history: the live in-memory
140622
+ * cache only holds the active branch, and the stored entry holds the rest.
140623
+ */
140624
+ mergedCompressionCacheForPersist(storedEntry) {
140625
+ const branch = String(this.currentBranchNodeId() || "");
140626
+ const others = (storedEntry?.compressionCache || []).filter((entry) => {
140627
+ const owner = String(entry.branchNodeId || "");
140628
+ return !!owner && owner !== branch;
140629
+ });
140630
+ return [...others, ...this.compressionCache.map((entry) => ({ ...entry, messages: [...entry.messages] }))];
140508
140631
  }
140509
140632
  coldCompressionEntries() {
140510
140633
  const scopeKey = this.compressionArchiveScopeKey();
@@ -140567,7 +140690,8 @@ ${text3.slice(-tailChars).trimStart()}`;
140567
140690
  foldedEntries: messages.length,
140568
140691
  foldedChars,
140569
140692
  model,
140570
- fallback
140693
+ fallback,
140694
+ branchNodeId: this.currentBranchNodeId() || void 0
140571
140695
  });
140572
140696
  this.nextCompressionCacheId += 1;
140573
140697
  const maxEntries = Math.max(0, Math.floor(this.config.getNum("context", "compression_cache_max") || 8));
@@ -141374,8 +141498,1023 @@ var GoalStateImpl = class {
141374
141498
  }
141375
141499
  };
141376
141500
 
141377
- // src/core/conversationKernel.ts
141501
+ // src/core/continuation/store.ts
141502
+ var fs28 = __toESM(require("fs"));
141503
+ var path31 = __toESM(require("path"));
141378
141504
  var import_crypto18 = require("crypto");
141505
+
141506
+ // src/core/continuation/contracts.ts
141507
+ var CONTINUATION_SCHEMA_VERSION = 1;
141508
+ var ContinuationError = class extends Error {
141509
+ constructor(code, message, detail) {
141510
+ super(message);
141511
+ this.code = code;
141512
+ this.detail = detail;
141513
+ this.name = "ContinuationError";
141514
+ }
141515
+ code;
141516
+ detail;
141517
+ };
141518
+ function stableJson(value) {
141519
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
141520
+ if (Array.isArray(value)) return `[${value.map((item) => stableJson(item)).join(",")}]`;
141521
+ const record3 = value;
141522
+ return `{${Object.keys(record3).sort().map((key3) => `${JSON.stringify(key3)}:${stableJson(record3[key3])}`).join(",")}}`;
141523
+ }
141524
+ function emptyLedger(workspaceId) {
141525
+ return {
141526
+ version: CONTINUATION_SCHEMA_VERSION,
141527
+ workspaceId,
141528
+ roots: {},
141529
+ branches: {},
141530
+ builds: {},
141531
+ attempts: {},
141532
+ guards: {},
141533
+ commands: {},
141534
+ finals: {},
141535
+ events: [],
141536
+ nextEventCursor: 1,
141537
+ nextQueueSequence: 1
141538
+ };
141539
+ }
141540
+ function defaultGuard(branchId) {
141541
+ return { branchId, activeBuildId: null, activeAttemptId: null, fence: 0, leaseUntil: 0, workerCapability: "" };
141542
+ }
141543
+ function commandKey(actorId, commandId) {
141544
+ return `${actorId}\0${commandId}`;
141545
+ }
141546
+ function buildInputHash(input) {
141547
+ return require("crypto").createHash("sha256").update(stableJson(input)).digest("hex").slice(0, 24);
141548
+ }
141549
+ function requestHash(command) {
141550
+ return require("crypto").createHash("sha256").update(stableJson({
141551
+ type: command.type,
141552
+ target: command.target,
141553
+ expectedTailBuildId: command.expectedTailBuildId,
141554
+ expectedQueueRevision: command.expectedQueueRevision,
141555
+ input: command.input,
141556
+ recipeSnapshotId: command.recipeSnapshotId
141557
+ })).digest("hex");
141558
+ }
141559
+
141560
+ // src/core/continuation/store.ts
141561
+ var GuardedContinuationStore = class {
141562
+ constructor(workspacePath, workspaceId, options = {}) {
141563
+ this.workspacePath = workspacePath;
141564
+ this.workspaceId = workspaceId;
141565
+ this.ledgerPath = path31.join(path31.resolve(workspacePath), "conversations", "continuation-ledger.json");
141566
+ this.lockPath = `${this.ledgerPath}.lock`;
141567
+ this.leaseMs = Math.max(5e3, Math.floor(options.leaseMs || 6e4));
141568
+ this.eventRetention = Math.max(200, Math.floor(options.eventRetention || 5e3));
141569
+ }
141570
+ workspacePath;
141571
+ workspaceId;
141572
+ ledgerPath;
141573
+ lockPath;
141574
+ leaseMs;
141575
+ eventRetention;
141576
+ fingerprint = "";
141577
+ cached = null;
141578
+ get filePath() {
141579
+ return this.ledgerPath;
141580
+ }
141581
+ ensureRoot(rootId, defaultBranchId) {
141582
+ this.mutate((ledger) => {
141583
+ if (!ledger.roots[rootId]) {
141584
+ ledger.roots[rootId] = {
141585
+ rootId,
141586
+ workspaceId: this.workspaceId,
141587
+ defaultBranchId,
141588
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
141589
+ };
141590
+ }
141591
+ this.ensureBranchRecord(ledger, { rootId, branchId: defaultBranchId, parentAnchorBuildId: null });
141592
+ });
141593
+ }
141594
+ ensureBranch(input) {
141595
+ return this.mutate((ledger) => this.ensureBranchRecord(ledger, input));
141596
+ }
141597
+ getReceipt(actorId, commandId) {
141598
+ return this.readLedger().commands[commandKey(actorId, commandId)];
141599
+ }
141600
+ enqueueBuild(command) {
141601
+ if (!command.target?.workspaceId || !command.target.expectedRootId || !command.target.branchId) {
141602
+ throw new ContinuationError("TARGET_REQUIRED", "workspaceId, expectedRootId and branchId are required");
141603
+ }
141604
+ if (command.target.workspaceId !== this.workspaceId) {
141605
+ throw new ContinuationError("ROUTE_MISMATCH", `Command workspace ${command.target.workspaceId} does not match ledger workspace ${this.workspaceId}`);
141606
+ }
141607
+ const hash = requestHash(command);
141608
+ return this.mutate((ledger) => {
141609
+ const key3 = commandKey(command.actorId, command.commandId);
141610
+ const existing = ledger.commands[key3];
141611
+ if (existing) {
141612
+ if (existing.requestHash !== hash) {
141613
+ throw new ContinuationError("IDEMPOTENCY_KEY_REUSE", `Command ${command.commandId} was already used with a different request`, { commandId: command.commandId });
141614
+ }
141615
+ return { ...existing, duplicate: true };
141616
+ }
141617
+ const branch = this.requireBranch(ledger, {
141618
+ workspaceId: command.target.workspaceId,
141619
+ rootId: command.target.expectedRootId,
141620
+ branchId: command.target.branchId
141621
+ });
141622
+ if (branch.queueRevision !== command.expectedQueueRevision) {
141623
+ throw new ContinuationError("QUEUE_REVISION_CONFLICT", `Queue revision ${command.expectedQueueRevision} is stale; authoritative revision is ${branch.queueRevision}`, {
141624
+ expected: command.expectedQueueRevision,
141625
+ actual: branch.queueRevision
141626
+ });
141627
+ }
141628
+ if ((branch.tailBuildId || null) !== (command.expectedTailBuildId || null)) {
141629
+ throw new ContinuationError("QUEUE_REVISION_CONFLICT", `Expected tail ${command.expectedTailBuildId || "null"} does not match authoritative tail ${branch.tailBuildId || "null"}`, {
141630
+ expected: command.expectedTailBuildId,
141631
+ actual: branch.tailBuildId
141632
+ });
141633
+ }
141634
+ const parentBuildId = branch.tailBuildId;
141635
+ const parent2 = parentBuildId ? ledger.builds[parentBuildId] : null;
141636
+ if (parentBuildId && (!parent2 || parent2.branchId !== branch.branchId)) {
141637
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch tail ${parentBuildId} is not owned by branch ${branch.branchId}`);
141638
+ }
141639
+ const buildId = `build-${(0, import_crypto18.randomUUID)()}`;
141640
+ const queueSequence = ledger.nextQueueSequence++;
141641
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
141642
+ const build2 = {
141643
+ buildId,
141644
+ workspaceId: this.workspaceId,
141645
+ rootId: branch.rootId,
141646
+ branchId: branch.branchId,
141647
+ parentBuildId,
141648
+ inputHash: buildInputHash(command.input),
141649
+ input: cloneInput(command.input),
141650
+ recipeSnapshotId: command.recipeSnapshotId,
141651
+ status: "QUEUED",
141652
+ queueSequence,
141653
+ createdAt: now2,
141654
+ updatedAt: now2
141655
+ };
141656
+ ledger.builds[buildId] = build2;
141657
+ branch.tailBuildId = buildId;
141658
+ branch.queueRevision += 1;
141659
+ branch.lifecycleRevision += 1;
141660
+ branch.updatedAt = now2;
141661
+ const receipt = {
141662
+ schemaVersion: 1,
141663
+ commandId: command.commandId,
141664
+ requestHash: hash,
141665
+ workspaceId: this.workspaceId,
141666
+ rootId: branch.rootId,
141667
+ branchId: branch.branchId,
141668
+ buildId,
141669
+ parentBuildId,
141670
+ queueSequence,
141671
+ queueRevision: branch.queueRevision,
141672
+ lifecycleRevision: branch.lifecycleRevision,
141673
+ acceptedAt: now2
141674
+ };
141675
+ ledger.commands[key3] = receipt;
141676
+ this.appendEvent(ledger, {
141677
+ type: "BuildAccepted",
141678
+ workspaceId: this.workspaceId,
141679
+ rootId: branch.rootId,
141680
+ branchId: branch.branchId,
141681
+ buildId,
141682
+ attemptId: null,
141683
+ fence: null,
141684
+ payload: { parentBuildId, queueSequence, inputHash: build2.inputHash }
141685
+ });
141686
+ return receipt;
141687
+ });
141688
+ }
141689
+ claimBuild(input) {
141690
+ return this.mutate((ledger) => {
141691
+ const branch = this.requireBranch(ledger, input);
141692
+ if (branch.paused) throw new ContinuationError("BRANCH_PAUSED", `Branch ${branch.branchId} is paused`);
141693
+ const now2 = input.now ?? Date.now();
141694
+ const guard = this.ensureGuard(ledger, branch.branchId);
141695
+ if (guard.activeBuildId && guard.leaseUntil > now2) {
141696
+ return null;
141697
+ }
141698
+ if (guard.activeBuildId) this.releaseExpiredGuard(ledger, branch, guard, now2);
141699
+ const candidate = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence).find((build2) => {
141700
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) return false;
141701
+ const parent2 = build2.parentBuildId ? ledger.builds[build2.parentBuildId] : null;
141702
+ return !parent2 || parent2.status === "SUCCEEDED";
141703
+ });
141704
+ if (!candidate) return null;
141705
+ const attemptId = `attempt-${(0, import_crypto18.randomUUID)()}`;
141706
+ const fence = guard.fence + 1;
141707
+ const leaseUntil = now2 + this.leaseMs;
141708
+ const attempt = {
141709
+ attemptId,
141710
+ buildId: candidate.buildId,
141711
+ branchId: branch.branchId,
141712
+ fence,
141713
+ status: "RUNNING",
141714
+ leaseUntil,
141715
+ workerCapability: String(input.workerCapability || "unknown"),
141716
+ startedAt: new Date(now2).toISOString()
141717
+ };
141718
+ ledger.attempts[attemptId] = attempt;
141719
+ ledger.guards[branch.branchId] = {
141720
+ branchId: branch.branchId,
141721
+ activeBuildId: candidate.buildId,
141722
+ activeAttemptId: attemptId,
141723
+ fence,
141724
+ leaseUntil,
141725
+ workerCapability: attempt.workerCapability
141726
+ };
141727
+ candidate.status = "RUNNING";
141728
+ candidate.updatedAt = attempt.startedAt;
141729
+ candidate.waitingReason = void 0;
141730
+ branch.lifecycleRevision += 1;
141731
+ branch.updatedAt = attempt.startedAt;
141732
+ this.appendEvent(ledger, {
141733
+ type: "AttemptStarted",
141734
+ workspaceId: this.workspaceId,
141735
+ rootId: branch.rootId,
141736
+ branchId: branch.branchId,
141737
+ buildId: candidate.buildId,
141738
+ attemptId,
141739
+ fence,
141740
+ payload: { parentBuildId: candidate.parentBuildId, workerCapability: attempt.workerCapability }
141741
+ });
141742
+ return {
141743
+ workspaceId: this.workspaceId,
141744
+ rootId: branch.rootId,
141745
+ branchId: branch.branchId,
141746
+ buildId: candidate.buildId,
141747
+ attemptId,
141748
+ fence,
141749
+ parentBuildId: candidate.parentBuildId,
141750
+ baseContextSnapshotId: candidate.recipeSnapshotId,
141751
+ environmentSnapshotId: candidate.recipeSnapshotId,
141752
+ workerCapability: attempt.workerCapability
141753
+ };
141754
+ });
141755
+ }
141756
+ updateQueuedBuild(input) {
141757
+ return this.mutate((ledger) => {
141758
+ const build2 = ledger.builds[input.buildId];
141759
+ if (!build2) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} does not exist`);
141760
+ if (build2.workspaceId !== this.workspaceId || input.rootId && build2.rootId !== input.rootId) {
141761
+ throw new ContinuationError("ROUTE_MISMATCH", `Build ${input.buildId} does not belong to workspace/root ${this.workspaceId}/${input.rootId}`);
141762
+ }
141763
+ const branch = ledger.branches[build2.branchId];
141764
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Build ${input.buildId} references missing branch ${build2.branchId}`);
141765
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only QUEUED builds can be edited`);
141766
+ build2.input = cloneInput(input.input);
141767
+ build2.inputHash = buildInputHash(build2.input);
141768
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141769
+ branch.queueRevision += 1;
141770
+ branch.lifecycleRevision += 1;
141771
+ branch.updatedAt = build2.updatedAt;
141772
+ return { ...build2, input: cloneInput(build2.input) };
141773
+ });
141774
+ }
141775
+ /**
141776
+ * dev-0.6.4 hotfix: 当某个被受理的 Build 失败/取消后,它的后继会永远无法被
141777
+ * claim(`claimBuild` 只认「父 = 已提交 frontier」),整条队列就此卡死,新提交
141778
+ * 也只是接在失败链后面。
141779
+ *
141780
+ * 这里提供一条**显式**修复通道:把被阻断的排队 Build 重新挂到当前已提交的
141781
+ * frontier 上,保持原有队列顺序,并为每一次改挂写入 `BuildQueueRepaired`
141782
+ * 审计事件(记录旧 parent / 新 parent / 原因)。它不是静默 rebase:调用方是
141783
+ * 用户的显式动作(恢复队列)或一次新的入队命令。
141784
+ */
141785
+ repairBlockedQueue(input) {
141786
+ return this.mutate((ledger) => {
141787
+ const branch = this.requireBranch(ledger, input);
141788
+ const frontier = branch.headBuildId || null;
141789
+ const queued = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence);
141790
+ const repaired = [];
141791
+ let chainParent = frontier;
141792
+ let mutated = false;
141793
+ for (const build2 of queued) {
141794
+ if ((build2.parentBuildId || null) !== (chainParent || null)) {
141795
+ const previousParentBuildId = build2.parentBuildId;
141796
+ build2.parentBuildId = chainParent;
141797
+ build2.waitingReason = void 0;
141798
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141799
+ repaired.push(build2.buildId);
141800
+ mutated = true;
141801
+ this.appendEvent(ledger, {
141802
+ type: "BuildQueueRepaired",
141803
+ workspaceId: this.workspaceId,
141804
+ rootId: branch.rootId,
141805
+ branchId: branch.branchId,
141806
+ buildId: build2.buildId,
141807
+ attemptId: null,
141808
+ fence: null,
141809
+ payload: {
141810
+ previousParentBuildId,
141811
+ newParentBuildId: chainParent,
141812
+ reason: String(input.reason || "committed-frontier-repair")
141813
+ }
141814
+ });
141815
+ }
141816
+ chainParent = build2.buildId;
141817
+ }
141818
+ if (mutated) {
141819
+ branch.queueRevision += 1;
141820
+ branch.lifecycleRevision += 1;
141821
+ branch.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141822
+ }
141823
+ return { repaired, frontier };
141824
+ });
141825
+ }
141826
+ /**
141827
+ * dev-0.6.4 hotfix: 读取视角的受阻推导。
141828
+ *
141829
+ * 一个 QUEUED Build 只有在它的父正好是「已提交 frontier」或队列里位于它之前
141830
+ * 的可执行 Build 时才可能被 claim(见 `claimBuild`)。这里按队列顺序推导哪些行
141831
+ * 目前不可执行:父不是链上前驱、或父已 FAILED/CANCELLED 的行即为受阻,且受阻点
141832
+ * 之后的所有行同样受阻。
141833
+ */
141834
+ blockedQueuedBuildIds(ledger, branch) {
141835
+ const blocked = /* @__PURE__ */ new Set();
141836
+ const queued = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence);
141837
+ let chainParent = branch.headBuildId || null;
141838
+ for (const build2 of queued) {
141839
+ const parent2 = build2.parentBuildId ? ledger.builds[build2.parentBuildId] : null;
141840
+ const parentIsChainPredecessor = (build2.parentBuildId || null) === (chainParent || null);
141841
+ const parentFailed = !!parent2 && (parent2.status === "FAILED" || parent2.status === "CANCELLED");
141842
+ if (!parentIsChainPredecessor || parentFailed) {
141843
+ blocked.add(build2.buildId);
141844
+ continue;
141845
+ }
141846
+ chainParent = build2.buildId;
141847
+ }
141848
+ return blocked;
141849
+ }
141850
+ deleteQueuedBuild(input) {
141851
+ this.mutate((ledger) => {
141852
+ const build2 = ledger.builds[input.buildId];
141853
+ if (!build2) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} does not exist`);
141854
+ if (build2.workspaceId !== this.workspaceId || input.rootId && build2.rootId !== input.rootId) {
141855
+ throw new ContinuationError("ROUTE_MISMATCH", `Build ${input.buildId} does not belong to workspace/root ${this.workspaceId}/${input.rootId}`);
141856
+ }
141857
+ const branch = ledger.branches[build2.branchId];
141858
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Build ${input.buildId} references missing branch ${build2.branchId}`);
141859
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only QUEUED builds can be deleted`);
141860
+ if (Object.values(ledger.builds).some((item) => item.parentBuildId === build2.buildId)) {
141861
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} still has queued successors; delete them from the tail first`);
141862
+ }
141863
+ if (branch.tailBuildId === build2.buildId) branch.tailBuildId = build2.parentBuildId;
141864
+ delete ledger.builds[build2.buildId];
141865
+ branch.queueRevision += 1;
141866
+ branch.lifecycleRevision += 1;
141867
+ branch.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
141868
+ });
141869
+ }
141870
+ reorderQueuedBuilds(input) {
141871
+ return this.mutate((ledger) => {
141872
+ const branch = this.requireBranch(ledger, input);
141873
+ const queued = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId && build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence);
141874
+ throw new ContinuationError(
141875
+ "ANCHOR_NOT_COMMITTED",
141876
+ `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.`,
141877
+ { branchId: branch.branchId, queuedBuildIds: queued.map((build2) => build2.buildId) }
141878
+ );
141879
+ });
141880
+ }
141881
+ heartbeat(scope, now2 = Date.now()) {
141882
+ return this.mutate((ledger) => {
141883
+ const guard = ledger.guards[scope.branchId];
141884
+ const attempt = ledger.attempts[scope.attemptId];
141885
+ 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) {
141886
+ this.appendEvent(ledger, {
141887
+ type: "StaleWriteRejected",
141888
+ workspaceId: this.workspaceId,
141889
+ rootId: ledger.builds[scope.buildId]?.rootId || "",
141890
+ branchId: scope.branchId,
141891
+ buildId: scope.buildId,
141892
+ attemptId: scope.attemptId,
141893
+ fence: scope.fence,
141894
+ payload: { operation: "heartbeat" }
141895
+ });
141896
+ return false;
141897
+ }
141898
+ const leaseUntil = now2 + this.leaseMs;
141899
+ attempt.leaseUntil = leaseUntil;
141900
+ guard.leaseUntil = leaseUntil;
141901
+ this.appendEvent(ledger, {
141902
+ type: "AttemptHeartbeat",
141903
+ workspaceId: this.workspaceId,
141904
+ rootId: ledger.builds[scope.buildId]?.rootId || "",
141905
+ branchId: scope.branchId,
141906
+ buildId: scope.buildId,
141907
+ attemptId: scope.attemptId,
141908
+ fence: scope.fence,
141909
+ payload: { leaseUntil }
141910
+ });
141911
+ return true;
141912
+ });
141913
+ }
141914
+ commitFinal(input) {
141915
+ return this.mutate((ledger) => {
141916
+ const { scope } = input;
141917
+ const branch = this.requireBranch(ledger, scope);
141918
+ const build2 = ledger.builds[scope.buildId];
141919
+ const attempt = ledger.attempts[scope.attemptId];
141920
+ const guard = ledger.guards[scope.branchId];
141921
+ const now2 = input.now ?? Date.now();
141922
+ if (!build2 || build2.branchId !== scope.branchId || build2.rootId !== scope.rootId) {
141923
+ throw new ContinuationError("UNKNOWN_BUILD", `Build ${scope.buildId} does not belong to branch ${scope.branchId}`);
141924
+ }
141925
+ if (ledger.finals[build2.buildId]) {
141926
+ throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already has an immutable final`, { final: ledger.finals[build2.buildId] });
141927
+ }
141928
+ 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) {
141929
+ this.appendEvent(ledger, {
141930
+ type: "StaleWriteRejected",
141931
+ workspaceId: this.workspaceId,
141932
+ rootId: branch.rootId,
141933
+ branchId: branch.branchId,
141934
+ buildId: build2.buildId,
141935
+ attemptId: scope.attemptId,
141936
+ fence: scope.fence,
141937
+ payload: { operation: "commit_final" }
141938
+ });
141939
+ throw new ContinuationError("STALE_EXECUTION", `Attempt ${scope.attemptId} no longer owns branch ${branch.branchId}`);
141940
+ }
141941
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) {
141942
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} parent ${build2.parentBuildId || "null"} is not the current head ${branch.headBuildId || "null"}`);
141943
+ }
141944
+ const final = {
141945
+ finalId: `final-${(0, import_crypto18.randomUUID)()}`,
141946
+ buildId: build2.buildId,
141947
+ branchId: branch.branchId,
141948
+ finalHash: String(input.finalHash || (0, import_crypto18.createHash)("sha256").update(String(input.text || "")).digest("hex").slice(0, 24)),
141949
+ stateSnapshotId: String(input.stateSnapshotId || build2.recipeSnapshotId),
141950
+ text: String(input.text || ""),
141951
+ committedAt: new Date(now2).toISOString()
141952
+ };
141953
+ ledger.finals[build2.buildId] = final;
141954
+ build2.status = "SUCCEEDED";
141955
+ build2.finalId = final.finalId;
141956
+ build2.updatedAt = final.committedAt;
141957
+ attempt.status = "COMPLETED";
141958
+ attempt.endedAt = final.committedAt;
141959
+ branch.headBuildId = build2.buildId;
141960
+ branch.lifecycleRevision += 1;
141961
+ branch.updatedAt = final.committedAt;
141962
+ this.releaseGuard(ledger, branch.branchId, attempt.fence);
141963
+ this.appendEvent(ledger, {
141964
+ type: "BuildCommitted",
141965
+ workspaceId: this.workspaceId,
141966
+ rootId: branch.rootId,
141967
+ branchId: branch.branchId,
141968
+ buildId: build2.buildId,
141969
+ attemptId: attempt.attemptId,
141970
+ fence: attempt.fence,
141971
+ payload: { finalId: final.finalId, finalHash: final.finalHash, headBuildId: branch.headBuildId }
141972
+ });
141973
+ return final;
141974
+ });
141975
+ }
141976
+ /**
141977
+ * Trusted external-owner completion.
141978
+ *
141979
+ * A Flow is a kernel-owned external run, not a leased model worker. It still
141980
+ * has to be a durable build so queued Goal/Next successors have a committed
141981
+ * parent. This path validates the parent/head relation transactionally but
141982
+ * does not require a BranchGuard attempt; the kernel owns the Flow lifetime.
141983
+ * If the build is not the next ready build, it stays QUEUED and the caller
141984
+ * must retry after the predecessor commits.
141985
+ */
141986
+ commitExternalBuild(input) {
141987
+ return this.mutate((ledger) => {
141988
+ const branch = this.requireBranch(ledger, input);
141989
+ const build2 = ledger.builds[input.buildId];
141990
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} is not in branch ${branch.branchId}`);
141991
+ if (build2.status === "SUCCEEDED") return true;
141992
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `External build ${build2.buildId} is ${build2.status}`);
141993
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) return false;
141994
+ const now2 = input.now ?? Date.now();
141995
+ const committedAt = new Date(now2).toISOString();
141996
+ const final = {
141997
+ finalId: `final-${(0, import_crypto18.randomUUID)()}`,
141998
+ buildId: build2.buildId,
141999
+ branchId: branch.branchId,
142000
+ finalHash: (0, import_crypto18.createHash)("sha256").update(String(input.text || "")).digest("hex").slice(0, 24),
142001
+ stateSnapshotId: build2.recipeSnapshotId,
142002
+ text: String(input.text || ""),
142003
+ committedAt
142004
+ };
142005
+ ledger.finals[build2.buildId] = final;
142006
+ build2.status = "SUCCEEDED";
142007
+ build2.finalId = final.finalId;
142008
+ build2.updatedAt = committedAt;
142009
+ branch.headBuildId = build2.buildId;
142010
+ branch.lifecycleRevision += 1;
142011
+ branch.updatedAt = committedAt;
142012
+ this.appendEvent(ledger, {
142013
+ type: "BuildCommitted",
142014
+ workspaceId: this.workspaceId,
142015
+ rootId: branch.rootId,
142016
+ branchId: branch.branchId,
142017
+ buildId: build2.buildId,
142018
+ attemptId: null,
142019
+ fence: null,
142020
+ payload: { finalId: final.finalId, finalHash: final.finalHash, externalOwner: true, headBuildId: branch.headBuildId }
142021
+ });
142022
+ return true;
142023
+ });
142024
+ }
142025
+ /**
142026
+ * Claim a new attempt for an existing external Flow build (suspend/resume).
142027
+ * The build identity and fixed parent are preserved; only the attempt/fence
142028
+ * advance. This is the external-owner equivalent of retryBuild.
142029
+ */
142030
+ claimExternalBuild(input) {
142031
+ return this.mutate((ledger) => {
142032
+ const branch = this.requireBranch(ledger, input);
142033
+ const build2 = ledger.builds[input.buildId];
142034
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} is not in branch ${branch.branchId}`);
142035
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already committed`);
142036
+ if (build2.status !== "QUEUED") throw new ContinuationError("BUILD_NOT_READY", `External build ${build2.buildId} is ${build2.status}`);
142037
+ if ((branch.headBuildId || null) !== (build2.parentBuildId || null)) {
142038
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `External build ${build2.buildId} parent is not the current head`);
142039
+ }
142040
+ const now2 = input.now ?? Date.now();
142041
+ const guard = this.ensureGuard(ledger, branch.branchId);
142042
+ const attemptId = `attempt-${(0, import_crypto18.randomUUID)()}`;
142043
+ const fence = guard.fence + 1;
142044
+ const leaseUntil = now2 + this.leaseMs;
142045
+ const attempt = {
142046
+ attemptId,
142047
+ buildId: build2.buildId,
142048
+ branchId: branch.branchId,
142049
+ fence,
142050
+ status: "RUNNING",
142051
+ leaseUntil,
142052
+ workerCapability: String(input.workerCapability || "flow-external"),
142053
+ startedAt: new Date(now2).toISOString()
142054
+ };
142055
+ ledger.attempts[attemptId] = attempt;
142056
+ ledger.guards[branch.branchId] = {
142057
+ branchId: branch.branchId,
142058
+ activeBuildId: build2.buildId,
142059
+ activeAttemptId: attemptId,
142060
+ fence,
142061
+ leaseUntil,
142062
+ workerCapability: attempt.workerCapability
142063
+ };
142064
+ build2.status = "RUNNING";
142065
+ build2.updatedAt = attempt.startedAt;
142066
+ branch.lifecycleRevision += 1;
142067
+ this.appendEvent(ledger, {
142068
+ type: "AttemptStarted",
142069
+ workspaceId: this.workspaceId,
142070
+ rootId: branch.rootId,
142071
+ branchId: branch.branchId,
142072
+ buildId: build2.buildId,
142073
+ attemptId,
142074
+ fence,
142075
+ payload: { externalOwner: true, workerCapability: attempt.workerCapability }
142076
+ });
142077
+ return {
142078
+ workspaceId: this.workspaceId,
142079
+ rootId: branch.rootId,
142080
+ branchId: branch.branchId,
142081
+ buildId: build2.buildId,
142082
+ attemptId,
142083
+ fence,
142084
+ parentBuildId: build2.parentBuildId,
142085
+ baseContextSnapshotId: build2.recipeSnapshotId,
142086
+ environmentSnapshotId: build2.recipeSnapshotId,
142087
+ workerCapability: attempt.workerCapability
142088
+ };
142089
+ });
142090
+ }
142091
+ failBuild(input) {
142092
+ this.terminateAttempt(input.scope, "FAILED", input.reason, input.now);
142093
+ }
142094
+ cancelBuild(input) {
142095
+ this.mutate((ledger) => {
142096
+ const branch = this.requireBranch(ledger, input);
142097
+ const build2 = ledger.builds[input.buildId];
142098
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} is not in branch ${branch.branchId}`);
142099
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${input.buildId} already committed`);
142100
+ const guard = this.ensureGuard(ledger, branch.branchId);
142101
+ if (guard.activeBuildId === build2.buildId) {
142102
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142103
+ if (attempt) {
142104
+ attempt.status = "CANCELLED";
142105
+ attempt.endedAt = new Date(input.now ?? Date.now()).toISOString();
142106
+ }
142107
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
142108
+ }
142109
+ build2.status = "CANCELLED";
142110
+ build2.updatedAt = new Date(input.now ?? Date.now()).toISOString();
142111
+ branch.lifecycleRevision += 1;
142112
+ this.markDependentsBlocked(ledger, branch, build2.buildId);
142113
+ this.appendEvent(ledger, {
142114
+ type: "BuildCancelled",
142115
+ workspaceId: this.workspaceId,
142116
+ rootId: branch.rootId,
142117
+ branchId: branch.branchId,
142118
+ buildId: build2.buildId,
142119
+ attemptId: null,
142120
+ fence: null
142121
+ });
142122
+ });
142123
+ }
142124
+ retryBuild(input) {
142125
+ return this.mutate((ledger) => {
142126
+ const branch = this.requireBranch(ledger, input);
142127
+ const build2 = ledger.builds[input.buildId];
142128
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} is not in branch ${branch.branchId}`);
142129
+ if (build2.status !== "FAILED" && build2.status !== "CANCELLED") {
142130
+ throw new ContinuationError("BUILD_NOT_READY", `Build ${build2.buildId} is ${build2.status}; only FAILED/CANCELLED builds can be retried`);
142131
+ }
142132
+ if (this.hasCommittedDescendant(ledger, build2.buildId)) {
142133
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Build ${build2.buildId} already has a committed descendant`);
142134
+ }
142135
+ build2.status = "QUEUED";
142136
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
142137
+ branch.lifecycleRevision += 1;
142138
+ return { ...build2, input: cloneInput(build2.input) };
142139
+ });
142140
+ }
142141
+ /**
142142
+ * Idempotent failure recovery for an input that was never accepted.
142143
+ *
142144
+ * Stop/archive may release the branch guard before the runtime reports the
142145
+ * failure. In that case the build is still the same durable row and must be
142146
+ * returned to QUEUED for an explicit resume instead of being stranded in
142147
+ * RUNNING (or permanently FAILED). A committed build is never requeued.
142148
+ */
142149
+ requeueBuild(input) {
142150
+ return this.mutate((ledger) => {
142151
+ const branch = this.requireBranch(ledger, input);
142152
+ const build2 = ledger.builds[input.buildId];
142153
+ if (!build2 || build2.branchId !== branch.branchId) throw new ContinuationError("UNKNOWN_BUILD", `Build ${input.buildId} is not in branch ${branch.branchId}`);
142154
+ if (build2.status === "SUCCEEDED") throw new ContinuationError("FINAL_ALREADY_COMMITTED", `Build ${build2.buildId} already committed and cannot be requeued`);
142155
+ const guard = this.ensureGuard(ledger, branch.branchId);
142156
+ if (guard.activeBuildId === build2.buildId) {
142157
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142158
+ if (attempt && attempt.status === "RUNNING") {
142159
+ attempt.status = "EXPIRED";
142160
+ attempt.endedAt = (/* @__PURE__ */ new Date()).toISOString();
142161
+ }
142162
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
142163
+ }
142164
+ build2.status = "QUEUED";
142165
+ build2.waitingReason = void 0;
142166
+ build2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
142167
+ branch.lifecycleRevision += 1;
142168
+ branch.updatedAt = build2.updatedAt;
142169
+ return { ...build2, input: cloneInput(build2.input) };
142170
+ });
142171
+ }
142172
+ forkBranch(input) {
142173
+ const hash = (0, import_crypto18.createHash)("sha256").update(JSON.stringify(input)).digest("hex");
142174
+ return this.mutate((ledger) => {
142175
+ const key3 = commandKey(input.actorId, input.commandId);
142176
+ const existing = ledger.commands[key3];
142177
+ if (existing) {
142178
+ if (existing.requestHash !== hash) throw new ContinuationError("IDEMPOTENCY_KEY_REUSE", `Command ${input.commandId} was already used with a different fork request`);
142179
+ return { ...ledger.branches[existing.branchId] };
142180
+ }
142181
+ const source = this.requireBranch(ledger, { workspaceId: input.workspaceId, rootId: "", branchId: input.sourceBranchId });
142182
+ const anchor2 = ledger.builds[input.anchorBuildId];
142183
+ if (!anchor2 || anchor2.branchId !== source.branchId || anchor2.status !== "SUCCEEDED") {
142184
+ throw new ContinuationError("ANCHOR_NOT_COMMITTED", `Anchor ${input.anchorBuildId} is not a committed build of source branch ${source.branchId}`);
142185
+ }
142186
+ if (!this.isAncestorOfHead(ledger, source, anchor2.buildId)) {
142187
+ throw new ContinuationError("ANCHOR_NOT_IN_LINEAGE", `Anchor ${anchor2.buildId} is not on the source branch lineage`);
142188
+ }
142189
+ const branch = this.ensureBranchRecord(ledger, {
142190
+ rootId: source.rootId,
142191
+ branchId: input.newBranchId,
142192
+ parentAnchorBuildId: anchor2.buildId
142193
+ });
142194
+ branch.headBuildId = anchor2.buildId;
142195
+ branch.tailBuildId = anchor2.buildId;
142196
+ branch.queueRevision = 0;
142197
+ branch.lifecycleRevision += 1;
142198
+ const receipt = {
142199
+ schemaVersion: 1,
142200
+ commandId: input.commandId,
142201
+ requestHash: hash,
142202
+ workspaceId: this.workspaceId,
142203
+ rootId: source.rootId,
142204
+ branchId: branch.branchId,
142205
+ buildId: anchor2.buildId,
142206
+ parentBuildId: anchor2.buildId,
142207
+ queueSequence: 0,
142208
+ queueRevision: branch.queueRevision,
142209
+ lifecycleRevision: branch.lifecycleRevision,
142210
+ acceptedAt: (/* @__PURE__ */ new Date()).toISOString()
142211
+ };
142212
+ ledger.commands[key3] = receipt;
142213
+ this.appendEvent(ledger, {
142214
+ type: "BranchForked",
142215
+ workspaceId: this.workspaceId,
142216
+ rootId: source.rootId,
142217
+ branchId: branch.branchId,
142218
+ buildId: anchor2.buildId,
142219
+ attemptId: null,
142220
+ fence: null,
142221
+ payload: { sourceBranchId: source.branchId, anchorBuildId: anchor2.buildId }
142222
+ });
142223
+ return { ...branch };
142224
+ });
142225
+ }
142226
+ setPaused(input) {
142227
+ return this.mutate((ledger) => {
142228
+ const branch = this.requireBranch(ledger, input);
142229
+ branch.paused = input.paused === true;
142230
+ branch.lifecycleRevision += 1;
142231
+ branch.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
142232
+ this.appendEvent(ledger, {
142233
+ type: branch.paused ? "BranchPaused" : "BranchResumed",
142234
+ workspaceId: this.workspaceId,
142235
+ rootId: branch.rootId,
142236
+ branchId: branch.branchId,
142237
+ buildId: null,
142238
+ attemptId: null,
142239
+ fence: null
142240
+ });
142241
+ return branch.paused;
142242
+ });
142243
+ }
142244
+ snapshot(input) {
142245
+ const ledger = this.readLedger();
142246
+ const branch = this.requireBranch(ledger, input);
142247
+ return this.snapshotUnlocked(ledger, branch);
142248
+ }
142249
+ snapshotUnlocked(ledger, branch) {
142250
+ const guard = ledger.guards[branch.branchId] || defaultGuard(branch.branchId);
142251
+ const blockedBuildIds = this.blockedQueuedBuildIds(ledger, branch);
142252
+ const builds = Object.values(ledger.builds).filter((build2) => build2.branchId === branch.branchId).sort((a, b) => a.queueSequence - b.queueSequence).map((build2) => ({
142253
+ ...build2,
142254
+ input: cloneInput(build2.input),
142255
+ waitingReason: build2.waitingReason || (blockedBuildIds.has(build2.buildId) ? "DEPENDENCY_FAILED" : void 0)
142256
+ }));
142257
+ return {
142258
+ workspaceId: this.workspaceId,
142259
+ rootId: branch.rootId,
142260
+ branchId: branch.branchId,
142261
+ headBuildId: branch.headBuildId,
142262
+ tailBuildId: branch.tailBuildId,
142263
+ queueRevision: branch.queueRevision,
142264
+ lifecycleRevision: branch.lifecycleRevision,
142265
+ paused: branch.paused,
142266
+ activeBuildId: guard.activeBuildId,
142267
+ guard: { ...guard },
142268
+ builds
142269
+ };
142270
+ }
142271
+ events(afterCursor = 0, limit = 500) {
142272
+ 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 }));
142273
+ }
142274
+ recoverExpiredLeases(now2 = Date.now()) {
142275
+ return this.mutate((ledger) => {
142276
+ let recovered = 0;
142277
+ for (const guard of Object.values(ledger.guards)) {
142278
+ if (!guard.activeBuildId || guard.leaseUntil > now2) continue;
142279
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142280
+ const build2 = ledger.builds[guard.activeBuildId];
142281
+ if (attempt && attempt.status === "RUNNING") {
142282
+ attempt.status = "EXPIRED";
142283
+ attempt.endedAt = new Date(now2).toISOString();
142284
+ }
142285
+ if (build2 && build2.status === "RUNNING") {
142286
+ build2.status = "QUEUED";
142287
+ build2.updatedAt = new Date(now2).toISOString();
142288
+ }
142289
+ this.releaseGuard(ledger, guard.branchId, guard.fence);
142290
+ recovered += 1;
142291
+ }
142292
+ return recovered;
142293
+ });
142294
+ }
142295
+ terminateAttempt(scope, status, reason, now2 = Date.now()) {
142296
+ this.mutate((ledger) => {
142297
+ const branch = this.requireBranch(ledger, scope);
142298
+ const build2 = ledger.builds[scope.buildId];
142299
+ const attempt = ledger.attempts[scope.attemptId];
142300
+ const guard = ledger.guards[scope.branchId];
142301
+ if (!build2 || !attempt || !guard || guard.activeAttemptId !== scope.attemptId || guard.fence !== scope.fence || attempt.fence !== scope.fence) {
142302
+ throw new ContinuationError("STALE_EXECUTION", `Attempt ${scope.attemptId} cannot terminate branch ${scope.branchId}`);
142303
+ }
142304
+ build2.status = status;
142305
+ build2.updatedAt = new Date(now2).toISOString();
142306
+ attempt.status = status === "FAILED" ? "FAILED" : "CANCELLED";
142307
+ attempt.endedAt = build2.updatedAt;
142308
+ branch.lifecycleRevision += 1;
142309
+ this.releaseGuard(ledger, branch.branchId, attempt.fence);
142310
+ this.markDependentsBlocked(ledger, branch, build2.buildId);
142311
+ this.appendEvent(ledger, {
142312
+ type: status === "FAILED" ? "BuildFailed" : "BuildCancelled",
142313
+ workspaceId: this.workspaceId,
142314
+ rootId: branch.rootId,
142315
+ branchId: branch.branchId,
142316
+ buildId: build2.buildId,
142317
+ attemptId: attempt.attemptId,
142318
+ fence: attempt.fence,
142319
+ payload: { reason: String(reason || "") }
142320
+ });
142321
+ });
142322
+ }
142323
+ releaseExpiredGuard(ledger, branch, guard, now2) {
142324
+ const attempt = guard.activeAttemptId ? ledger.attempts[guard.activeAttemptId] : void 0;
142325
+ const build2 = guard.activeBuildId ? ledger.builds[guard.activeBuildId] : void 0;
142326
+ if (attempt && attempt.status === "RUNNING") {
142327
+ attempt.status = "EXPIRED";
142328
+ attempt.endedAt = new Date(now2).toISOString();
142329
+ }
142330
+ if (build2 && build2.status === "RUNNING") {
142331
+ build2.status = "QUEUED";
142332
+ build2.updatedAt = new Date(now2).toISOString();
142333
+ }
142334
+ this.releaseGuard(ledger, branch.branchId, guard.fence);
142335
+ }
142336
+ markDependentsBlocked(ledger, branch, failedBuildId) {
142337
+ for (const build2 of Object.values(ledger.builds)) {
142338
+ if (build2.branchId !== branch.branchId || build2.status !== "QUEUED") continue;
142339
+ if (build2.parentBuildId === failedBuildId) build2.waitingReason = "DEPENDENCY_FAILED";
142340
+ }
142341
+ }
142342
+ hasCommittedDescendant(ledger, buildId) {
142343
+ return Object.values(ledger.builds).some((build2) => build2.parentBuildId === buildId && build2.status === "SUCCEEDED");
142344
+ }
142345
+ isAncestorOfHead(ledger, branch, anchorBuildId) {
142346
+ let cursor = branch.headBuildId;
142347
+ const seen = /* @__PURE__ */ new Set();
142348
+ while (cursor) {
142349
+ if (seen.has(cursor)) return false;
142350
+ seen.add(cursor);
142351
+ if (cursor === anchorBuildId) return true;
142352
+ cursor = ledger.builds[cursor]?.parentBuildId || null;
142353
+ }
142354
+ return false;
142355
+ }
142356
+ ensureBranchRecord(ledger, input) {
142357
+ const existing = ledger.branches[input.branchId];
142358
+ if (existing) return existing;
142359
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
142360
+ const branch = {
142361
+ branchId: input.branchId,
142362
+ workspaceId: this.workspaceId,
142363
+ rootId: input.rootId,
142364
+ parentAnchorBuildId: input.parentAnchorBuildId,
142365
+ headBuildId: input.parentAnchorBuildId,
142366
+ tailBuildId: input.parentAnchorBuildId,
142367
+ queueRevision: 0,
142368
+ lifecycleRevision: 0,
142369
+ paused: false,
142370
+ createdAt: now2,
142371
+ updatedAt: now2
142372
+ };
142373
+ ledger.branches[branch.branchId] = branch;
142374
+ ledger.guards[branch.branchId] = defaultGuard(branch.branchId);
142375
+ if (!ledger.roots[branch.rootId]) {
142376
+ ledger.roots[branch.rootId] = { rootId: branch.rootId, workspaceId: this.workspaceId, defaultBranchId: branch.branchId, createdAt: now2 };
142377
+ }
142378
+ return branch;
142379
+ }
142380
+ requireBranch(ledger, target) {
142381
+ const branch = ledger.branches[target.branchId];
142382
+ if (!branch) throw new ContinuationError("UNKNOWN_BRANCH", `Branch ${target.branchId} does not exist`);
142383
+ if (branch.workspaceId !== this.workspaceId) {
142384
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch ${target.branchId} belongs to workspace ${branch.workspaceId}`);
142385
+ }
142386
+ if (target.rootId && branch.rootId !== target.rootId) {
142387
+ throw new ContinuationError("ROUTE_MISMATCH", `Branch ${target.branchId} belongs to root ${branch.rootId}, not ${target.rootId}`);
142388
+ }
142389
+ return branch;
142390
+ }
142391
+ ensureGuard(ledger, branchId) {
142392
+ if (!ledger.guards[branchId]) ledger.guards[branchId] = defaultGuard(branchId);
142393
+ return ledger.guards[branchId];
142394
+ }
142395
+ /**
142396
+ * Release the active attempt without ever moving the branch fence backward.
142397
+ * A recovered/completed attempt's fence stays as the monotonic high-water
142398
+ * mark; the next claim increments it again.
142399
+ */
142400
+ releaseGuard(ledger, branchId, fence) {
142401
+ ledger.guards[branchId] = {
142402
+ ...defaultGuard(branchId),
142403
+ fence: Math.max(0, Math.floor(Number(fence) || 0))
142404
+ };
142405
+ }
142406
+ appendEvent(ledger, input) {
142407
+ const event = {
142408
+ ...input,
142409
+ eventId: `event-${(0, import_crypto18.randomUUID)()}`,
142410
+ cursor: ledger.nextEventCursor++,
142411
+ at: input.at || (/* @__PURE__ */ new Date()).toISOString()
142412
+ };
142413
+ ledger.events.push(event);
142414
+ if (ledger.events.length > this.eventRetention) ledger.events = ledger.events.slice(-this.eventRetention);
142415
+ return event;
142416
+ }
142417
+ mutate(apply) {
142418
+ fs28.mkdirSync(path31.dirname(this.ledgerPath), { recursive: true });
142419
+ const lockHandle = this.acquireLock();
142420
+ try {
142421
+ this.invalidateCache();
142422
+ const ledger = this.readLedgerUnlocked();
142423
+ const result = apply(ledger);
142424
+ this.writeLedgerUnlocked(ledger);
142425
+ return result;
142426
+ } finally {
142427
+ try {
142428
+ fs28.closeSync(lockHandle);
142429
+ } catch {
142430
+ }
142431
+ try {
142432
+ fs28.unlinkSync(this.lockPath);
142433
+ } catch {
142434
+ }
142435
+ }
142436
+ }
142437
+ acquireLock() {
142438
+ for (let attempt = 0; attempt < 400; attempt += 1) {
142439
+ try {
142440
+ return fs28.openSync(this.lockPath, "wx");
142441
+ } catch (error2) {
142442
+ const code = error2 && typeof error2 === "object" && "code" in error2 ? String(error2.code || "") : "";
142443
+ if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(code)) throw error2;
142444
+ if (code === "EEXIST") {
142445
+ try {
142446
+ if (Date.now() - fs28.statSync(this.lockPath).mtimeMs > 3e4) fs28.unlinkSync(this.lockPath);
142447
+ } catch {
142448
+ }
142449
+ }
142450
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5 + attempt);
142451
+ }
142452
+ }
142453
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Timed out acquiring continuation ledger lock: ${this.lockPath}`);
142454
+ }
142455
+ readLedger() {
142456
+ this.ensureLedgerExists();
142457
+ const stat = fs28.statSync(this.ledgerPath, { bigint: true });
142458
+ const fingerprint2 = `${stat.mtimeNs}:${stat.ctimeNs}:${stat.size}`;
142459
+ if (this.cached && this.fingerprint === fingerprint2) return this.cached;
142460
+ const ledger = this.readLedgerUnlocked();
142461
+ this.cached = ledger;
142462
+ this.fingerprint = fingerprint2;
142463
+ return ledger;
142464
+ }
142465
+ readLedgerUnlocked() {
142466
+ this.ensureLedgerExists();
142467
+ try {
142468
+ const raw = fs28.readFileSync(this.ledgerPath, "utf-8").replace(/^\uFEFF/, "");
142469
+ const parsed = JSON.parse(raw);
142470
+ if (!parsed || parsed.version !== 1 || !parsed.branches || !parsed.builds) {
142471
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Continuation ledger ${this.ledgerPath} has an unsupported shape`);
142472
+ }
142473
+ parsed.attempts = parsed.attempts || {};
142474
+ parsed.guards = parsed.guards || {};
142475
+ parsed.commands = parsed.commands || {};
142476
+ parsed.finals = parsed.finals || {};
142477
+ parsed.events = Array.isArray(parsed.events) ? parsed.events : [];
142478
+ parsed.nextEventCursor = Math.max(1, Number(parsed.nextEventCursor) || (parsed.events.at(-1)?.cursor || 0) + 1);
142479
+ parsed.nextQueueSequence = Math.max(1, Number(parsed.nextQueueSequence) || Object.values(parsed.builds).reduce((max, build2) => Math.max(max, build2.queueSequence || 0), 0) + 1);
142480
+ return parsed;
142481
+ } catch (error2) {
142482
+ if (error2 instanceof ContinuationError) throw error2;
142483
+ throw new ContinuationError("EFFECT_UNCERTAIN", `Continuation ledger ${this.ledgerPath} is unreadable: ${error2 instanceof Error ? error2.message : String(error2)}`);
142484
+ }
142485
+ }
142486
+ writeLedgerUnlocked(ledger) {
142487
+ const temp = `${this.ledgerPath}.${process.pid}.${(0, import_crypto18.randomUUID)()}.tmp`;
142488
+ fs28.writeFileSync(temp, `${JSON.stringify(ledger, null, 2)}
142489
+ `, "utf-8");
142490
+ fs28.renameSync(temp, this.ledgerPath);
142491
+ this.invalidateCache();
142492
+ }
142493
+ ensureLedgerExists() {
142494
+ if (fs28.existsSync(this.ledgerPath)) return;
142495
+ fs28.mkdirSync(path31.dirname(this.ledgerPath), { recursive: true });
142496
+ const ledger = emptyLedger(this.workspaceId);
142497
+ const temp = `${this.ledgerPath}.${process.pid}.${(0, import_crypto18.randomUUID)()}.tmp`;
142498
+ fs28.writeFileSync(temp, `${JSON.stringify(ledger, null, 2)}
142499
+ `, "utf-8");
142500
+ fs28.renameSync(temp, this.ledgerPath);
142501
+ }
142502
+ invalidateCache() {
142503
+ this.cached = null;
142504
+ this.fingerprint = "";
142505
+ }
142506
+ };
142507
+ function cloneInput(input) {
142508
+ return {
142509
+ ...input,
142510
+ images: input.images?.map((image) => ({ ...image })),
142511
+ attachments: input.attachments?.map((attachment) => ({ ...attachment })),
142512
+ branchPath: input.branchPath?.slice()
142513
+ };
142514
+ }
142515
+
142516
+ // src/core/conversationKernel.ts
142517
+ var import_crypto19 = require("crypto");
141379
142518
  function changedLineCount(value) {
141380
142519
  if (!value) return 0;
141381
142520
  return value.split(/\r?\n/).length;
@@ -141433,25 +142572,168 @@ var ConversationKernel = class {
141433
142572
  return runtimes.map((runtime) => runtime.runtimeKey);
141434
142573
  }
141435
142574
  /** A Flow and its queue share one Agent; no second history writer is created. */
141436
- beginExternalRun(targetInput, options, createOwner, previousQueuePaused) {
142575
+ beginExternalRun(targetInput, options, createOwner, previousQueuePaused, buildInput) {
141437
142576
  const target = this.normalizeTarget(targetInput);
141438
142577
  const existing = this.findRuntime(target);
141439
142578
  if (existing?.activePromise || existing?.externalOwner?.active) throw new Error("Target conversation is already running");
141440
142579
  const runtime = existing || this.runtime(target, options, createOwner());
142580
+ this.reconcilePendingContinuations(runtime);
141441
142581
  runtime.options = { ...options };
141442
142582
  runtime.externalOwner = { active: true, wasPaused: runtime.externalOwner?.wasPaused ?? previousQueuePaused ?? runtime.queuePaused };
141443
142583
  runtime.queuePaused = true;
141444
- runtime.runId ||= (0, import_crypto18.randomUUID)();
142584
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141445
142585
  runtime.stopRequestedRunId = "";
142586
+ if (buildInput) {
142587
+ const continuation = this.continuationStore(runtime);
142588
+ if (continuation) {
142589
+ if (buildInput.existingBuildId) {
142590
+ runtime.externalBuildId = buildInput.existingBuildId;
142591
+ runtime.externalScope = continuation.store.claimExternalBuild({
142592
+ workspaceId: continuation.workspaceId,
142593
+ rootId: continuation.rootId,
142594
+ branchId: continuation.branchId,
142595
+ buildId: buildInput.existingBuildId,
142596
+ workerCapability: "flow-external"
142597
+ });
142598
+ } else if (buildInput.resume && runtime.externalBuildId) {
142599
+ runtime.externalScope = continuation.store.claimExternalBuild({
142600
+ workspaceId: continuation.workspaceId,
142601
+ rootId: continuation.rootId,
142602
+ branchId: continuation.branchId,
142603
+ buildId: runtime.externalBuildId,
142604
+ workerCapability: "flow-external"
142605
+ });
142606
+ } else {
142607
+ const authoritative = continuation.store.snapshot({
142608
+ workspaceId: continuation.workspaceId,
142609
+ rootId: continuation.rootId,
142610
+ branchId: continuation.branchId
142611
+ });
142612
+ const receipt = continuation.store.enqueueBuild({
142613
+ schemaVersion: 1,
142614
+ type: "ENQUEUE_BUILD",
142615
+ commandId: buildInput.commandId || (0, import_crypto19.randomUUID)(),
142616
+ actorId: "flow",
142617
+ target: {
142618
+ workspaceId: continuation.workspaceId,
142619
+ expectedRootId: continuation.rootId,
142620
+ branchId: continuation.branchId
142621
+ },
142622
+ expectedTailBuildId: authoritative.tailBuildId,
142623
+ expectedQueueRevision: authoritative.queueRevision,
142624
+ input: {
142625
+ text: buildInput.text,
142626
+ requestedMode: buildInput.requestedMode || "flow",
142627
+ goalObjective: buildInput.goalObjective,
142628
+ modelSelection: buildInput.modelSelection || runtime.options.model,
142629
+ branchNodeId: buildInput.branchNodeId,
142630
+ branchPath: buildInput.branchPath
142631
+ },
142632
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:flow`,
142633
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
142634
+ });
142635
+ runtime.externalBuildId = receipt.buildId;
142636
+ runtime.externalScope = continuation.store.claimExternalBuild({
142637
+ workspaceId: continuation.workspaceId,
142638
+ rootId: continuation.rootId,
142639
+ branchId: continuation.branchId,
142640
+ buildId: receipt.buildId,
142641
+ workerCapability: "flow-external"
142642
+ });
142643
+ }
142644
+ }
142645
+ }
141446
142646
  this.emitQueueUpdate(runtime);
141447
142647
  return runtime.runner;
141448
142648
  }
142649
+ /**
142650
+ * Admit a Flow build at command-acceptance time. The Flow may wait behind a
142651
+ * running Build, but its queue position (and therefore the parent of every
142652
+ * later Next item) is fixed now, not when the Flow finally starts.
142653
+ */
142654
+ admitExternalBuild(targetInput, buildInput) {
142655
+ const target = this.normalizeTarget(targetInput);
142656
+ const existing = this.findRuntime(target);
142657
+ const runtime = existing || this.runtime(target, {
142658
+ mode: "flow",
142659
+ model: buildInput.modelSelection || this.host.modelSelectionValue(),
142660
+ intelligence: this.host.intelligence,
142661
+ inputMode: this.host.inputMode,
142662
+ engine: this.host.engine
142663
+ }, this.createRunner(target));
142664
+ const continuation = this.continuationStore(runtime);
142665
+ if (!continuation) return null;
142666
+ const authoritative = continuation.store.snapshot({
142667
+ workspaceId: continuation.workspaceId,
142668
+ rootId: continuation.rootId,
142669
+ branchId: continuation.branchId
142670
+ });
142671
+ const receipt = continuation.store.enqueueBuild({
142672
+ schemaVersion: 1,
142673
+ type: "ENQUEUE_BUILD",
142674
+ commandId: buildInput.commandId,
142675
+ actorId: "flow",
142676
+ target: {
142677
+ workspaceId: continuation.workspaceId,
142678
+ expectedRootId: continuation.rootId,
142679
+ branchId: continuation.branchId
142680
+ },
142681
+ expectedTailBuildId: authoritative.tailBuildId,
142682
+ expectedQueueRevision: authoritative.queueRevision,
142683
+ input: {
142684
+ text: buildInput.text,
142685
+ requestedMode: buildInput.requestedMode || "flow",
142686
+ goalObjective: buildInput.goalObjective,
142687
+ modelSelection: buildInput.modelSelection || runtime.options.model,
142688
+ branchNodeId: buildInput.branchNodeId,
142689
+ branchPath: buildInput.branchPath
142690
+ },
142691
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:flow`,
142692
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
142693
+ });
142694
+ return receipt.buildId;
142695
+ }
141449
142696
  settleExternalRun(target, completed) {
141450
142697
  const runtime = this.findRuntime(target);
141451
142698
  if (!runtime?.externalOwner) return;
141452
142699
  const wasPaused = runtime.externalOwner.wasPaused;
141453
142700
  if (completed) runtime.externalOwner = void 0;
141454
142701
  else runtime.externalOwner.active = false;
142702
+ if (runtime.externalBuildId) {
142703
+ const continuation = this.continuationStore(runtime);
142704
+ if (continuation) {
142705
+ if (completed) {
142706
+ if (runtime.externalScope) {
142707
+ continuation.store.commitFinal({
142708
+ scope: runtime.externalScope,
142709
+ text: runtime.externalFinalText || ""
142710
+ });
142711
+ } else {
142712
+ continuation.store.commitExternalBuild({
142713
+ workspaceId: continuation.workspaceId,
142714
+ rootId: continuation.rootId,
142715
+ branchId: continuation.branchId,
142716
+ buildId: runtime.externalBuildId,
142717
+ text: runtime.externalFinalText || ""
142718
+ });
142719
+ }
142720
+ runtime.externalBuildId = void 0;
142721
+ runtime.externalScope = void 0;
142722
+ runtime.externalFinalText = void 0;
142723
+ } else {
142724
+ try {
142725
+ continuation.store.requeueBuild({
142726
+ workspaceId: continuation.workspaceId,
142727
+ rootId: continuation.rootId,
142728
+ branchId: continuation.branchId,
142729
+ buildId: runtime.externalBuildId
142730
+ });
142731
+ } catch {
142732
+ }
142733
+ runtime.externalScope = void 0;
142734
+ }
142735
+ }
142736
+ }
141455
142737
  runtime.queuePaused = completed && !runtime.preparingArchive ? wasPaused : true;
141456
142738
  runtime.runner.saveWorkspaceConversationState(true);
141457
142739
  this.emitQueueUpdate(runtime);
@@ -141461,6 +142743,24 @@ var ConversationKernel = class {
141461
142743
  const runtime = this.findRuntime(target);
141462
142744
  if (!runtime) return;
141463
142745
  if (runtime.externalOwner?.active) throw new Error("Wait for the Flow to stop before releasing its queue");
142746
+ if (runtime.externalBuildId) {
142747
+ const continuation = this.continuationStore(runtime);
142748
+ if (continuation) {
142749
+ try {
142750
+ continuation.store.commitExternalBuild({
142751
+ workspaceId: continuation.workspaceId,
142752
+ rootId: continuation.rootId,
142753
+ branchId: continuation.branchId,
142754
+ buildId: runtime.externalBuildId,
142755
+ text: "Flow exited by the user; the conversation queue resumed."
142756
+ });
142757
+ } catch {
142758
+ }
142759
+ }
142760
+ runtime.externalBuildId = void 0;
142761
+ runtime.externalScope = void 0;
142762
+ runtime.externalFinalText = void 0;
142763
+ }
141464
142764
  runtime.externalOwner = void 0;
141465
142765
  this.setQueuePaused(target, paused);
141466
142766
  }
@@ -141556,27 +142856,82 @@ var ConversationKernel = class {
141556
142856
  queueItems(target) {
141557
142857
  const runtime = this.findRuntime(target);
141558
142858
  if (!runtime) return [];
142859
+ let waitingByBuildId = /* @__PURE__ */ new Map();
142860
+ const continuation = this.continuationStore(runtime);
142861
+ if (continuation) {
142862
+ try {
142863
+ const snapshot2 = continuation.store.snapshot({
142864
+ workspaceId: continuation.workspaceId,
142865
+ rootId: continuation.rootId,
142866
+ branchId: continuation.branchId
142867
+ });
142868
+ waitingByBuildId = new Map(snapshot2.builds.filter((build2) => !!build2.waitingReason).map((build2) => [build2.buildId, String(build2.waitingReason)]));
142869
+ } catch {
142870
+ }
142871
+ }
141559
142872
  return runtime.pendingNextTurn.flatMap((item) => {
141560
142873
  if (item.queueMode !== "followUp") return [];
141561
142874
  if (typeof item.message === "string") return [];
141562
142875
  const id = String(item.message.clientMessageId || "");
141563
142876
  if (!id) return [];
142877
+ const buildId = String(item.message.buildId || "");
141564
142878
  return [{
141565
142879
  id,
142880
+ buildId: item.message.buildId,
141566
142881
  text: String(item.message.visibleUserInput || item.message.text || "").replace(/^\[Next queued while current turn is running\]\n/, ""),
141567
142882
  queueMode: item.queueMode,
141568
142883
  requestedMode: item.message.visibleMode,
141569
142884
  goalObjective: item.message.goalObjective,
141570
142885
  runId: item.message.runId,
141571
142886
  createdAt: String(item.message.createdAt || ""),
141572
- images: item.message.images?.map((image) => ({ ...image }))
142887
+ images: item.message.images?.map((image) => ({ ...image })),
142888
+ branchNodeId: item.message.branchNodeId,
142889
+ branchPath: item.message.branchPath?.slice(),
142890
+ modelSelection: item.message.modelSelection,
142891
+ waitingReason: waitingByBuildId.get(buildId),
142892
+ blocked: waitingByBuildId.has(buildId)
141573
142893
  }];
141574
142894
  });
141575
142895
  }
142896
+ /**
142897
+ * Capture the exact runtime branch that owns a queued user turn. A queued
142898
+ * Next is a new user turn, but it must still land on the branch the user was
142899
+ * viewing when they enqueued it, not on whatever branch happens to be active
142900
+ * when the previous Build settles.
142901
+ */
142902
+ runtimeBranchIdentity(runtime) {
142903
+ try {
142904
+ const snapshot2 = runtime.runner.getConversationSnapshot(runtime.id);
142905
+ const path32 = Array.isArray(snapshot2.runtimeBranchNodePath) ? snapshot2.runtimeBranchNodePath.map((id) => String(id || "")).filter(Boolean) : [];
142906
+ const branchNodeId = String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || path32[path32.length - 1] || "");
142907
+ return {
142908
+ branchNodeId,
142909
+ branchPath: path32.length ? path32 : branchNodeId ? [branchNodeId] : []
142910
+ };
142911
+ } catch {
142912
+ return { branchNodeId: "", branchPath: [] };
142913
+ }
142914
+ }
142915
+ /**
142916
+ * Map the current conversation/branch model onto the continuation-v1
142917
+ * Root/Branch identity. The ledger is workspace-scoped and shared by the
142918
+ * PC GUI, hosted mobile API and isolated runtimes.
142919
+ */
142920
+ continuationStore(runtime, branchNodeIdOverride = "") {
142921
+ const workspace = runtime.target.workspace;
142922
+ if (!workspace?.path) return null;
142923
+ const workspaceId = String(workspace.id || workspace.path);
142924
+ const branchIdentity = this.runtimeBranchIdentity(runtime);
142925
+ const rootId = runtime.target.conversationId;
142926
+ const branchId = branchNodeIdOverride.includes("::") ? branchNodeIdOverride : `${rootId}::${branchNodeIdOverride || branchIdentity.branchNodeId || "main"}`;
142927
+ const store = new GuardedContinuationStore(workspace.path, workspaceId);
142928
+ store.ensureRoot(rootId, branchId);
142929
+ return { store, workspaceId, rootId, branchId };
142930
+ }
141576
142931
  enqueueNext(target, input) {
141577
142932
  const runtime = this.findRuntime(target);
141578
142933
  if (!runtime) throw new Error("Target conversation runtime is unavailable");
141579
- runtime.runId ||= (0, import_crypto18.randomUUID)();
142934
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141580
142935
  const id = String(input.id || "").trim().slice(0, 200);
141581
142936
  const text3 = String(input.text || "").trim();
141582
142937
  if (!id || !text3) throw new Error("Queue item id and text are required");
@@ -141585,8 +142940,50 @@ var ConversationKernel = class {
141585
142940
  const prompt = `[Next queued while current turn is running]
141586
142941
  ${text3}`;
141587
142942
  const createdAt = String(input.createdAt || (/* @__PURE__ */ new Date()).toISOString());
142943
+ const capturedBranch = this.runtimeBranchIdentity(runtime);
142944
+ const branchPath = Array.isArray(input.branchPath) && input.branchPath.length ? input.branchPath.map((id2) => String(id2 || "")).filter(Boolean) : capturedBranch.branchPath;
142945
+ const branchNodeId = String(input.branchNodeId || branchPath[branchPath.length - 1] || capturedBranch.branchNodeId || "");
142946
+ const targetRuntimeKey = String(input.targetRuntimeKey || runtime.target.runtimeKey).trim() || runtime.target.runtimeKey;
142947
+ const workspaceKey = runtime.target.workspaceKey;
142948
+ const modelSelection = String(input.modelSelection || runtime.options.model || "").trim() || void 0;
142949
+ const continuation = this.continuationStore(runtime, branchNodeId);
142950
+ const ledgerBranchId = continuation?.branchId;
142951
+ let buildId = "";
142952
+ if (continuation) {
142953
+ const authoritative = continuation.store.snapshot({
142954
+ workspaceId: continuation.workspaceId,
142955
+ rootId: continuation.rootId,
142956
+ branchId: continuation.branchId
142957
+ });
142958
+ const receipt = continuation.store.enqueueBuild({
142959
+ schemaVersion: 1,
142960
+ type: "ENQUEUE_BUILD",
142961
+ commandId: id,
142962
+ actorId: "kernel",
142963
+ target: {
142964
+ workspaceId: continuation.workspaceId,
142965
+ expectedRootId: continuation.rootId,
142966
+ branchId: continuation.branchId
142967
+ },
142968
+ expectedTailBuildId: authoritative.tailBuildId,
142969
+ expectedQueueRevision: authoritative.queueRevision,
142970
+ input: {
142971
+ text: text3,
142972
+ images: input.images,
142973
+ requestedMode: input.requestedMode,
142974
+ goalObjective: input.goalObjective,
142975
+ modelSelection,
142976
+ branchNodeId: branchNodeId || void 0,
142977
+ branchPath: branchPath.length ? branchPath : void 0
142978
+ },
142979
+ recipeSnapshotId: `${continuation.rootId}:${continuation.branchId}:${modelSelection || "auto"}`,
142980
+ createdAt
142981
+ });
142982
+ buildId = receipt.buildId;
142983
+ }
141588
142984
  runtime.pendingNextTurn.push({
141589
142985
  message: {
142986
+ buildId: buildId || void 0,
141590
142987
  text: prompt,
141591
142988
  visibleUserInput: text3,
141592
142989
  visibleMode: String(input.requestedMode || "build"),
@@ -141594,11 +142991,18 @@ ${text3}`;
141594
142991
  images: Array.isArray(input.images) ? input.images.slice(0, 6).map((image) => ({ ...image })) : void 0,
141595
142992
  clientMessageId: id,
141596
142993
  runId: runtime.runId,
142994
+ branchNodeId: branchNodeId || void 0,
142995
+ branchPath: branchPath.length ? branchPath : void 0,
142996
+ ledgerBranchId,
142997
+ targetRuntimeKey,
142998
+ workspaceKey,
142999
+ modelSelection,
141597
143000
  createdAt
141598
143001
  },
141599
143002
  queueMode: "followUp"
141600
143003
  });
141601
143004
  runtime.runner.retainConversationContinuations([{
143005
+ buildId: buildId || void 0,
141602
143006
  content: prompt,
141603
143007
  queueMode: "followUp",
141604
143008
  clientMessageId: id,
@@ -141607,7 +143011,13 @@ ${text3}`;
141607
143011
  images: input.images,
141608
143012
  visibleUserInput: text3,
141609
143013
  visibleMode: String(input.requestedMode || "build"),
141610
- goalObjective: input.goalObjective
143014
+ goalObjective: input.goalObjective,
143015
+ branchNodeId: branchNodeId || void 0,
143016
+ branchPath: branchPath.length ? branchPath : void 0,
143017
+ ledgerBranchId,
143018
+ targetRuntimeKey,
143019
+ workspaceKey,
143020
+ modelSelection
141611
143021
  }]);
141612
143022
  this.trackQueuedMessage(runtime, prompt, "followUp");
141613
143023
  this.emitQueueUpdate(runtime);
@@ -141623,12 +143033,34 @@ ${text3}`;
141623
143033
  const pending3 = runtime.pendingNextTurn.find((item) => typeof item.message !== "string" && item.message.clientMessageId === id);
141624
143034
  if (!pending3 || typeof pending3.message === "string") throw new Error("Queue item is no longer editable");
141625
143035
  const previous = runtime.runner.conversationContinuations().find((item) => item.clientMessageId === id);
141626
- pending3.message.text = `[Next queued while current turn is running]
143036
+ const nextText = `[Next queued while current turn is running]
141627
143037
  ${text3}`;
143038
+ const nextVisibleMode = input.requestedMode !== void 0 ? input.requestedMode : pending3.message.visibleMode;
143039
+ const nextGoalObjective = input.goalObjective !== void 0 ? input.goalObjective : pending3.message.goalObjective;
143040
+ const nextImages = input.images !== void 0 ? input.images.map((image) => ({ ...image })) : pending3.message.images?.map((image) => ({ ...image }));
143041
+ const continuation = this.continuationStore(runtime, pending3.message.ledgerBranchId || pending3.message.branchNodeId);
143042
+ if (continuation && pending3.message.buildId) {
143043
+ continuation.store.updateQueuedBuild({
143044
+ workspaceId: continuation.workspaceId,
143045
+ rootId: continuation.rootId,
143046
+ branchId: continuation.branchId,
143047
+ buildId: pending3.message.buildId,
143048
+ input: {
143049
+ text: text3,
143050
+ images: nextImages,
143051
+ requestedMode: nextVisibleMode,
143052
+ goalObjective: nextGoalObjective,
143053
+ modelSelection: pending3.message.modelSelection,
143054
+ branchNodeId: pending3.message.branchNodeId,
143055
+ branchPath: pending3.message.branchPath
143056
+ }
143057
+ });
143058
+ }
143059
+ pending3.message.text = nextText;
141628
143060
  pending3.message.visibleUserInput = text3;
141629
- if (input.requestedMode !== void 0) pending3.message.visibleMode = input.requestedMode;
141630
- if (input.goalObjective !== void 0) pending3.message.goalObjective = input.goalObjective;
141631
- if (input.images !== void 0) pending3.message.images = input.images.map((image) => ({ ...image }));
143061
+ pending3.message.visibleMode = nextVisibleMode;
143062
+ pending3.message.goalObjective = nextGoalObjective;
143063
+ pending3.message.images = nextImages;
141632
143064
  runtime.runner.retainConversationContinuations([{
141633
143065
  ...previous,
141634
143066
  content: pending3.message.text,
@@ -141638,7 +143070,12 @@ ${text3}`;
141638
143070
  images: pending3.message.images,
141639
143071
  visibleUserInput: text3,
141640
143072
  visibleMode: pending3.message.visibleMode,
141641
- goalObjective: pending3.message.goalObjective
143073
+ goalObjective: pending3.message.goalObjective,
143074
+ branchNodeId: pending3.message.branchNodeId,
143075
+ branchPath: pending3.message.branchPath,
143076
+ targetRuntimeKey: pending3.message.targetRuntimeKey,
143077
+ workspaceKey: pending3.message.workspaceKey,
143078
+ modelSelection: pending3.message.modelSelection
141642
143079
  }]);
141643
143080
  this.emitQueueUpdate(runtime);
141644
143081
  return this.queueItems(runtime.target).find((item) => item.id === id);
@@ -141649,7 +143086,19 @@ ${text3}`;
141649
143086
  const id = String(idInput || "").trim();
141650
143087
  const index2 = runtime.pendingNextTurn.findIndex((item) => typeof item.message !== "string" && item.message.clientMessageId === id);
141651
143088
  if (index2 < 0) return false;
141652
- const [removed] = runtime.pendingNextTurn.splice(index2, 1);
143089
+ const removed = runtime.pendingNextTurn[index2];
143090
+ if (typeof removed.message !== "string") {
143091
+ const continuation = this.continuationStore(runtime, removed.message.ledgerBranchId || removed.message.branchNodeId);
143092
+ if (continuation && removed.message.buildId) {
143093
+ continuation.store.deleteQueuedBuild({
143094
+ workspaceId: continuation.workspaceId,
143095
+ rootId: continuation.rootId,
143096
+ branchId: continuation.branchId,
143097
+ buildId: removed.message.buildId
143098
+ });
143099
+ }
143100
+ }
143101
+ runtime.pendingNextTurn.splice(index2, 1);
141653
143102
  if (typeof removed.message !== "string") {
141654
143103
  runtime.runner.consumeConversationContinuation({ content: removed.message.text, queueMode: removed.queueMode, clientMessageId: id });
141655
143104
  }
@@ -141672,6 +143121,26 @@ ${text3}`;
141672
143121
  if (item.queueMode !== "followUp" || typeof item.message === "string" || !item.message.clientMessageId) return [];
141673
143122
  return [[String(item.message.clientMessageId), item]];
141674
143123
  }));
143124
+ const firstOrdered = pendingById.get(orderedIds[0] || "");
143125
+ const continuation = this.continuationStore(
143126
+ runtime,
143127
+ firstOrdered && typeof firstOrdered.message !== "string" ? firstOrdered.message.ledgerBranchId || firstOrdered.message.branchNodeId || "" : ""
143128
+ );
143129
+ if (continuation) {
143130
+ const orderedBuildIds = orderedIds.map((id) => {
143131
+ const item = pendingById.get(id);
143132
+ return item && typeof item.message !== "string" ? item.message.buildId : void 0;
143133
+ }).filter((id) => !!id);
143134
+ if (orderedBuildIds.length !== orderedIds.length) {
143135
+ throw new Error("A queued build id is missing from the authoritative ledger projection");
143136
+ }
143137
+ continuation.store.reorderQueuedBuilds({
143138
+ workspaceId: continuation.workspaceId,
143139
+ rootId: continuation.rootId,
143140
+ branchId: continuation.branchId,
143141
+ orderedBuildIds
143142
+ });
143143
+ }
141675
143144
  const reorderedPending = orderedIds.map((id) => pendingById.get(id));
141676
143145
  let nextIndex = 0;
141677
143146
  runtime.pendingNextTurn = runtime.pendingNextTurn.map((item) => {
@@ -141694,6 +143163,35 @@ ${text3}`;
141694
143163
  }
141695
143164
  return runtime.queuePaused;
141696
143165
  }
143166
+ /**
143167
+ * dev-0.6.4 hotfix: 显式修复被失败前置阻断的排队行。
143168
+ *
143169
+ * 0.6.3 的合约是「失败/取消阻断后继,且不静默跳过」,所以这里不挂在恢复动作上
143170
+ * 自动执行;它必须由用户的显式动作触发(界面上的“修复受阻队列”按钮)。每一次
143171
+ * 改挂都写入 `BuildQueueRepaired` 事件并发布可见状态,触发者与原因可审计。
143172
+ */
143173
+ repairBlockedQueueNow(runtime) {
143174
+ const continuation = this.continuationStore(runtime);
143175
+ if (!continuation) return 0;
143176
+ try {
143177
+ const result = continuation.store.repairBlockedQueue({
143178
+ workspaceId: continuation.workspaceId,
143179
+ rootId: continuation.rootId,
143180
+ branchId: continuation.branchId,
143181
+ reason: "explicit-user-repair"
143182
+ });
143183
+ if (result.repaired.length) {
143184
+ runtime.runner.recordWorkStatus(
143185
+ `${result.repaired.length} queued row(s) blocked by a failed predecessor were re-anchored to the last committed build; the queue resumes in order.`
143186
+ );
143187
+ this.schedulePendingRuntimeContinuation(runtime, runtime.runId);
143188
+ }
143189
+ return result.repaired.length;
143190
+ } catch (error2) {
143191
+ runtime.runner.recordWorkStatus(`Queue repair failed: ${error2 instanceof Error ? error2.message : String(error2)}`);
143192
+ return 0;
143193
+ }
143194
+ }
141697
143195
  queueAction(target, action, input = {}) {
141698
143196
  const normalized = this.normalizeTarget(target);
141699
143197
  const runtime = this.findRuntime(normalized) || this.runtime(normalized, {
@@ -141703,7 +143201,7 @@ ${text3}`;
141703
143201
  inputMode: this.host.inputMode,
141704
143202
  engine: this.host.engine
141705
143203
  });
141706
- runtime.runId ||= (0, import_crypto18.randomUUID)();
143204
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141707
143205
  let receipt;
141708
143206
  if (action === "enqueue") {
141709
143207
  this.enqueueNext(runtime.target, {
@@ -141712,7 +143210,11 @@ ${text3}`;
141712
143210
  requestedMode: input.requestedMode,
141713
143211
  goalObjective: input.goalObjective,
141714
143212
  createdAt: input.createdAt,
141715
- images: input.images
143213
+ images: input.images,
143214
+ branchNodeId: input.branchNodeId,
143215
+ branchPath: input.branchPath,
143216
+ modelSelection: input.modelSelection,
143217
+ targetRuntimeKey: input.targetRuntimeKey
141716
143218
  });
141717
143219
  } else if (action === "update") {
141718
143220
  this.updateQueueItem(runtime.target, String(input.id || ""), String(input.text || ""), input);
@@ -141724,13 +143226,15 @@ ${text3}`;
141724
143226
  this.setQueuePaused(runtime.target, !runtime.queuePaused);
141725
143227
  } else if (action === "set_pause") {
141726
143228
  this.setQueuePaused(runtime.target, input.paused === true);
143229
+ } else if (action === "repair_blocked") {
143230
+ this.repairBlockedQueueNow(runtime);
141727
143231
  } else if (action === "guide") {
141728
143232
  if (input.text !== void 0) this.updateQueueItem(runtime.target, String(input.id || ""), input.text, input);
141729
143233
  const item = this.queueItems(runtime.target).find((entry) => entry.id === String(input.id || ""));
141730
143234
  if (!item) throw new Error("Queue item was not found");
141731
143235
  receipt = this.enqueueGuide({
141732
143236
  clientMessageId: item.id,
141733
- guideId: (0, import_crypto18.randomUUID)(),
143237
+ guideId: (0, import_crypto19.randomUUID)(),
141734
143238
  target: runtime.target,
141735
143239
  runId: runtime.runId,
141736
143240
  deliveryMode: "steer",
@@ -141782,7 +143286,7 @@ ${item.goalObjective}` : item.text,
141782
143286
  if (!runtime && runner.conversationContinuations().length) {
141783
143287
  runtime = this.runtime(normalized, { mode: runner.mode, model: runner.modelSelectionValue(), intelligence: runner.intelligence, inputMode: runner.inputMode, engine: runner.engine }, runner);
141784
143288
  runtime.queuePaused = true;
141785
- runtime.runId ||= (0, import_crypto18.randomUUID)();
143289
+ runtime.runId ||= (0, import_crypto19.randomUUID)();
141786
143290
  }
141787
143291
  const conversationSnapshot = runner.getConversationSnapshot(normalized.conversationId, options);
141788
143292
  return {
@@ -142208,7 +143712,7 @@ ${item.goalObjective}` : item.text,
142208
143712
  const active = this.findRuntime(normalized);
142209
143713
  if (active?.preparingArchive) throw new Error("This conversation is being archived");
142210
143714
  if (active?.activePromise) {
142211
- this.enqueueSameSession(active, message, queueMode);
143715
+ this.enqueueSameSession(active, message, queueMode, options.model);
142212
143716
  this.activateAcceptedGoal(active, typeof message === "string" ? "" : message.goalObjective);
142213
143717
  return active.activePromise;
142214
143718
  }
@@ -142218,7 +143722,7 @@ ${item.goalObjective}` : item.text,
142218
143722
  runtime.generation = (this.generations.get(runtime.runtimeKey) || runtime.generation || 0) + 1;
142219
143723
  this.generations.set(runtime.runtimeKey, runtime.generation);
142220
143724
  const requestedRunId = typeof message === "string" ? "" : String(message.runId || "").trim().slice(0, 200);
142221
- runtime.runId = requestedRunId || (0, import_crypto18.randomUUID)();
143725
+ runtime.runId = requestedRunId || (0, import_crypto19.randomUUID)();
142222
143726
  runtime.stopRequestedRunId = "";
142223
143727
  runtime.forceStopArmedRunId = "";
142224
143728
  runtime.stopCheckpointed = false;
@@ -142318,10 +143822,12 @@ ${item.goalObjective}` : item.text,
142318
143822
  return this.result(runtime, lastTokens);
142319
143823
  }
142320
143824
  for (; ; ) {
142321
- while (!runtime.queuePaused && runtime.pendingNextTurn.length > 0) {
143825
+ while (!runtime.queuePaused) {
142322
143826
  if (runtime.stopRequestedRunId === runtime.runId) return this.result(runtime, lastTokens);
142323
- const next2 = runtime.pendingNextTurn.shift();
142324
- if (next2.queueMode === "steer" && typeof next2.message !== "string" && !!next2.message.clientMessageId) {
143827
+ const steerIndex = runtime.pendingNextTurn.findIndex((item) => item.queueMode === "steer");
143828
+ if (steerIndex < 0) break;
143829
+ const next2 = runtime.pendingNextTurn.splice(steerIndex, 1)[0];
143830
+ if (typeof next2.message !== "string" && !!next2.message.clientMessageId) {
142325
143831
  const batchGuides = [];
142326
143832
  const pushGuide = (message2) => {
142327
143833
  batchGuides.push({
@@ -142333,8 +143839,10 @@ ${item.goalObjective}` : item.text,
142333
143839
  });
142334
143840
  };
142335
143841
  pushGuide(next2.message);
142336
- while (runtime.pendingNextTurn.length > 0 && runtime.pendingNextTurn[0].queueMode === "steer" && typeof runtime.pendingNextTurn[0].message !== "string" && !!runtime.pendingNextTurn[0].message.clientMessageId) {
142337
- const guide = runtime.pendingNextTurn.shift();
143842
+ while (true) {
143843
+ const guideIndex = runtime.pendingNextTurn.findIndex((item) => item.queueMode === "steer" && typeof item.message !== "string" && !!item.message.clientMessageId);
143844
+ if (guideIndex < 0) break;
143845
+ const guide = runtime.pendingNextTurn.splice(guideIndex, 1)[0];
142338
143846
  pushGuide(guide.message);
142339
143847
  }
142340
143848
  if (batchGuides.length === 1) {
@@ -142352,21 +143860,9 @@ ${batchText}`,
142352
143860
  lastTokens = await this.runSingle(runtime, batchMessage, "steer");
142353
143861
  if (this.repeatedAutomaticAssistant(runtime, batchMessage, "steer")) break;
142354
143862
  } else {
142355
- const drained = this.drainQueuedFollowUpMessage(next2.message);
142356
- lastTokens = await this.runPendingQueueItem(runtime, next2, async () => {
142357
- if (typeof drained !== "string" && drained.visibleMode && ["build", "chat", "plan", "goal"].includes(drained.visibleMode)) {
142358
- runtime.runner.setMode(drained.visibleMode);
142359
- runtime.options.mode = drained.visibleMode;
142360
- }
142361
- this.activateAcceptedGoal(runtime, typeof drained === "string" ? "" : drained.goalObjective);
142362
- return this.runSingle(
142363
- runtime,
142364
- drained,
142365
- next2.queueMode,
142366
- typeof next2.message === "string" ? void 0 : next2.message.clientMessageId
142367
- );
142368
- });
142369
- if (this.repeatedAutomaticAssistant(runtime, drained, next2.queueMode)) break;
143863
+ lastTokens = await this.runSingle(runtime, next2.message, next2.queueMode);
143864
+ if (this.repeatedAutomaticAssistant(runtime, next2.message, next2.queueMode)) break;
143865
+ continue;
142370
143866
  }
142371
143867
  }
142372
143868
  const rootMessage = runtime.runner.subagents.readRootInbox()[0];
@@ -142379,8 +143875,8 @@ ${batchText}`,
142379
143875
  if (!runtime.pendingNextTurn.length) this.clearQueued(runtime);
142380
143876
  const completedRunId = runtime.runId;
142381
143877
  runtime.runner.finishConversationWorkRun(completedRunId, "completed");
142382
- await new Promise((resolve15) => setImmediate(resolve15));
142383
- if (runtime.runId === completedRunId && runtime.stopRequestedRunId !== completedRunId && !runtime.queuePaused && runtime.pendingNextTurn.length > 0) {
143878
+ await new Promise((resolve16) => setImmediate(resolve16));
143879
+ if (runtime.runId === completedRunId && runtime.stopRequestedRunId !== completedRunId && !runtime.queuePaused && runtime.pendingNextTurn.some((item) => item.queueMode === "steer")) {
142384
143880
  runtime.guideAcceptanceClosedRunId = "";
142385
143881
  if (!runtime.runner.resumeConversationWorkRun(completedRunId)) {
142386
143882
  throw new Error(`Unable to resume deferred Guide work run ${completedRunId}`);
@@ -142551,6 +144047,12 @@ Review this persisted peer result and summarize or continue the parent task as n
142551
144047
  visibleUserInput: continuation.visibleUserInput,
142552
144048
  visibleMode: continuation.visibleMode,
142553
144049
  goalObjective: continuation.goalObjective,
144050
+ buildId: continuation.buildId,
144051
+ modelSelection: continuation.modelSelection,
144052
+ branchNodeId: continuation.branchNodeId,
144053
+ branchPath: continuation.branchPath?.slice(),
144054
+ targetRuntimeKey: continuation.targetRuntimeKey,
144055
+ workspaceKey: continuation.workspaceKey,
142554
144056
  createdAt: continuation.createdAt,
142555
144057
  hiddenUserInput: continuation.hiddenUserInput
142556
144058
  } : continuation.content,
@@ -142637,10 +144139,90 @@ Review this persisted peer result and summarize or continue the parent task as n
142637
144139
  setImmediate(() => {
142638
144140
  runtime.pendingContinuationRunId = void 0;
142639
144141
  if (runtime.preparingArchive || runtime.runId !== runId || runtime.activePromise || runtime.externalOwner || runtime.stopRequestedRunId === runId || runtime.queuePaused) return;
142640
- const next2 = runtime.pendingNextTurn.shift();
144142
+ const next2 = runtime.pendingNextTurn[0];
142641
144143
  if (!next2) return;
142642
- const delivery = next2.queueMode === "followUp" ? this.drainQueuedFollowUpMessage(next2.message) : next2.message;
142643
- const message = typeof delivery === "string" ? { text: delivery, runId } : { ...delivery, runId: delivery.runId || runId };
144144
+ const queued = typeof next2.message === "string" ? null : next2.message;
144145
+ if (queued?.targetRuntimeKey && queued.targetRuntimeKey !== runtime.target.runtimeKey) {
144146
+ runtime.queuePaused = true;
144147
+ runtime.runner.recordWorkStatus("Queued turn target mismatch; the queue is paused instead of running in another conversation.");
144148
+ this.emitQueueUpdate(runtime);
144149
+ return;
144150
+ }
144151
+ runtime.pendingNextTurn.shift();
144152
+ if (next2.queueMode === "followUp") {
144153
+ const delivery = this.drainQueuedFollowUpMessage(next2.message);
144154
+ const message2 = typeof delivery === "string" ? { text: delivery } : { ...delivery, runId: void 0 };
144155
+ const continuation = this.continuationStore(runtime);
144156
+ let scope = null;
144157
+ void this.runPendingQueueItem(runtime, next2, async () => {
144158
+ this.bindQueuedTurnBranch(runtime, queued);
144159
+ if (queued?.modelSelection) runtime.options.model = queued.modelSelection;
144160
+ if (message2.visibleMode && ["build", "chat", "plan", "goal"].includes(message2.visibleMode)) {
144161
+ this.setMode(runtime.target, message2.visibleMode);
144162
+ }
144163
+ this.activateAcceptedGoal(runtime, message2.goalObjective || "");
144164
+ if (continuation && queued?.buildId) {
144165
+ const authoritative = continuation.store.snapshot({
144166
+ workspaceId: continuation.workspaceId,
144167
+ rootId: continuation.rootId,
144168
+ branchId: continuation.branchId
144169
+ });
144170
+ const ready = authoritative.builds.filter((build2) => build2.status === "QUEUED").sort((a, b) => a.queueSequence - b.queueSequence)[0];
144171
+ if (ready && ready.buildId !== queued.buildId) {
144172
+ runtime.pendingNextTurn.unshift(next2);
144173
+ runtime.runner.recordWorkStatus("Queued turn is waiting for the authoritative predecessor.");
144174
+ this.emitQueueUpdate(runtime);
144175
+ return this.result(runtime, []);
144176
+ }
144177
+ scope = continuation.store.claimBuild({
144178
+ workspaceId: continuation.workspaceId,
144179
+ rootId: continuation.rootId,
144180
+ branchId: continuation.branchId,
144181
+ workerCapability: `kernel:${process.pid}`
144182
+ });
144183
+ if (scope && scope.buildId !== queued.buildId) {
144184
+ continuation.store.failBuild({ scope, reason: "Authoritative build mismatch during claim" });
144185
+ scope = null;
144186
+ }
144187
+ if (!scope) {
144188
+ runtime.pendingNextTurn.unshift(next2);
144189
+ runtime.runner.recordWorkStatus("Queued turn is not ready for execution yet.");
144190
+ this.emitQueueUpdate(runtime);
144191
+ return this.result(runtime, []);
144192
+ }
144193
+ }
144194
+ const result = await this.prompt(message2, runtime.target, runtime.options, "followUp");
144195
+ if (continuation && scope) {
144196
+ continuation.store.commitFinal({
144197
+ scope,
144198
+ text: result.tokens.map((token) => token.text || "").join("")
144199
+ });
144200
+ }
144201
+ return result;
144202
+ }, (accepted, error2) => {
144203
+ if (!continuation || !scope) return;
144204
+ const reason = error2 instanceof Error ? error2.message : String(error2);
144205
+ if (accepted) {
144206
+ try {
144207
+ continuation.store.failBuild({ scope, reason });
144208
+ } catch {
144209
+ }
144210
+ } else {
144211
+ try {
144212
+ continuation.store.requeueBuild({
144213
+ workspaceId: continuation.workspaceId,
144214
+ rootId: continuation.rootId,
144215
+ branchId: continuation.branchId,
144216
+ buildId: scope.buildId
144217
+ });
144218
+ } catch {
144219
+ }
144220
+ }
144221
+ }).catch(() => {
144222
+ });
144223
+ return;
144224
+ }
144225
+ const message = typeof next2.message === "string" ? { text: next2.message, runId } : { ...next2.message, runId: next2.message.runId || runId };
142644
144226
  void this.runPendingQueueItem(runtime, next2, async () => {
142645
144227
  if (message.visibleMode && ["build", "chat", "plan", "goal"].includes(message.visibleMode)) {
142646
144228
  this.setMode(runtime.target, message.visibleMode);
@@ -142650,7 +144232,24 @@ Review this persisted peer result and summarize or continue the parent task as n
142650
144232
  });
142651
144233
  });
142652
144234
  }
142653
- async runPendingQueueItem(runtime, next2, execute) {
144235
+ /**
144236
+ * Restore the runtime branch captured by a queued user turn. If the branch
144237
+ * disappeared (manual deletion/rewind), fail the queued item into the
144238
+ * existing pause/retry path instead of appending it to a different branch.
144239
+ */
144240
+ bindQueuedTurnBranch(runtime, message) {
144241
+ const branchNodeId = String(message?.branchNodeId || "").trim();
144242
+ if (!branchNodeId) return;
144243
+ const snapshot2 = runtime.runner.getConversationSnapshot(runtime.id);
144244
+ const currentBranch = String(snapshot2.runtimeBranchId || snapshot2.activeBranchId || "");
144245
+ if (currentBranch === branchNodeId) return;
144246
+ try {
144247
+ runtime.runner.switchConversationBranch(runtime.id, branchNodeId);
144248
+ } catch (error2) {
144249
+ throw new Error(`Queued turn branch ${branchNodeId} is unavailable: ${error2 instanceof Error ? error2.message : String(error2)}`);
144250
+ }
144251
+ }
144252
+ async runPendingQueueItem(runtime, next2, execute, onFailure) {
142654
144253
  const queuedMessage = typeof next2.message === "string" ? void 0 : next2.message;
142655
144254
  const id = queuedMessage?.clientMessageId;
142656
144255
  if (next2.queueMode !== "followUp" || !id) return execute();
@@ -142662,6 +144261,10 @@ Review this persisted peer result and summarize or continue the parent task as n
142662
144261
  return await execute();
142663
144262
  } catch (error2) {
142664
144263
  runtime.queuePaused = true;
144264
+ try {
144265
+ onFailure?.(accepted, error2);
144266
+ } catch {
144267
+ }
142665
144268
  throw error2;
142666
144269
  } finally {
142667
144270
  unsubscribe();
@@ -142820,14 +144423,27 @@ Review this persisted peer result and summarize or continue the parent task as n
142820
144423
  guides: (run.guides || []).map(bindGuide)
142821
144424
  }));
142822
144425
  }
142823
- enqueueSameSession(runtime, message, queueMode) {
144426
+ enqueueSameSession(runtime, message, queueMode, requestedModel = "") {
142824
144427
  const isSteer = queueMode === "steer";
142825
144428
  const text3 = typeof message === "string" ? message : message.text;
142826
144429
  const prompt = isSteer ? text3 : `[Next queued while current turn is running]
142827
144430
  ${text3}`;
142828
144431
  if (!isSteer) {
142829
144432
  const structured = typeof message === "string" ? null : message;
142830
- const clientMessageId = String(structured?.clientMessageId || (0, import_crypto18.randomUUID)());
144433
+ const requestedRuntimeKey = String(structured?.targetRuntimeKey || "").trim();
144434
+ if (requestedRuntimeKey && requestedRuntimeKey !== runtime.target.runtimeKey) {
144435
+ throw new Error(`Queued message target mismatch: expected ${requestedRuntimeKey}, received ${runtime.target.runtimeKey}`);
144436
+ }
144437
+ const clientMessageId = String(structured?.clientMessageId || (0, import_crypto19.randomUUID)());
144438
+ const capturedBranch = this.runtimeBranchIdentity(runtime);
144439
+ const branchPath = Array.isArray(structured?.branchPath) && structured.branchPath.length ? structured.branchPath.map((id) => String(id || "")).filter(Boolean) : capturedBranch.branchPath;
144440
+ const branchNodeId = String(structured?.branchNodeId || branchPath[branchPath.length - 1] || capturedBranch.branchNodeId || "");
144441
+ const targetRuntimeKey = runtime.target.runtimeKey;
144442
+ const workspaceKey = runtime.target.workspaceKey;
144443
+ const modelSelection = String(
144444
+ structured?.modelSelection || requestedModel || runtime.options.model || ""
144445
+ ).trim() || void 0;
144446
+ const ledgerBranchId = this.continuationStore(runtime, branchNodeId)?.branchId;
142831
144447
  const queuedMessage = {
142832
144448
  ...structured || {},
142833
144449
  text: prompt,
@@ -142835,6 +144451,12 @@ ${text3}`;
142835
144451
  visibleMode: structured?.visibleMode || runtime.options.mode,
142836
144452
  clientMessageId,
142837
144453
  runId: structured?.runId || runtime.runId,
144454
+ branchNodeId: branchNodeId || void 0,
144455
+ branchPath: branchPath.length ? branchPath : void 0,
144456
+ ledgerBranchId,
144457
+ targetRuntimeKey,
144458
+ workspaceKey,
144459
+ modelSelection,
142838
144460
  createdAt: String(structured?.createdAt || (/* @__PURE__ */ new Date()).toISOString())
142839
144461
  };
142840
144462
  if (!runtime.pendingNextTurn.some((item) => typeof item.message !== "string" && item.message.clientMessageId === clientMessageId)) {
@@ -142850,7 +144472,13 @@ ${text3}`;
142850
144472
  createdAt: queuedMessage.createdAt,
142851
144473
  visibleUserInput: queuedMessage.visibleUserInput,
142852
144474
  visibleMode: queuedMessage.visibleMode,
142853
- goalObjective: queuedMessage.goalObjective
144475
+ goalObjective: queuedMessage.goalObjective,
144476
+ branchNodeId: queuedMessage.branchNodeId,
144477
+ branchPath: queuedMessage.branchPath,
144478
+ ledgerBranchId: queuedMessage.ledgerBranchId,
144479
+ targetRuntimeKey,
144480
+ workspaceKey,
144481
+ modelSelection
142854
144482
  }]);
142855
144483
  this.trackQueuedMessage(runtime, prompt, "followUp");
142856
144484
  runtime.runner.recordWorkStatus(runtime.stopRequestedRunId === runtime.runId ? "Next message retained while stopping." : "Next message queued.");
@@ -142928,6 +144556,52 @@ ${text3}`;
142928
144556
  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);
142929
144557
  return runtime;
142930
144558
  }
144559
+ /**
144560
+ * Merge queue continuations persisted by another owner/kernel into this
144561
+ * runtime's in-memory projection. Flow takeover, cold restore and a pool
144562
+ * hand-off must not lose an already-admitted Next row. Deduplication is by
144563
+ * the stable clientMessageId, never by text.
144564
+ */
144565
+ reconcilePendingContinuations(runtime) {
144566
+ runtime.runner.setConversationFromStorage(runtime.id);
144567
+ const persisted = runtime.runner.conversationContinuations();
144568
+ const existingIds = /* @__PURE__ */ new Set();
144569
+ for (const item of runtime.pendingNextTurn) {
144570
+ if (typeof item.message === "string") continue;
144571
+ const id = String(item.message.clientMessageId || "").trim();
144572
+ if (id) existingIds.add(id);
144573
+ }
144574
+ let changed = false;
144575
+ for (const continuation of persisted) {
144576
+ if (continuation.queueMode !== "followUp" || !continuation.clientMessageId) continue;
144577
+ if (existingIds.has(continuation.clientMessageId)) continue;
144578
+ runtime.pendingNextTurn.push({
144579
+ message: {
144580
+ text: continuation.content,
144581
+ visibleUserInput: continuation.visibleUserInput,
144582
+ visibleMode: continuation.visibleMode,
144583
+ goalObjective: continuation.goalObjective,
144584
+ images: continuation.images?.map((image) => ({ ...image })),
144585
+ attachments: continuation.attachments?.map((attachment) => ({ ...attachment })),
144586
+ clientMessageId: continuation.clientMessageId,
144587
+ buildId: continuation.buildId,
144588
+ branchNodeId: continuation.branchNodeId,
144589
+ branchPath: continuation.branchPath?.slice(),
144590
+ targetRuntimeKey: continuation.targetRuntimeKey,
144591
+ workspaceKey: continuation.workspaceKey,
144592
+ modelSelection: continuation.modelSelection,
144593
+ createdAt: continuation.createdAt
144594
+ },
144595
+ queueMode: "followUp"
144596
+ });
144597
+ existingIds.add(continuation.clientMessageId);
144598
+ changed = true;
144599
+ }
144600
+ if (changed) {
144601
+ this.queueState(runtime);
144602
+ this.emitQueueUpdate(runtime);
144603
+ }
144604
+ }
142931
144605
  normalizeTarget(input) {
142932
144606
  if (typeof input !== "string") {
142933
144607
  const withWorkspace = input.workspace ? input : { ...input, workspace: this.workspaceForId(input.workspaceId) };