wildcrane-runner 0.6.104 → 0.6.106

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.
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.104 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.106 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -958,9 +958,9 @@ var require_timers = __commonJS({
958
958
  * before the specified function or code is executed.
959
959
  * @param {*} arg
960
960
  */
961
- constructor(callback, delay3, arg) {
961
+ constructor(callback, delay4, arg) {
962
962
  this._onTimeout = callback;
963
- this._idleTimeout = delay3;
963
+ this._idleTimeout = delay4;
964
964
  this._timerArg = arg;
965
965
  this.refresh();
966
966
  }
@@ -1005,8 +1005,8 @@ var require_timers = __commonJS({
1005
1005
  * when the timer expires.
1006
1006
  * @returns {NodeJS.Timeout|FastTimer}
1007
1007
  */
1008
- setTimeout(callback, delay3, arg) {
1009
- return delay3 <= RESOLUTION_MS ? setTimeout(callback, delay3, arg) : new FastTimer(callback, delay3, arg);
1008
+ setTimeout(callback, delay4, arg) {
1009
+ return delay4 <= RESOLUTION_MS ? setTimeout(callback, delay4, arg) : new FastTimer(callback, delay4, arg);
1010
1010
  },
1011
1011
  /**
1012
1012
  * The clearTimeout method cancels an instantiated Timer previously created
@@ -1032,8 +1032,8 @@ var require_timers = __commonJS({
1032
1032
  * when the timer expires.
1033
1033
  * @returns {FastTimer}
1034
1034
  */
1035
- setFastTimeout(callback, delay3, arg) {
1036
- return new FastTimer(callback, delay3, arg);
1035
+ setFastTimeout(callback, delay4, arg) {
1036
+ return new FastTimer(callback, delay4, arg);
1037
1037
  },
1038
1038
  /**
1039
1039
  * The clearTimeout method cancels an instantiated FastTimer previously
@@ -1059,8 +1059,8 @@ var require_timers = __commonJS({
1059
1059
  * @deprecated
1060
1060
  * @param {number} [delay=0] The delay in milliseconds to add to the now value.
1061
1061
  */
1062
- tick(delay3 = 0) {
1063
- fastNow += delay3 - RESOLUTION_MS + 1;
1062
+ tick(delay4 = 0) {
1063
+ fastNow += delay4 - RESOLUTION_MS + 1;
1064
1064
  onTick();
1065
1065
  onTick();
1066
1066
  },
@@ -1885,14 +1885,14 @@ var require_util = __commonJS({
1885
1885
  }
1886
1886
  const port = url.port != null ? url.port : url.protocol === "https:" ? 443 : 80;
1887
1887
  let origin = url.origin != null ? url.origin : `${url.protocol || ""}//${url.hostname || ""}:${port}`;
1888
- let path8 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1888
+ let path9 = url.path != null ? url.path : `${url.pathname || ""}${url.search || ""}`;
1889
1889
  if (origin[origin.length - 1] === "/") {
1890
1890
  origin = origin.slice(0, origin.length - 1);
1891
1891
  }
1892
- if (path8 && path8[0] !== "/") {
1893
- path8 = `/${path8}`;
1892
+ if (path9 && path9[0] !== "/") {
1893
+ path9 = `/${path9}`;
1894
1894
  }
1895
- return new URL(`${origin}${path8}`);
1895
+ return new URL(`${origin}${path9}`);
1896
1896
  }
1897
1897
  if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {
1898
1898
  throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -2727,9 +2727,9 @@ var require_diagnostics = __commonJS({
2727
2727
  "undici:client:sendHeaders",
2728
2728
  (evt) => {
2729
2729
  const {
2730
- request: { method, path: path8, origin }
2730
+ request: { method, path: path9, origin }
2731
2731
  } = evt;
2732
- debugLog("sending request to %s %s%s", method, origin, path8);
2732
+ debugLog("sending request to %s %s%s", method, origin, path9);
2733
2733
  }
2734
2734
  );
2735
2735
  }
@@ -2747,14 +2747,14 @@ var require_diagnostics = __commonJS({
2747
2747
  "undici:request:headers",
2748
2748
  (evt) => {
2749
2749
  const {
2750
- request: { method, path: path8, origin },
2750
+ request: { method, path: path9, origin },
2751
2751
  response: { statusCode }
2752
2752
  } = evt;
2753
2753
  debugLog(
2754
2754
  "received response to %s %s%s - HTTP %d",
2755
2755
  method,
2756
2756
  origin,
2757
- path8,
2757
+ path9,
2758
2758
  statusCode
2759
2759
  );
2760
2760
  }
@@ -2763,23 +2763,23 @@ var require_diagnostics = __commonJS({
2763
2763
  "undici:request:trailers",
2764
2764
  (evt) => {
2765
2765
  const {
2766
- request: { method, path: path8, origin }
2766
+ request: { method, path: path9, origin }
2767
2767
  } = evt;
2768
- debugLog("trailers received from %s %s%s", method, origin, path8);
2768
+ debugLog("trailers received from %s %s%s", method, origin, path9);
2769
2769
  }
2770
2770
  );
2771
2771
  diagnosticsChannel.subscribe(
2772
2772
  "undici:request:error",
2773
2773
  (evt) => {
2774
2774
  const {
2775
- request: { method, path: path8, origin },
2775
+ request: { method, path: path9, origin },
2776
2776
  error
2777
2777
  } = evt;
2778
2778
  debugLog(
2779
2779
  "request to %s %s%s errored - %s",
2780
2780
  method,
2781
2781
  origin,
2782
- path8,
2782
+ path9,
2783
2783
  error.message
2784
2784
  );
2785
2785
  }
@@ -2894,7 +2894,7 @@ var require_request = __commonJS({
2894
2894
  var kHandler = /* @__PURE__ */ Symbol("handler");
2895
2895
  var Request = class {
2896
2896
  constructor(origin, {
2897
- path: path8,
2897
+ path: path9,
2898
2898
  method,
2899
2899
  body,
2900
2900
  headers,
@@ -2911,11 +2911,11 @@ var require_request = __commonJS({
2911
2911
  maxRedirections,
2912
2912
  typeOfService
2913
2913
  }, handler) {
2914
- if (typeof path8 !== "string") {
2914
+ if (typeof path9 !== "string") {
2915
2915
  throw new InvalidArgumentError("path must be a string");
2916
- } else if (path8[0] !== "/" && !(path8.startsWith("http://") || path8.startsWith("https://")) && method !== "CONNECT") {
2916
+ } else if (path9[0] !== "/" && !(path9.startsWith("http://") || path9.startsWith("https://")) && method !== "CONNECT") {
2917
2917
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
2918
- } else if (invalidPathRegex.test(path8)) {
2918
+ } else if (invalidPathRegex.test(path9)) {
2919
2919
  throw new InvalidArgumentError("invalid request path");
2920
2920
  }
2921
2921
  if (typeof method !== "string") {
@@ -2990,7 +2990,7 @@ var require_request = __commonJS({
2990
2990
  this.completed = false;
2991
2991
  this.aborted = false;
2992
2992
  this.upgrade = upgrade || null;
2993
- this.path = query ? serializePathWithQuery(path8, query) : path8;
2993
+ this.path = query ? serializePathWithQuery(path9, query) : path9;
2994
2994
  this.origin = origin;
2995
2995
  this.protocol = getProtocolFromUrlString(origin);
2996
2996
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -7578,21 +7578,21 @@ var require_client_h1 = __commonJS({
7578
7578
  this.connection = "";
7579
7579
  this.maxResponseSize = client[kMaxResponseSize];
7580
7580
  }
7581
- setTimeout(delay3, type) {
7582
- if (delay3 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
7581
+ setTimeout(delay4, type) {
7582
+ if (delay4 !== this.timeoutValue || type & USE_FAST_TIMER ^ this.timeoutType & USE_FAST_TIMER) {
7583
7583
  if (this.timeout) {
7584
7584
  timers.clearTimeout(this.timeout);
7585
7585
  this.timeout = null;
7586
7586
  }
7587
- if (delay3) {
7587
+ if (delay4) {
7588
7588
  if (type & USE_FAST_TIMER) {
7589
- this.timeout = timers.setFastTimeout(onParserTimeout, delay3, this.timeoutWeakRef);
7589
+ this.timeout = timers.setFastTimeout(onParserTimeout, delay4, this.timeoutWeakRef);
7590
7590
  } else {
7591
- this.timeout = setTimeout(onParserTimeout, delay3, this.timeoutWeakRef);
7591
+ this.timeout = setTimeout(onParserTimeout, delay4, this.timeoutWeakRef);
7592
7592
  this.timeout?.unref();
7593
7593
  }
7594
7594
  }
7595
- this.timeoutValue = delay3;
7595
+ this.timeoutValue = delay4;
7596
7596
  } else if (this.timeout) {
7597
7597
  if (this.timeout.refresh) {
7598
7598
  this.timeout.refresh();
@@ -8234,7 +8234,7 @@ var require_client_h1 = __commonJS({
8234
8234
  }
8235
8235
  }
8236
8236
  function writeH1(client, request) {
8237
- const { method, path: path8, host, upgrade, blocking, reset } = request;
8237
+ const { method, path: path9, host, upgrade, blocking, reset } = request;
8238
8238
  let { body, headers, contentLength } = request;
8239
8239
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
8240
8240
  if (util.isFormDataLike(body)) {
@@ -8310,7 +8310,7 @@ var require_client_h1 = __commonJS({
8310
8310
  socket[kBlocking] = true;
8311
8311
  }
8312
8312
  setTypeOfService(socket, request);
8313
- let header = `${method} ${path8} HTTP/1.1\r
8313
+ let header = `${method} ${path9} HTTP/1.1\r
8314
8314
  `;
8315
8315
  if (typeof host === "string") {
8316
8316
  header += `host: ${host}\r
@@ -8987,7 +8987,7 @@ var require_client_h2 = __commonJS({
8987
8987
  const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout];
8988
8988
  const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout];
8989
8989
  const session = client[kHTTP2Session];
8990
- const { method, path: path8, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8990
+ const { method, path: path9, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8991
8991
  let { body } = request;
8992
8992
  if (upgrade != null && upgrade !== "websocket") {
8993
8993
  util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -9056,7 +9056,7 @@ var require_client_h2 = __commonJS({
9056
9056
  }
9057
9057
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
9058
9058
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
9059
- headers[HTTP2_HEADER_PATH] = path8;
9059
+ headers[HTTP2_HEADER_PATH] = path9;
9060
9060
  if (protocol === "ws:" || protocol === "wss:") {
9061
9061
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
9062
9062
  } else {
@@ -9108,7 +9108,7 @@ var require_client_h2 = __commonJS({
9108
9108
  stream.setTimeout(headersTimeout);
9109
9109
  return true;
9110
9110
  }
9111
- headers[HTTP2_HEADER_PATH] = path8;
9111
+ headers[HTTP2_HEADER_PATH] = path9;
9112
9112
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
9113
9113
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
9114
9114
  if (body && typeof body.read === "function") {
@@ -11464,10 +11464,10 @@ var require_proxy_agent = __commonJS({
11464
11464
  };
11465
11465
  const {
11466
11466
  origin,
11467
- path: path8 = "/",
11467
+ path: path9 = "/",
11468
11468
  headers = {}
11469
11469
  } = opts;
11470
- opts.path = origin + path8;
11470
+ opts.path = origin + path9;
11471
11471
  if (!("host" in headers) && !("Host" in headers)) {
11472
11472
  const { host } = new URL(origin);
11473
11473
  headers.host = host;
@@ -13627,20 +13627,20 @@ var require_mock_utils = __commonJS({
13627
13627
  }
13628
13628
  return normalizedQp;
13629
13629
  }
13630
- function safeUrl(path8) {
13631
- if (typeof path8 !== "string") {
13632
- return path8;
13630
+ function safeUrl(path9) {
13631
+ if (typeof path9 !== "string") {
13632
+ return path9;
13633
13633
  }
13634
- const pathSegments = path8.split("?", 3);
13634
+ const pathSegments = path9.split("?", 3);
13635
13635
  if (pathSegments.length !== 2) {
13636
- return path8;
13636
+ return path9;
13637
13637
  }
13638
13638
  const qp = new URLSearchParams(pathSegments.pop());
13639
13639
  qp.sort();
13640
13640
  return [...pathSegments, qp.toString()].join("?");
13641
13641
  }
13642
- function matchKey(mockDispatch2, { path: path8, method, body, headers }) {
13643
- const pathMatch = matchValue(mockDispatch2.path, path8);
13642
+ function matchKey(mockDispatch2, { path: path9, method, body, headers }) {
13643
+ const pathMatch = matchValue(mockDispatch2.path, path9);
13644
13644
  const methodMatch = matchValue(mockDispatch2.method, method);
13645
13645
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
13646
13646
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -13665,8 +13665,8 @@ var require_mock_utils = __commonJS({
13665
13665
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
13666
13666
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
13667
13667
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
13668
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path8, ignoreTrailingSlash }) => {
13669
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path8)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path8), resolvedPath);
13668
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path9, ignoreTrailingSlash }) => {
13669
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path9)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path9), resolvedPath);
13670
13670
  });
13671
13671
  if (matchedMockDispatches.length === 0) {
13672
13672
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -13705,19 +13705,19 @@ var require_mock_utils = __commonJS({
13705
13705
  mockDispatches.splice(index, 1);
13706
13706
  }
13707
13707
  }
13708
- function removeTrailingSlash(path8) {
13709
- while (path8.endsWith("/")) {
13710
- path8 = path8.slice(0, -1);
13708
+ function removeTrailingSlash(path9) {
13709
+ while (path9.endsWith("/")) {
13710
+ path9 = path9.slice(0, -1);
13711
13711
  }
13712
- if (path8.length === 0) {
13713
- path8 = "/";
13712
+ if (path9.length === 0) {
13713
+ path9 = "/";
13714
13714
  }
13715
- return path8;
13715
+ return path9;
13716
13716
  }
13717
13717
  function buildKey(opts) {
13718
- const { path: path8, method, body, headers, query } = opts;
13718
+ const { path: path9, method, body, headers, query } = opts;
13719
13719
  return {
13720
- path: path8,
13720
+ path: path9,
13721
13721
  method,
13722
13722
  body,
13723
13723
  headers,
@@ -13758,7 +13758,7 @@ var require_mock_utils = __commonJS({
13758
13758
  if (mockDispatch2.data.callback) {
13759
13759
  mockDispatch2.data = { ...mockDispatch2.data, ...mockDispatch2.data.callback(opts) };
13760
13760
  }
13761
- const { data: { statusCode, data, headers, trailers, error }, delay: delay3, persist } = mockDispatch2;
13761
+ const { data: { statusCode, data, headers, trailers, error }, delay: delay4, persist } = mockDispatch2;
13762
13762
  const { timesInvoked, times } = mockDispatch2;
13763
13763
  mockDispatch2.consumed = !persist && timesInvoked >= times;
13764
13764
  mockDispatch2.pending = timesInvoked < times;
@@ -13781,11 +13781,11 @@ var require_mock_utils = __commonJS({
13781
13781
  handler.onError(err);
13782
13782
  }
13783
13783
  handler.onConnect?.(abort, null);
13784
- if (typeof delay3 === "number" && delay3 > 0) {
13784
+ if (typeof delay4 === "number" && delay4 > 0) {
13785
13785
  timer = setTimeout(() => {
13786
13786
  timer = null;
13787
13787
  handleReply(this[kDispatches]);
13788
- }, delay3);
13788
+ }, delay4);
13789
13789
  } else {
13790
13790
  handleReply(this[kDispatches]);
13791
13791
  }
@@ -14407,10 +14407,10 @@ var require_pending_interceptors_formatter = __commonJS({
14407
14407
  }
14408
14408
  format(pendingInterceptors) {
14409
14409
  const withPrettyHeaders = pendingInterceptors.map(
14410
- ({ method, path: path8, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
14410
+ ({ method, path: path9, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
14411
14411
  Method: method,
14412
14412
  Origin: origin,
14413
- Path: path8,
14413
+ Path: path9,
14414
14414
  "Status code": statusCode,
14415
14415
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
14416
14416
  Invocations: timesInvoked,
@@ -14492,9 +14492,9 @@ var require_mock_agent = __commonJS({
14492
14492
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
14493
14493
  const dispatchOpts = { ...opts };
14494
14494
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
14495
- const [path8, searchParams] = dispatchOpts.path.split("?");
14495
+ const [path9, searchParams] = dispatchOpts.path.split("?");
14496
14496
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
14497
- dispatchOpts.path = `${path8}?${normalizedSearchParams}`;
14497
+ dispatchOpts.path = `${path9}?${normalizedSearchParams}`;
14498
14498
  }
14499
14499
  return this[kAgent].dispatch(dispatchOpts, handler);
14500
14500
  }
@@ -14895,12 +14895,12 @@ var require_snapshot_recorder = __commonJS({
14895
14895
  * @return {Promise<void>} - Resolves when snapshots are loaded
14896
14896
  */
14897
14897
  async loadSnapshots(filePath) {
14898
- const path8 = filePath || this.#snapshotPath;
14899
- if (!path8) {
14898
+ const path9 = filePath || this.#snapshotPath;
14899
+ if (!path9) {
14900
14900
  throw new InvalidArgumentError("Snapshot path is required");
14901
14901
  }
14902
14902
  try {
14903
- const data = await readFile(resolve(path8), "utf8");
14903
+ const data = await readFile(resolve(path9), "utf8");
14904
14904
  const parsed = JSON.parse(data);
14905
14905
  if (Array.isArray(parsed)) {
14906
14906
  this.#snapshots.clear();
@@ -14914,7 +14914,7 @@ var require_snapshot_recorder = __commonJS({
14914
14914
  if (error.code === "ENOENT") {
14915
14915
  this.#snapshots.clear();
14916
14916
  } else {
14917
- throw new UndiciError(`Failed to load snapshots from ${path8}`, { cause: error });
14917
+ throw new UndiciError(`Failed to load snapshots from ${path9}`, { cause: error });
14918
14918
  }
14919
14919
  }
14920
14920
  }
@@ -14925,11 +14925,11 @@ var require_snapshot_recorder = __commonJS({
14925
14925
  * @returns {Promise<void>} - Resolves when snapshots are saved
14926
14926
  */
14927
14927
  async saveSnapshots(filePath) {
14928
- const path8 = filePath || this.#snapshotPath;
14929
- if (!path8) {
14928
+ const path9 = filePath || this.#snapshotPath;
14929
+ if (!path9) {
14930
14930
  throw new InvalidArgumentError("Snapshot path is required");
14931
14931
  }
14932
- const resolvedPath = resolve(path8);
14932
+ const resolvedPath = resolve(path9);
14933
14933
  await mkdir(dirname(resolvedPath), { recursive: true });
14934
14934
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
14935
14935
  hash,
@@ -15570,15 +15570,15 @@ var require_redirect_handler = __commonJS({
15570
15570
  receivedAt: Date.now()
15571
15571
  });
15572
15572
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
15573
- const path8 = search ? `${pathname}${search}` : pathname;
15574
- const redirectUrlString = `${origin}${path8}`;
15573
+ const path9 = search ? `${pathname}${search}` : pathname;
15574
+ const redirectUrlString = `${origin}${path9}`;
15575
15575
  for (const historyUrl of this.history) {
15576
15576
  if (historyUrl.toString() === redirectUrlString) {
15577
15577
  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.`);
15578
15578
  }
15579
15579
  }
15580
15580
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
15581
- this.opts.path = path8;
15581
+ this.opts.path = path9;
15582
15582
  this.opts.origin = origin;
15583
15583
  this.opts.query = null;
15584
15584
  }
@@ -17395,10 +17395,10 @@ var require_cache_handler = __commonJS({
17395
17395
  }
17396
17396
  return locationUrl.pathname + locationUrl.search;
17397
17397
  }
17398
- function deleteCachedUri(store, cacheKey, path8) {
17398
+ function deleteCachedUri(store, cacheKey, path9) {
17399
17399
  deleteCachedValue(store, {
17400
17400
  ...cacheKey,
17401
- path: path8
17401
+ path: path9
17402
17402
  });
17403
17403
  for (let i = 0; i < util.safeHTTPMethods.length; i++) {
17404
17404
  const method = util.safeHTTPMethods[i];
@@ -17406,7 +17406,7 @@ var require_cache_handler = __commonJS({
17406
17406
  deleteCachedValue(store, {
17407
17407
  ...cacheKey,
17408
17408
  method,
17409
- path: path8
17409
+ path: path9
17410
17410
  });
17411
17411
  }
17412
17412
  }
@@ -17417,9 +17417,9 @@ var require_cache_handler = __commonJS({
17417
17417
  }
17418
17418
  const values = Array.isArray(headerValue) ? headerValue : [headerValue];
17419
17419
  for (let i = 0; i < values.length; i++) {
17420
- const path8 = getSameOriginPath(cacheKey, values[i]);
17421
- if (path8 !== void 0) {
17422
- deleteCachedUri(store, cacheKey, path8);
17420
+ const path9 = getSameOriginPath(cacheKey, values[i]);
17421
+ if (path9 !== void 0) {
17422
+ deleteCachedUri(store, cacheKey, path9);
17423
17423
  }
17424
17424
  }
17425
17425
  }
@@ -22907,11 +22907,11 @@ var require_fetch = __commonJS({
22907
22907
  function dispatch({ body }) {
22908
22908
  const url = requestCurrentURL(request);
22909
22909
  const agent = fetchParams.controller.dispatcher;
22910
- const path8 = url.pathname + url.search;
22910
+ const path9 = url.pathname + url.search;
22911
22911
  const hasTrailingQuestionMark = url.search.length === 0 && url.href[url.href.length - url.hash.length - 1] === "?";
22912
22912
  return new Promise((resolve, reject) => agent.dispatch(
22913
22913
  {
22914
- path: hasTrailingQuestionMark ? `${path8}?` : path8,
22914
+ path: hasTrailingQuestionMark ? `${path9}?` : path9,
22915
22915
  origin: url.origin,
22916
22916
  method: request.method,
22917
22917
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
@@ -23858,9 +23858,9 @@ var require_util4 = __commonJS({
23858
23858
  }
23859
23859
  }
23860
23860
  }
23861
- function validateCookiePath(path8) {
23862
- for (let i = 0; i < path8.length; ++i) {
23863
- const code = path8.charCodeAt(i);
23861
+ function validateCookiePath(path9) {
23862
+ for (let i = 0; i < path9.length; ++i) {
23863
+ const code = path9.charCodeAt(i);
23864
23864
  if (code < 32 || // exclude CTLs (0-31)
23865
23865
  code > 126 || // exclude DEL and non-ascii
23866
23866
  code === 59) {
@@ -27296,11 +27296,11 @@ var require_undici = __commonJS({
27296
27296
  if (typeof opts.path !== "string") {
27297
27297
  throw new InvalidArgumentError("invalid opts.path");
27298
27298
  }
27299
- let path8 = opts.path;
27299
+ let path9 = opts.path;
27300
27300
  if (!opts.path.startsWith("/")) {
27301
- path8 = `/${path8}`;
27301
+ path9 = `/${path9}`;
27302
27302
  }
27303
- url = new URL(util.parseOrigin(url).origin + path8);
27303
+ url = new URL(util.parseOrigin(url).origin + path9);
27304
27304
  } else {
27305
27305
  if (!opts) {
27306
27306
  opts = typeof url === "object" ? url : {};
@@ -27414,9 +27414,9 @@ import { createInterface } from "node:readline";
27414
27414
 
27415
27415
  // src/codex-execution.ts
27416
27416
  import crypto2 from "node:crypto";
27417
- import fs5 from "node:fs";
27418
- import path6 from "node:path";
27419
- import { setTimeout as delay } from "node:timers/promises";
27417
+ import fs6 from "node:fs";
27418
+ import path7 from "node:path";
27419
+ import { setTimeout as delay2 } from "node:timers/promises";
27420
27420
  import { spawn } from "node:child_process";
27421
27421
  import { fileURLToPath } from "node:url";
27422
27422
 
@@ -27643,6 +27643,36 @@ function tryLock(dir) {
27643
27643
  }
27644
27644
  }
27645
27645
 
27646
+ // ../cli/src/lib/agent/retry.ts
27647
+ var MAX_SUMMARY_CHARS = 300;
27648
+ var MAX_DETAIL_CHARS = 4e3;
27649
+ function clipSummary(text) {
27650
+ const clean = text.replace(/\s+/g, " ").trim();
27651
+ return clean.length > MAX_SUMMARY_CHARS ? `${clean.slice(0, MAX_SUMMARY_CHARS - 1)}\u2026` : clean;
27652
+ }
27653
+ function clipDetail(text) {
27654
+ if (!text) return void 0;
27655
+ const trimmed = text.trim();
27656
+ if (!trimmed) return void 0;
27657
+ return trimmed.length > MAX_DETAIL_CHARS ? `${trimmed.slice(0, MAX_DETAIL_CHARS - 1)}\u2026` : trimmed;
27658
+ }
27659
+ function makeFailure(source, rawSummary, options) {
27660
+ const summary = clipSummary(rawSummary) || "Execution failed.";
27661
+ const rawDetail = options?.detail?.trim() || (rawSummary.trim().length > summary.length || rawSummary.includes("\n") ? rawSummary.trim() : void 0);
27662
+ const detail = clipDetail(rawDetail);
27663
+ return {
27664
+ ...options?.code ? { code: options.code } : {},
27665
+ source,
27666
+ summary,
27667
+ ...detail && detail !== summary ? { detail } : {},
27668
+ ...typeof options?.retryAfterMs === "number" && Number.isFinite(options.retryAfterMs) && options.retryAfterMs >= 0 ? { retryAfterMs: options.retryAfterMs } : {}
27669
+ };
27670
+ }
27671
+ var SESSION_MISSING_RE = /no rollout found for thread id|no conversation found with session id|session[_\s-]*not[_\s-]*found|session[_\s-]*mismatch|(?:session|thread|conversation)\s+\S+\s+not\s+found|unknown\s+(?:session|thread)|did not resume the requested conversation|did not return the requested session/i;
27672
+ function isSessionMissingText(text) {
27673
+ return !!text && SESSION_MISSING_RE.test(text);
27674
+ }
27675
+
27646
27676
  // ../cli/src/lib/agent/wire/json.ts
27647
27677
  function obj(value) {
27648
27678
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -27654,7 +27684,7 @@ function str(value) {
27654
27684
  // ../cli/src/lib/agent/wire/failures.ts
27655
27685
  var ExecutionError = class extends Error {
27656
27686
  constructor(failure) {
27657
- super(failure.reason);
27687
+ super(failure.summary);
27658
27688
  this.failure = failure;
27659
27689
  }
27660
27690
  failure;
@@ -27663,13 +27693,9 @@ var NETWORK = /* @__PURE__ */ new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "E
27663
27693
  function executionFailure(error) {
27664
27694
  if (error instanceof ExecutionError) return error.failure;
27665
27695
  const code = str(obj(error).code);
27666
- const reason = error instanceof Error ? error.message : String(error);
27667
- return {
27668
- code: NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed",
27669
- level: NETWORK.has(code) ? 2 : 3,
27670
- source: "harness",
27671
- reason
27672
- };
27696
+ const raw = error instanceof Error ? error.message : String(error);
27697
+ const resolvedCode = isSessionMissingText(raw) ? "session_not_found" : NETWORK.has(code) ? "connection_lost" : code === "ENOENT" ? "executable_missing" : "execution_failed";
27698
+ return makeFailure("runner", raw, { code: resolvedCode, detail: raw });
27673
27699
  }
27674
27700
 
27675
27701
  // ../cli/src/lib/agent/wire/rpc.ts
@@ -27728,7 +27754,7 @@ function connect(stdout, stdin, onCall, dialect = {}) {
27728
27754
  } else pending.ok(obj(msg.result));
27729
27755
  }
27730
27756
  });
27731
- stdout.on("close", () => closed(new ExecutionError({ code: "connection_lost", level: 2, reason: "The agent closed the connection." })));
27757
+ stdout.on("close", () => closed(new ExecutionError({ code: "connection_lost", source: "runtime", summary: "The agent closed the connection." })));
27732
27758
  stdout.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
27733
27759
  stdin.on("error", (err) => closed(new ExecutionError(executionFailure(err))));
27734
27760
  return {
@@ -27772,12 +27798,17 @@ function mcpEnvironment(config, defaults) {
27772
27798
  }
27773
27799
  }
27774
27800
 
27801
+ // src/codex-ownership.ts
27802
+ import fs5 from "node:fs";
27803
+ import path6 from "node:path";
27804
+
27775
27805
  // src/codex-native.ts
27776
27806
  import crypto from "node:crypto";
27777
27807
  import fs4 from "node:fs";
27778
27808
  var import_undici2 = __toESM(require_undici(), 1);
27779
27809
  import path5 from "node:path";
27780
27810
  import { PassThrough, Writable } from "node:stream";
27811
+ import { setTimeout as delay } from "node:timers/promises";
27781
27812
 
27782
27813
  // ../cli/src/lib/agent/connection-process.ts
27783
27814
  import { spawnSync } from "node:child_process";
@@ -27874,61 +27905,141 @@ async function nativeConnection(backend, onMessage) {
27874
27905
  close();
27875
27906
  throw error;
27876
27907
  }
27877
- const rpc = connect(incoming, outgoing, onMessage);
27878
- return { rpc, incoming, close };
27908
+ const unloads = new EventTarget();
27909
+ const rpc = connect(incoming, outgoing, (message) => {
27910
+ const params = obj(message.params), id = str(params.threadId);
27911
+ if (id && message.id === void 0 && (message.method === "thread/closed" || message.method === "thread/status/changed" && obj(params.status).type === "notLoaded")) unloads.dispatchEvent(new Event(id));
27912
+ onMessage(message);
27913
+ });
27914
+ return { rpc, incoming, close, unloads };
27879
27915
  }
27880
27916
  async function initializeNative(connection) {
27881
27917
  const result = await bounded(connection.rpc.call("initialize", { clientInfo: { name: "wildcrane", version: "1" }, capabilities: { experimentalApi: true } }), CODEX_TIMEOUT, "Codex initialize timed out.");
27882
27918
  connection.rpc.notify("initialized");
27883
27919
  return result;
27884
27920
  }
27885
- async function backgroundTerminals(rpc, threadId) {
27921
+ async function backgroundTerminals(rpc, threadId, deadline = Date.now() + CODEX_TIMEOUT) {
27886
27922
  const result = [], seen = /* @__PURE__ */ new Set();
27887
- let cursor = null;
27923
+ let cursor;
27888
27924
  do {
27889
- if (seen.has(cursor)) throw Error("Codex repeated a terminal cursor.");
27890
- seen.add(cursor);
27891
- const page = await rpc.call("thread/backgroundTerminals/list", { threadId, ...cursor ? { cursor } : {} });
27925
+ if (cursor !== void 0) {
27926
+ if (seen.has(cursor)) throw Error("Codex repeated a terminal cursor.");
27927
+ seen.add(cursor);
27928
+ }
27929
+ const page = await beforeDeadline(deadline, "background terminal verification", () => rpc.call("thread/backgroundTerminals/list", { threadId, ...cursor === void 0 ? {} : { cursor } }));
27892
27930
  if (!Array.isArray(page.data) || page.nextCursor != null && typeof page.nextCursor !== "string") throw Error("Codex background terminal state is unconfirmed.");
27893
27931
  for (const value of page.data) result.push({ ...obj(value), threadId });
27894
- cursor = page.nextCursor;
27895
- } while (cursor);
27932
+ cursor = typeof page.nextCursor === "string" ? page.nextCursor : void 0;
27933
+ } while (cursor !== void 0);
27896
27934
  return result;
27897
27935
  }
27898
- async function releaseNativeThread(connection, threadId, turnId, stopWork, unloading) {
27899
- const missing = (error) => error instanceof RpcError && /thread not (?:found|loaded)/i.test(error.message);
27936
+ function codexDiagnostic(error) {
27937
+ return error instanceof RpcError ? `RPC ${error.code ?? "unknown"}: ${error.message}` : error instanceof Error ? error.message : String(error);
27938
+ }
27939
+ function beforeDeadline(deadline, operation, run) {
27940
+ const timeout = `Codex ${operation} timed out.`;
27941
+ const remaining = deadline - Date.now();
27942
+ if (remaining <= 0) throw Error(timeout);
27943
+ return bounded(run(), remaining, timeout);
27944
+ }
27945
+ async function inspectNativeThread(rpc, threadId, deadline = Date.now() + CODEX_TIMEOUT, checkBackground = true) {
27946
+ let diagnostic;
27900
27947
  try {
27901
- await bounded((async () => {
27902
- if (stopWork) {
27903
- if (turnId) {
27904
- try {
27905
- await connection.rpc.call("turn/interrupt", { threadId, turnId });
27906
- } catch (error) {
27907
- if (!missing(error)) throw error;
27908
- }
27909
- }
27910
- try {
27911
- await connection.rpc.call("thread/backgroundTerminals/clean", { threadId });
27912
- } catch (error) {
27913
- if (!(error instanceof RpcError) || error.code !== -32601 && !missing(error)) throw error;
27914
- }
27915
- }
27916
- const unloaded = new Promise((resolve) => unloading.set(threadId, resolve));
27917
- let result;
27948
+ const reply = await beforeDeadline(deadline, "thread/read", () => rpc.call("thread/read", { threadId }));
27949
+ const thread = obj(reply.thread), status = obj(thread.status).type;
27950
+ if (thread.id !== threadId || status !== "notLoaded" && status !== "active" && status !== "idle") {
27951
+ throw Error("thread/read returned an unexpected thread or status.");
27952
+ }
27953
+ if (status === "idle" && checkBackground) {
27954
+ const work = await backgroundTerminals(rpc, threadId, deadline);
27955
+ if (work.length) return { status: "background-work", thread };
27956
+ }
27957
+ return { status, thread };
27958
+ } catch (error) {
27959
+ diagnostic = codexDiagnostic(error);
27960
+ }
27961
+ let cursor;
27962
+ const seen = /* @__PURE__ */ new Set();
27963
+ try {
27964
+ do {
27965
+ const page = await beforeDeadline(deadline, "thread/loaded/list", () => rpc.call("thread/loaded/list", cursor === void 0 ? {} : { cursor }));
27966
+ const next = page.nextCursor;
27967
+ if (!Array.isArray(page.data) || page.data.some((id) => typeof id !== "string" || !id.trim()) || next != null && typeof next !== "string") throw Error("thread/loaded/list returned an invalid page.");
27968
+ if (page.data.includes(threadId)) return { status: "unverified", diagnostic: `${diagnostic} The thread is still loaded.` };
27969
+ cursor = typeof next === "string" ? next : void 0;
27970
+ if (cursor !== void 0) {
27971
+ if (seen.has(cursor)) throw Error("thread/loaded/list repeated a cursor.");
27972
+ seen.add(cursor);
27973
+ }
27974
+ } while (cursor !== void 0);
27975
+ return { status: "notLoaded", diagnostic };
27976
+ } catch (error) {
27977
+ return { status: "unverified", diagnostic: `${diagnostic} ${codexDiagnostic(error)}` };
27978
+ }
27979
+ }
27980
+ function releaseError(method, threadId, evidence, error) {
27981
+ const diagnostic = [`${method} could not confirm Codex thread ${threadId}: ${evidence.status}.`, evidence.diagnostic].filter(Boolean).join(" ");
27982
+ return error instanceof RpcError ? new RpcError(`${error.message} ${diagnostic}`, error.code, error.data) : Error([error && codexDiagnostic(error), diagnostic].filter(Boolean).join(" "));
27983
+ }
27984
+ async function interruptNativeThread(connection, threadId, turnId, deadline) {
27985
+ try {
27986
+ await beforeDeadline(deadline, "turn/interrupt", () => connection.rpc.call("turn/interrupt", { threadId, turnId }));
27987
+ } catch (error) {
27988
+ const evidence = await inspectNativeThread(connection.rpc, threadId, deadline, false);
27989
+ if (evidence.status !== "idle" && evidence.status !== "notLoaded") throw releaseError("turn/interrupt", threadId, evidence, error);
27990
+ console.error(`Codex turn/interrupt: ${codexDiagnostic(error)} (${evidence.status}, ${threadId})`);
27991
+ }
27992
+ }
27993
+ async function releaseNativeThread(connection, threadId, turnId, stopWork, deadline = Date.now() + CODEX_TIMEOUT) {
27994
+ const { rpc, unloads } = connection;
27995
+ let closed = false;
27996
+ let observed;
27997
+ const unloaded = new Promise((resolve) => {
27998
+ observed = () => {
27999
+ closed = true;
28000
+ resolve();
28001
+ };
28002
+ });
28003
+ unloads.addEventListener(threadId, observed, { once: true });
28004
+ const release = async () => {
28005
+ if (stopWork && turnId) await interruptNativeThread(connection, threadId, turnId, deadline);
28006
+ if (closed) return;
28007
+ if (stopWork) {
27918
28008
  try {
27919
- result = await connection.rpc.call("thread/unsubscribe", { threadId });
28009
+ await beforeDeadline(deadline, "thread/backgroundTerminals/clean", () => rpc.call("thread/backgroundTerminals/clean", { threadId }));
27920
28010
  } catch (error) {
27921
- if (!missing(error)) throw error;
27922
- result = { status: "notLoaded" };
28011
+ if (closed) return;
28012
+ if (!(error instanceof RpcError && error.code === -32601)) {
28013
+ const evidence = await inspectNativeThread(rpc, threadId, deadline, false);
28014
+ if (!closed && evidence.status !== "notLoaded") throw releaseError("thread/backgroundTerminals/clean", threadId, evidence, error);
28015
+ console.error(`Codex thread/backgroundTerminals/clean: ${codexDiagnostic(error)} (${threadId})`);
28016
+ return;
28017
+ }
27923
28018
  }
27924
- if (result.status === "unsubscribed") await unloaded;
27925
- else if (result.status !== "notLoaded") {
27926
- const snapshot = obj((await connection.rpc.call("thread/read", { threadId })).thread);
27927
- if (obj(snapshot.status).type !== "notLoaded") throw Error("Codex thread unload is unconfirmed.");
28019
+ }
28020
+ if (closed) return;
28021
+ let status, failure;
28022
+ try {
28023
+ status = (await beforeDeadline(deadline, "thread/unsubscribe", () => rpc.call("thread/unsubscribe", { threadId }))).status;
28024
+ } catch (error) {
28025
+ failure = error;
28026
+ }
28027
+ if (status === "notLoaded") return;
28028
+ while (!closed) {
28029
+ const evidence = await inspectNativeThread(rpc, threadId, deadline, false);
28030
+ if (closed || evidence.status === "notLoaded") {
28031
+ if (failure) console.error(`Codex thread/unsubscribe: ${codexDiagnostic(failure)} (${threadId})`);
28032
+ return;
27928
28033
  }
27929
- })(), CODEX_TIMEOUT, "Codex thread cleanup timed out; ownership remains unconfirmed.");
28034
+ if (status !== "unsubscribed") throw releaseError("thread/unsubscribe", threadId, evidence, failure);
28035
+ if (Date.now() >= deadline) throw releaseError("thread unload", threadId, evidence, Error("Codex thread cleanup timed out."));
28036
+ await delay(Math.min(50, deadline - Date.now()));
28037
+ }
28038
+ };
28039
+ try {
28040
+ await Promise.race([release(), unloaded]);
27930
28041
  } finally {
27931
- unloading.delete(threadId);
28042
+ unloads.removeEventListener(threadId, observed);
27932
28043
  }
27933
28044
  }
27934
28045
 
@@ -27941,35 +28052,68 @@ function executionOwner(environment) {
27941
28052
  }
27942
28053
  return { run: environment.KANBAN_RUN?.trim() || void 0, task: environment.AI4KANBAN_TASK?.trim() || void 0, job: str(execution.job).trim() || void 0 };
27943
28054
  }
27944
- function ownershipConflict(thread, requester, owner, status, phase, wait = false) {
28055
+ function ownershipConflict(thread, requester, owner, status, phase, wait = false, diagnostic) {
27945
28056
  const describe = (value) => ({ run: value?.run ?? "unknown", task: value?.task ?? "unknown", job: value?.job ?? "unknown", pid: value?.pid ?? "unknown", lease: value?.lease ?? "unknown" });
27946
- const evidence = { thread, requester: describe(requester), owner: describe(owner), status, phase };
27947
- const failure = wait ? { code: "codex_source_busy", level: 2, source: "harness", reason: "Waiting for the source conversation to finish." } : { code: "codex_ownership_unconfirmed", level: 3, source: "invariant", reason: "The conversation could not be opened safely. Saved work was preserved." };
28057
+ const evidence = { thread, requester: describe(requester), owner: describe(owner), status, phase, diagnostic };
28058
+ const failure = wait ? { code: "codex_source_busy", source: "runner", summary: "Waiting for the source conversation to finish." } : { code: "codex_ownership_unconfirmed", source: "runner", summary: "The conversation could not be opened safely. Saved work was preserved." };
27948
28059
  if (!wait) console.error(JSON.stringify({ code: failure.code, ...evidence }));
27949
28060
  const message = status === "caller-does-not-own-thread" ? "This run does not own that Codex thread." : "Codex thread is already in use by another run.";
27950
28061
  return new RpcError(`${message} ${JSON.stringify(evidence)}`, -32e3, { wildcraneFailure: failure });
27951
28062
  }
27952
- async function inspectThread(rpc, threadId) {
27953
- let snapshot;
28063
+ function leaseGroups(backend) {
28064
+ const directory2 = path6.join(nativeDirectory(), "threads", backend.instance);
28065
+ const groups = /* @__PURE__ */ new Map();
28066
+ let files;
27954
28067
  try {
27955
- snapshot = obj((await rpc.call("thread/read", { threadId })).thread);
28068
+ files = fs5.readdirSync(directory2).filter((name) => name.endsWith(".json"));
27956
28069
  } catch (error) {
27957
- if (!(error instanceof RpcError) || !/thread not (?:found|loaded)|no rollout found/i.test(error.message)) throw error;
27958
- let cursor;
27959
- const seen = /* @__PURE__ */ new Set();
27960
- do {
27961
- const page = await rpc.call("thread/loaded/list", { ...cursor ? { cursor } : {} });
27962
- if (!Array.isArray(page.data) || page.data.some((id) => typeof id !== "string") || page.nextCursor != null && typeof page.nextCursor !== "string") throw Error("Codex loaded threads are unconfirmed.");
27963
- if (page.data.includes(threadId)) return "unverified";
27964
- cursor = str(page.nextCursor) || void 0;
27965
- if (cursor && seen.has(cursor)) throw Error("Codex repeated a loaded-thread cursor.");
27966
- if (cursor) seen.add(cursor);
27967
- } while (cursor);
27968
- return "notLoaded";
28070
+ if (error.code === "ENOENT") return groups;
28071
+ throw error;
28072
+ }
28073
+ for (const name of files) {
28074
+ const file = path6.join(directory2, name), owner = readPrivate(file);
28075
+ if (!owner || owner.instance !== backend.instance || !Array.isArray(owner.threads)) continue;
28076
+ const thread = owner.thread ?? owner.threads.find((id) => leaseFile(backend, id) === file);
28077
+ if (!thread || leaseFile(backend, thread) !== file) continue;
28078
+ const group = groups.get(owner.lease) ?? /* @__PURE__ */ new Map();
28079
+ group.set(thread, owner);
28080
+ groups.set(owner.lease, group);
27969
28081
  }
27970
- const status = str(obj(snapshot.status).type);
27971
- if (status === "idle" && (await backgroundTerminals(rpc, threadId)).length) return "background-work";
27972
- return status;
28082
+ return groups;
28083
+ }
28084
+ function abandonedLeaseGroup(backend, thread, owner) {
28085
+ const group = leaseGroups(backend).get(owner.lease) ?? /* @__PURE__ */ new Map();
28086
+ group.set(thread, owner);
28087
+ return group;
28088
+ }
28089
+ function lockLeaseGroup(backend, group) {
28090
+ const threads = [...new Set([...group].flatMap(([thread, owner]) => [thread, ...owner.threads]))].sort();
28091
+ const releases = [];
28092
+ const release = () => {
28093
+ for (const unlock of releases.reverse()) unlock();
28094
+ };
28095
+ try {
28096
+ for (const thread of threads) {
28097
+ const unlock = tryLock(leaseFile(backend, thread) + ".lock");
28098
+ if (!unlock) {
28099
+ release();
28100
+ return;
28101
+ }
28102
+ releases.push(unlock);
28103
+ }
28104
+ const abandoned = () => threads.every((thread) => {
28105
+ const owner = readPrivate(leaseFile(backend, thread)), expected = group.get(thread);
28106
+ return !owner || !!expected && Number.isInteger(owner.pid) && owner.pid > 0 && JSON.stringify(owner) === JSON.stringify(expected) && !liveLease(owner);
28107
+ });
28108
+ return { threads, abandoned, release };
28109
+ } catch (error) {
28110
+ release();
28111
+ throw error;
28112
+ }
28113
+ }
28114
+ async function verifyStoppedThreads(rpc, threads, deadline = Date.now() + CODEX_TIMEOUT) {
28115
+ const evidence = await Promise.all(threads.map(async (threadId) => ({ threadId, ...await inspectNativeThread(rpc, threadId, deadline) })));
28116
+ return evidence.find(({ status }) => status !== "idle" && status !== "notLoaded");
27973
28117
  }
27974
28118
 
27975
28119
  // src/codex-execution.ts
@@ -27980,15 +28124,14 @@ async function codexExecution(backend, config, environment, cwd, send) {
27980
28124
  const threads = /* @__PURE__ */ new Set(), active = /* @__PURE__ */ new Map(), requests = /* @__PURE__ */ new Set();
27981
28125
  const preparing = /* @__PURE__ */ new Map();
27982
28126
  const pending = /* @__PURE__ */ new Set();
27983
- const unloading = /* @__PURE__ */ new Map();
27984
28127
  let closing;
27985
28128
  let settled;
27986
28129
  let keeper = false;
27987
28130
  let stoppingForRetry = false;
27988
- const state = () => ({ ...identity, lease, instance: backend.instance, settings, threads: [...threads], ...settled ? { retained: settled } : {} });
28131
+ const state = () => ({ ...identity, lease, instance: backend.instance, settings, threads: [...threads], ...settled?.kept.length ? { retained: settled } : {} });
27989
28132
  const owned = (id) => readPrivate(leaseFile(backend, id))?.lease === lease;
27990
28133
  const remove = (id) => {
27991
- if (owned(id)) fs5.rmSync(leaseFile(backend, id), { force: true });
28134
+ if (owned(id)) fs6.rmSync(leaseFile(backend, id), { force: true });
27992
28135
  };
27993
28136
  const leaseAt = (id, phase) => {
27994
28137
  const file = leaseFile(backend, id);
@@ -27999,50 +28142,66 @@ async function codexExecution(backend, config, environment, cwd, send) {
27999
28142
  }
28000
28143
  throw ownershipConflict(id, state(), void 0, "invalid-ownership-record", phase);
28001
28144
  };
28145
+ const claimLocked = (id, loaded, previous, forkSource = false) => {
28146
+ const current = leaseAt(id, "claim-thread");
28147
+ if (current && current.lease !== lease && current.lease !== previous?.lease) throw ownershipConflict(id, state(), current, liveLease(current) ? "owner-alive" : "unverified", loaded ? "claim-thread" : "reserve-source", forkSource && liveLease(current));
28148
+ if (loaded) threads.add(id);
28149
+ writeLease(backend, id, { ...state(), ...previous?.retained?.kept.length ? { retained: previous.retained, adopting: previous.lease } : {} });
28150
+ for (const thread of threads) {
28151
+ const owner = readPrivate(leaseFile(backend, thread));
28152
+ if (owner?.lease === lease) writeLease(backend, thread, { ...owner, threads: [...threads] });
28153
+ }
28154
+ };
28002
28155
  const claim = (id, loaded = true, previous, forkSource = false) => {
28003
28156
  if (!id) return;
28004
- const file = leaseFile(backend, id);
28005
- const release = tryLock(file + ".lock");
28157
+ const release = tryLock(leaseFile(backend, id) + ".lock");
28006
28158
  if (!release) throw ownershipConflict(id, state(), leaseAt(id, "claim-thread"), "ownership-transfer", loaded ? "claim-thread" : "reserve-source", forkSource);
28007
28159
  try {
28008
- const current = leaseAt(id, "claim-thread");
28009
- if (current && current.lease !== lease && current.lease !== previous?.lease) throw ownershipConflict(id, state(), current, liveLease(current) ? "owner-alive" : "unverified", loaded ? "claim-thread" : "reserve-source", forkSource && liveLease(current));
28010
- if (loaded) threads.add(id);
28011
- writeLease(backend, id, { ...state(), ...previous?.retained ? { retained: previous.retained, adopting: previous.lease } : {} });
28012
- for (const thread of threads) {
28013
- const owner = readPrivate(leaseFile(backend, thread));
28014
- if (owner?.lease === lease) writeLease(backend, thread, { ...owner, threads: [...threads] });
28015
- }
28160
+ claimLocked(id, loaded, previous, forkSource);
28016
28161
  } finally {
28017
28162
  release();
28018
28163
  }
28019
28164
  };
28165
+ const reserveAbandoned = async (id, owner) => {
28166
+ const deadline = Date.now() + CODEX_TIMEOUT;
28167
+ const group = abandonedLeaseGroup(backend, id, owner);
28168
+ let locked = lockLeaseGroup(backend, group);
28169
+ while (!locked && !closing && Date.now() < deadline) {
28170
+ await delay2(25);
28171
+ locked = lockLeaseGroup(backend, group);
28172
+ }
28173
+ if (!locked) throw ownershipConflict(id, state(), owner, "ownership-transfer", "verify-source", false, "Codex ownership verification timed out.");
28174
+ try {
28175
+ if (closing || !locked.abandoned()) throw ownershipConflict(id, state(), owner, "ownership-changed", "verify-source");
28176
+ const problem = await verifyStoppedThreads(connection.rpc, locked.threads, deadline);
28177
+ if (problem) {
28178
+ const busy = problem.status === "active" || problem.status === "background-work";
28179
+ throw ownershipConflict(problem.threadId, state(), owner, busy ? "work still running; automatic replay refused" : "unverified", "verify-source", false, problem.diagnostic);
28180
+ }
28181
+ if (closing || !locked.abandoned()) throw ownershipConflict(id, state(), owner, "ownership-changed", "verify-source");
28182
+ claimLocked(id, false, owner);
28183
+ for (const thread of group.keys()) if (thread !== id) fs6.rmSync(leaseFile(backend, thread), { force: true });
28184
+ } finally {
28185
+ locked.release();
28186
+ }
28187
+ };
28020
28188
  const reserve = async (id, forkSource) => {
28021
28189
  const previous = leaseAt(id, "reserve-source");
28022
- if (previous && previous.lease !== lease) {
28023
- if (previous.retained) {
28024
- if (previous.retained.root !== id) throw Error("Resume the owning Codex thread to adopt its retained work.");
28025
- if (previous.settings !== settings) throw Error("This Codex version cannot change execution settings while retaining a loaded session. Its services and saved results were preserved; no new work was submitted.");
28026
- const actual = [];
28027
- for (const thread of previous.threads) actual.push(...await backgroundTerminals(connection.rpc, thread));
28028
- const key = (value) => JSON.stringify([value.threadId, value.itemId, value.processId]);
28029
- if (actual.length !== previous.retained.kept.length || actual.some((value) => !previous.retained.kept.some((item) => key(item) === key(value)))) throw Error("The retained Codex services changed; no new work was submitted.");
28030
- } else {
28031
- if (liveLease(previous)) throw ownershipConflict(id, state(), previous, "owner-alive", "reserve-source", forkSource);
28032
- for (const thread of /* @__PURE__ */ new Set([id, ...previous.threads])) {
28033
- let status;
28034
- try {
28035
- status = await inspectThread(connection.rpc, thread);
28036
- } catch {
28037
- throw ownershipConflict(thread, state(), previous, "unverified", "verify-source");
28038
- }
28039
- if (status !== "idle" && status !== "notLoaded") throw ownershipConflict(thread, state(), previous, status === "active" || status === "background-work" ? "work still running; automatic replay refused" : "unverified", "verify-source");
28040
- }
28041
- }
28042
- }
28043
- claim(id, false, previous, forkSource);
28190
+ const retained = previous?.retained?.kept.length ? previous.retained : void 0;
28191
+ if (previous && previous.lease !== lease && retained) {
28192
+ if (retained.root !== id) throw Error("Resume the owning Codex thread to adopt its retained work.");
28193
+ if (previous.settings !== settings) throw Error("This Codex version cannot change execution settings while retaining a loaded session. Its services and saved results were preserved; no new work was submitted.");
28194
+ const actual = [];
28195
+ for (const thread of previous.threads) actual.push(...await backgroundTerminals(connection.rpc, thread));
28196
+ const key = (value) => JSON.stringify([value.threadId, value.itemId, value.processId]);
28197
+ if (actual.length !== retained.kept.length || actual.some((value) => !retained.kept.some((item) => key(item) === key(value)))) throw Error("The retained Codex services changed; no new work was submitted.");
28198
+ }
28199
+ if (previous && previous.lease !== lease && !retained) {
28200
+ if (liveLease(previous)) throw ownershipConflict(id, state(), previous, "owner-alive", "reserve-source", forkSource);
28201
+ await reserveAbandoned(id, previous);
28202
+ } else claim(id, false, previous, forkSource);
28044
28203
  preparing.set(id, (preparing.get(id) ?? 0) + 1);
28045
- return { previous: previous?.retained ? previous : void 0, release() {
28204
+ return { previous: retained ? previous : void 0, release() {
28046
28205
  const remaining = preparing.get(id) - 1;
28047
28206
  if (remaining) preparing.set(id, remaining);
28048
28207
  else {
@@ -28058,15 +28217,11 @@ async function codexExecution(backend, config, environment, cwd, send) {
28058
28217
  const notify = (message) => {
28059
28218
  const params = obj(message.params), thread = obj(params.thread);
28060
28219
  const id = str(params.threadId) || str(thread.id);
28061
- if (message.method === "thread/closed") {
28062
- unloading.get(id)?.();
28063
- unloading.delete(id);
28064
- }
28065
28220
  if (!threads.has(id)) {
28066
- const parent = str(thread.parentThreadId) || str(thread.forkedFromId);
28221
+ const parent = str(thread.parentThreadId);
28067
28222
  if (parent && threads.has(parent)) {
28068
28223
  try {
28069
- claim(id);
28224
+ if (owned(parent)) claim(id);
28070
28225
  } catch (error) {
28071
28226
  failNotification(error);
28072
28227
  return;
@@ -28083,7 +28238,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28083
28238
  const children = item.type === "subAgentActivity" && item.kind === "started" ? [item.agentThreadId] : item.type === "collabAgentToolCall" && item.tool === "spawnAgent" && Array.isArray(item.receiverThreadIds) ? item.receiverThreadIds : [];
28084
28239
  for (const child of children) if (typeof child === "string" && !threads.has(child)) {
28085
28240
  try {
28086
- claim(child);
28241
+ if (owned(id)) claim(child);
28087
28242
  } catch (error) {
28088
28243
  failNotification(error);
28089
28244
  return;
@@ -28101,7 +28256,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28101
28256
  throw error;
28102
28257
  }
28103
28258
  const keep = async () => {
28104
- const entry = process.env.RUNNER_DIST ? path6.join(process.env.RUNNER_DIST, "codex-retained.mjs") : fileURLToPath(new URL("./codex-retained.mjs", import.meta.url));
28259
+ const entry = process.env.RUNNER_DIST ? path7.join(process.env.RUNNER_DIST, "codex-retained.mjs") : fileURLToPath(new URL("./codex-retained.mjs", import.meta.url));
28105
28260
  const child = spawn(process.execPath, [entry, backendFile(backend.key), leaseFile(backend, settled.root), lease], {
28106
28261
  cwd,
28107
28262
  env: { ...environment, WILDCRANE_CODEX_GENERATION: backend.generation },
@@ -28132,7 +28287,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28132
28287
  for (const id of requests) connection.rpc.refuse(id, "Execution disconnected.");
28133
28288
  const results = await Promise.allSettled([...threads].map(async (id) => {
28134
28289
  if (!owned(id)) return;
28135
- await releaseNativeThread(connection, id, active.get(id), !settled, unloading);
28290
+ await releaseNativeThread(connection, id, active.get(id), !settled);
28136
28291
  remove(id);
28137
28292
  }));
28138
28293
  const failure = results.find((result) => result.status === "rejected");
@@ -28142,9 +28297,10 @@ async function codexExecution(backend, config, environment, cwd, send) {
28142
28297
  try {
28143
28298
  await cleanup();
28144
28299
  } catch (error) {
28300
+ const diagnostic = codexDiagnostic(error);
28145
28301
  for (const id of threads) if (owned(id)) writeLease(backend, id, { ...state(), uncertain: true });
28146
- send({ method: "wildcrane/cleanup", params: { status: "unconfirmed", lease } });
28147
- console.error(error instanceof Error ? error.message : String(error));
28302
+ send({ method: "wildcrane/cleanup", params: { status: "unconfirmed", lease, diagnostic } });
28303
+ console.error(diagnostic);
28148
28304
  } finally {
28149
28305
  connection.close();
28150
28306
  }
@@ -28156,16 +28312,19 @@ async function codexExecution(backend, config, environment, cwd, send) {
28156
28312
  }
28157
28313
  stoppingForRetry = true;
28158
28314
  const otherWork = pending.size || requests.size || active.size !== 1;
28159
- await bounded(connection.rpc.call("turn/interrupt", { threadId, turnId }), CODEX_TIMEOUT, "Codex did not acknowledge interrupting the idle turn.");
28315
+ await interruptNativeThread(connection, threadId, turnId, Date.now() + CODEX_TIMEOUT);
28160
28316
  if (otherWork) throw Error("Other Codex operations were pending when the idle turn was interrupted.");
28161
28317
  const deadline = Date.now() + CODEX_TIMEOUT;
28162
28318
  const call = (method, input) => bounded(connection.rpc.call(method, input), deadline - Date.now(), "Codex did not confirm the idle turn stopped.");
28163
28319
  for (; ; ) {
28164
- const snapshot = obj((await call("thread/read", { threadId, includeTurns: false })).thread);
28165
- if (snapshot.id !== threadId || closing) throw Error("Codex session availability could not be confirmed.");
28166
- if (obj(snapshot.status).type === "idle" && !active.has(threadId)) {
28320
+ const evidence = await inspectNativeThread(connection.rpc, threadId, deadline, false);
28321
+ const snapshot = evidence.thread;
28322
+ if (!snapshot || closing) throw Error(evidence.diagnostic ?? "Codex session availability could not be confirmed.");
28323
+ if ((evidence.status === "idle" || evidence.status === "notLoaded") && !active.has(threadId)) {
28167
28324
  const paginated = snapshot.historyMode === "paginated";
28168
- const listed = paginated ? (await call("thread/turns/list", { threadId, sortDirection: "desc", limit: 1, itemsView: "full" })).data : obj((await call("thread/read", { threadId, includeTurns: true })).thread).turns;
28325
+ const history = paginated ? void 0 : obj((await call("thread/read", { threadId, includeTurns: true })).thread);
28326
+ if (history && history.id !== threadId) throw Error("Codex returned a different session during interruption.");
28327
+ const listed = paginated ? (await call("thread/turns/list", { threadId, sortDirection: "desc", limit: 1, itemsView: "full" })).data : history?.turns;
28169
28328
  const turns = Array.isArray(listed) ? listed.map(obj) : [];
28170
28329
  const turn = turns.at(paginated ? 0 : -1);
28171
28330
  if (turn?.id !== turnId || turn.status !== "interrupted" || !Array.isArray(turn.items)) {
@@ -28177,16 +28336,18 @@ async function codexExecution(backend, config, environment, cwd, send) {
28177
28336
  break;
28178
28337
  }
28179
28338
  if (Date.now() >= deadline) throw Error("Codex did not confirm the idle turn stopped.");
28180
- await delay(50);
28339
+ await delay2(50);
28181
28340
  }
28182
28341
  const claimed = [...threads];
28183
- for (const thread of claimed) {
28184
- if (!owned(thread) || active.has(thread) || requests.size || closing) throw Error("Codex ownership or pending operations changed during interruption.");
28185
- const status = await bounded(inspectThread(connection.rpc, thread), CODEX_TIMEOUT, "Codex work is unconfirmed after interruption.");
28186
- if (status !== "idle" && (thread === threadId || status !== "notLoaded")) throw Error("Codex has unfinished work after interruption.");
28187
- }
28188
- await Promise.all(claimed.map((thread) => releaseNativeThread(connection, thread, void 0, false, unloading)));
28189
- if (active.size || requests.size || threads.size !== claimed.length || claimed.some((thread) => !owned(thread)) || closing) {
28342
+ const changed = () => active.size || requests.size || threads.size !== claimed.length || claimed.some((thread) => !owned(thread)) || closing;
28343
+ if (changed()) throw Error("Codex ownership or pending operations changed during interruption.");
28344
+ const problem = await verifyStoppedThreads(connection.rpc, claimed);
28345
+ if (problem) throw Error([`Codex thread ${problem.threadId} has unconfirmed or unfinished work after interruption (${problem.status}).`, problem.diagnostic].filter(Boolean).join(" "));
28346
+ if (changed()) throw Error("Codex ownership or pending operations changed during verification.");
28347
+ const results = await Promise.allSettled(claimed.map((thread) => releaseNativeThread(connection, thread, void 0, false)));
28348
+ const failure = results.find((result) => result.status === "rejected");
28349
+ if (failure?.status === "rejected") throw failure.reason;
28350
+ if (changed()) {
28190
28351
  throw Error("Codex ownership or pending operations changed during release.");
28191
28352
  }
28192
28353
  for (const thread of claimed) {
@@ -28242,7 +28403,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28242
28403
  if (["thread/start", "thread/resume", "thread/fork"].includes(message.method)) {
28243
28404
  if (message.method !== "thread/start") {
28244
28405
  const id2 = str(params.threadId);
28245
- if (message.method !== "thread/fork" || !leaseAt(id2, "reserve-source")?.retained) {
28406
+ if (message.method !== "thread/fork" || !leaseAt(id2, "reserve-source")?.retained?.kept.length) {
28246
28407
  source = id2;
28247
28408
  const reservation = await reserve(source, message.method === "thread/fork");
28248
28409
  previous = reservation.previous;
@@ -28250,6 +28411,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28250
28411
  }
28251
28412
  }
28252
28413
  const defaults = await connection.rpc.call("config/read", { cwd: params.cwd ?? cwd, includeLayers: false });
28414
+ if (closing) throw Error("Codex execution is stopping.");
28253
28415
  const overrides = { ...config, ...obj(params.config), thread_unload_delay_secs: 0 };
28254
28416
  mcpEnvironment(overrides, obj(obj(defaults.config).mcp_servers));
28255
28417
  params = { ...params, cwd: params.cwd ?? cwd, config: overrides };
@@ -28281,6 +28443,7 @@ async function codexExecution(backend, config, environment, cwd, send) {
28281
28443
  if (owned(thread)) writeLease(backend, thread, previous);
28282
28444
  threads.delete(thread);
28283
28445
  }
28446
+ if (message.method === "wildcrane/stopForRetry" && error instanceof RpcError) console.error(codexDiagnostic(error));
28284
28447
  if (id !== void 0) send({ id, error: { code: error instanceof RpcError ? error.code : -32e3, message: error instanceof Error ? error.message : String(error), ...error instanceof RpcError ? { data: error.data } : {} } });
28285
28448
  } finally {
28286
28449
  releaseSource?.();
@@ -28305,26 +28468,26 @@ var LIST_PROCS = [
28305
28468
  ].join("; ");
28306
28469
 
28307
28470
  // src/settings-control.ts
28308
- import fs6 from "node:fs";
28309
- import path7 from "node:path";
28310
- var directory = () => path7.join(runnerHome(), "executors");
28311
- var epochFile = () => path7.join(runnerHome(), "account-generation");
28471
+ import fs7 from "node:fs";
28472
+ import path8 from "node:path";
28473
+ var directory = () => path8.join(runnerHome(), "executors");
28474
+ var epochFile = () => path8.join(runnerHome(), "account-generation");
28312
28475
  function accountGeneration() {
28313
28476
  try {
28314
- return fs6.readFileSync(epochFile(), "utf8");
28477
+ return fs7.readFileSync(epochFile(), "utf8");
28315
28478
  } catch {
28316
28479
  return "";
28317
28480
  }
28318
28481
  }
28319
28482
  function executorRecord() {
28320
- fs6.mkdirSync(directory(), { recursive: true, mode: 448 });
28321
- const file = path7.join(directory(), `${process.pid}.json`);
28322
- fs6.writeFileSync(file, "{}", { mode: 384 });
28323
- return () => fs6.rmSync(file, { force: true });
28483
+ fs7.mkdirSync(directory(), { recursive: true, mode: 448 });
28484
+ const file = path8.join(directory(), `${process.pid}.json`);
28485
+ fs7.writeFileSync(file, "{}", { mode: 384 });
28486
+ return () => fs7.rmSync(file, { force: true });
28324
28487
  }
28325
28488
 
28326
28489
  // src/codex-server.ts
28327
- var delay2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28490
+ var delay3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
28328
28491
  async function requestCodexBackend(argv, env) {
28329
28492
  const until = Date.now() + CODEX_TIMEOUT;
28330
28493
  for (; ; ) {
@@ -28360,7 +28523,7 @@ async function requestCodexBackend(argv, env) {
28360
28523
  }
28361
28524
  }
28362
28525
  if (Date.now() >= until) throw Error("No active Runner could prepare Codex. Existing work was preserved.");
28363
- await delay2(50);
28526
+ await delay3(50);
28364
28527
  }
28365
28528
  }
28366
28529