agent-shim 8.20.2 → 8.21.1

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.
package/dist/cli.cjs CHANGED
@@ -3248,42 +3248,42 @@ var require_defaults = __commonJS({
3248
3248
  var require_env_paths = __commonJS({
3249
3249
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
3250
3250
  "use strict";
3251
- var path44 = require("path");
3252
- var os10 = require("os");
3253
- var homedir = os10.homedir();
3254
- var tmpdir = os10.tmpdir();
3251
+ var path46 = require("path");
3252
+ var os11 = require("os");
3253
+ var homedir = os11.homedir();
3254
+ var tmpdir = os11.tmpdir();
3255
3255
  var { env } = process;
3256
3256
  var macos = (name) => {
3257
- const library = path44.join(homedir, "Library");
3257
+ const library = path46.join(homedir, "Library");
3258
3258
  return {
3259
- data: path44.join(library, "Application Support", name),
3260
- config: path44.join(library, "Preferences", name),
3261
- cache: path44.join(library, "Caches", name),
3262
- log: path44.join(library, "Logs", name),
3263
- temp: path44.join(tmpdir, name)
3259
+ data: path46.join(library, "Application Support", name),
3260
+ config: path46.join(library, "Preferences", name),
3261
+ cache: path46.join(library, "Caches", name),
3262
+ log: path46.join(library, "Logs", name),
3263
+ temp: path46.join(tmpdir, name)
3264
3264
  };
3265
3265
  };
3266
3266
  var windows = (name) => {
3267
- const appData = env.APPDATA || path44.join(homedir, "AppData", "Roaming");
3268
- const localAppData = env.LOCALAPPDATA || path44.join(homedir, "AppData", "Local");
3267
+ const appData = env.APPDATA || path46.join(homedir, "AppData", "Roaming");
3268
+ const localAppData = env.LOCALAPPDATA || path46.join(homedir, "AppData", "Local");
3269
3269
  return {
3270
3270
  // Data/config/cache/log are invented by me as Windows isn't opinionated about this
3271
- data: path44.join(localAppData, name, "Data"),
3272
- config: path44.join(appData, name, "Config"),
3273
- cache: path44.join(localAppData, name, "Cache"),
3274
- log: path44.join(localAppData, name, "Log"),
3275
- temp: path44.join(tmpdir, name)
3271
+ data: path46.join(localAppData, name, "Data"),
3272
+ config: path46.join(appData, name, "Config"),
3273
+ cache: path46.join(localAppData, name, "Cache"),
3274
+ log: path46.join(localAppData, name, "Log"),
3275
+ temp: path46.join(tmpdir, name)
3276
3276
  };
3277
3277
  };
3278
3278
  var linux = (name) => {
3279
- const username = path44.basename(homedir);
3279
+ const username = path46.basename(homedir);
3280
3280
  return {
3281
- data: path44.join(env.XDG_DATA_HOME || path44.join(homedir, ".local", "share"), name),
3282
- config: path44.join(env.XDG_CONFIG_HOME || path44.join(homedir, ".config"), name),
3283
- cache: path44.join(env.XDG_CACHE_HOME || path44.join(homedir, ".cache"), name),
3281
+ data: path46.join(env.XDG_DATA_HOME || path46.join(homedir, ".local", "share"), name),
3282
+ config: path46.join(env.XDG_CONFIG_HOME || path46.join(homedir, ".config"), name),
3283
+ cache: path46.join(env.XDG_CACHE_HOME || path46.join(homedir, ".cache"), name),
3284
3284
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
3285
- log: path44.join(env.XDG_STATE_HOME || path44.join(homedir, ".local", "state"), name),
3286
- temp: path44.join(tmpdir, username, name)
3285
+ log: path46.join(env.XDG_STATE_HOME || path46.join(homedir, ".local", "state"), name),
3286
+ temp: path46.join(tmpdir, username, name)
3287
3287
  };
3288
3288
  };
3289
3289
  var envPaths = (name, options) => {
@@ -3351,11 +3351,11 @@ var require_util = __commonJS({
3351
3351
  return result;
3352
3352
  }
3353
3353
  exports2.emplace = emplace;
3354
- function getPropertyByPath(source, path44) {
3355
- if (typeof path44 === "string" && Object.prototype.hasOwnProperty.call(source, path44)) {
3356
- return source[path44];
3354
+ function getPropertyByPath(source, path46) {
3355
+ if (typeof path46 === "string" && Object.prototype.hasOwnProperty.call(source, path46)) {
3356
+ return source[path46];
3357
3357
  }
3358
- const parsedPath = typeof path44 === "string" ? path44.split(".") : path44;
3358
+ const parsedPath = typeof path46 === "string" ? path46.split(".") : path46;
3359
3359
  return parsedPath.reduce((previous, key) => {
3360
3360
  if (previous === void 0) {
3361
3361
  return previous;
@@ -3378,9 +3378,9 @@ var require_util = __commonJS({
3378
3378
  return Object.fromEntries(Object.entries(options).filter(([, value2]) => value2 !== void 0));
3379
3379
  }
3380
3380
  exports2.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
3381
- async function isDirectory(path44) {
3381
+ async function isDirectory(path46) {
3382
3382
  try {
3383
- const stat = await fs_1.promises.stat(path44);
3383
+ const stat = await fs_1.promises.stat(path46);
3384
3384
  return stat.isDirectory();
3385
3385
  } catch (e) {
3386
3386
  if (e.code === "ENOENT") {
@@ -3390,9 +3390,9 @@ var require_util = __commonJS({
3390
3390
  }
3391
3391
  }
3392
3392
  exports2.isDirectory = isDirectory;
3393
- function isDirectorySync(path44) {
3393
+ function isDirectorySync(path46) {
3394
3394
  try {
3395
- const stat = fs_1.default.statSync(path44);
3395
+ const stat = fs_1.default.statSync(path46);
3396
3396
  return stat.isDirectory();
3397
3397
  } catch (e) {
3398
3398
  if (e.code === "ENOENT") {
@@ -3490,7 +3490,7 @@ var require_ExplorerBase = __commonJS({
3490
3490
  const idx = importStack.indexOf(fullPath);
3491
3491
  if (idx !== -1) {
3492
3492
  throw new Error(`Circular import detected:
3493
- ${[...importStack, fullPath].map((path44, i2) => `${i2 + 1}. ${path44}`).join("\n")} (same as ${idx + 1}.)`);
3493
+ ${[...importStack, fullPath].map((path46, i2) => `${i2 + 1}. ${path46}`).join("\n")} (same as ${idx + 1}.)`);
3494
3494
  }
3495
3495
  }
3496
3496
  }
@@ -3678,9 +3678,9 @@ var require_Explorer = __commonJS({
3678
3678
  throw error62;
3679
3679
  }
3680
3680
  }
3681
- async #fileExists(path44) {
3681
+ async #fileExists(path46) {
3682
3682
  try {
3683
- await promises_1.default.stat(path44);
3683
+ await promises_1.default.stat(path46);
3684
3684
  return true;
3685
3685
  } catch (e) {
3686
3686
  return false;
@@ -3840,9 +3840,9 @@ var require_ExplorerSync = __commonJS({
3840
3840
  throw error62;
3841
3841
  }
3842
3842
  }
3843
- #fileExists(path44) {
3843
+ #fileExists(path46) {
3844
3844
  try {
3845
- fs_1.default.statSync(path44);
3845
+ fs_1.default.statSync(path46);
3846
3846
  return true;
3847
3847
  } catch (e) {
3848
3848
  return false;
@@ -3966,7 +3966,7 @@ var require_dist = __commonJS({
3966
3966
  };
3967
3967
  }
3968
3968
  function getResolvedSearchPlaces(moduleName, toolDefinedSearchPlaces, userConfiguredOptions) {
3969
- const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path44) => path44.replace("{name}", moduleName));
3969
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path46) => path46.replace("{name}", moduleName));
3970
3970
  if (userConfiguredOptions.mergeSearchPlaces) {
3971
3971
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
3972
3972
  }
@@ -4374,8 +4374,8 @@ var require_utils = __commonJS({
4374
4374
  }
4375
4375
  return output2;
4376
4376
  };
4377
- exports2.basename = (path44, { windows } = {}) => {
4378
- const segs = path44.split(windows ? /[\\/]/ : "/");
4377
+ exports2.basename = (path46, { windows } = {}) => {
4378
+ const segs = path46.split(windows ? /[\\/]/ : "/");
4379
4379
  const last = segs[segs.length - 1];
4380
4380
  if (last === "") {
4381
4381
  return segs[segs.length - 2];
@@ -6891,7 +6891,7 @@ var require_util2 = __commonJS({
6891
6891
  var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
6892
6892
  var { IncomingMessage } = require("node:http");
6893
6893
  var stream = require("node:stream");
6894
- var net3 = require("node:net");
6894
+ var net4 = require("node:net");
6895
6895
  var { stringify } = require("node:querystring");
6896
6896
  var { EventEmitter: EE } = require("node:events");
6897
6897
  var timers = require_timers();
@@ -7003,14 +7003,14 @@ var require_util2 = __commonJS({
7003
7003
  }
7004
7004
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
7005
7005
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
7006
- let path44 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
7006
+ let path46 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
7007
7007
  if (origin[origin.length - 1] === "/") {
7008
7008
  origin = origin.slice(0, origin.length - 1);
7009
7009
  }
7010
- if (path44 && path44[0] !== "/") {
7011
- path44 = `/${path44}`;
7010
+ if (path46 && path46[0] !== "/") {
7011
+ path46 = `/${path46}`;
7012
7012
  }
7013
- return new URL(`${origin}${path44}`);
7013
+ return new URL(`${origin}${path46}`);
7014
7014
  }
7015
7015
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
7016
7016
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -7040,7 +7040,7 @@ var require_util2 = __commonJS({
7040
7040
  }
7041
7041
  assert2(typeof host === "string");
7042
7042
  const servername = getHostname(host);
7043
- if (net3.isIP(servername)) {
7043
+ if (net4.isIP(servername)) {
7044
7044
  return "";
7045
7045
  }
7046
7046
  return servername;
@@ -7831,9 +7831,9 @@ var require_diagnostics = __commonJS({
7831
7831
  "undici:client:sendHeaders",
7832
7832
  (evt) => {
7833
7833
  const {
7834
- request: { method, path: path44, origin }
7834
+ request: { method, path: path46, origin }
7835
7835
  } = evt;
7836
- debugLog("sending request to %s %s%s", method, origin, path44);
7836
+ debugLog("sending request to %s %s%s", method, origin, path46);
7837
7837
  }
7838
7838
  );
7839
7839
  }
@@ -7851,14 +7851,14 @@ var require_diagnostics = __commonJS({
7851
7851
  "undici:request:headers",
7852
7852
  (evt) => {
7853
7853
  const {
7854
- request: { method, path: path44, origin },
7854
+ request: { method, path: path46, origin },
7855
7855
  response: { statusCode }
7856
7856
  } = evt;
7857
7857
  debugLog(
7858
7858
  "received response to %s %s%s - HTTP %d",
7859
7859
  method,
7860
7860
  origin,
7861
- path44,
7861
+ path46,
7862
7862
  statusCode
7863
7863
  );
7864
7864
  }
@@ -7867,23 +7867,23 @@ var require_diagnostics = __commonJS({
7867
7867
  "undici:request:trailers",
7868
7868
  (evt) => {
7869
7869
  const {
7870
- request: { method, path: path44, origin }
7870
+ request: { method, path: path46, origin }
7871
7871
  } = evt;
7872
- debugLog("trailers received from %s %s%s", method, origin, path44);
7872
+ debugLog("trailers received from %s %s%s", method, origin, path46);
7873
7873
  }
7874
7874
  );
7875
7875
  diagnosticsChannel.subscribe(
7876
7876
  "undici:request:error",
7877
7877
  (evt) => {
7878
7878
  const {
7879
- request: { method, path: path44, origin },
7879
+ request: { method, path: path46, origin },
7880
7880
  error: error62
7881
7881
  } = evt;
7882
7882
  debugLog(
7883
7883
  "request to %s %s%s errored - %s",
7884
7884
  method,
7885
7885
  origin,
7886
- path44,
7886
+ path46,
7887
7887
  error62.message
7888
7888
  );
7889
7889
  }
@@ -7998,7 +7998,7 @@ var require_request = __commonJS({
7998
7998
  var kHandler = /* @__PURE__ */ Symbol("handler");
7999
7999
  var Request2 = class {
8000
8000
  constructor(origin, {
8001
- path: path44,
8001
+ path: path46,
8002
8002
  method,
8003
8003
  body,
8004
8004
  headers,
@@ -8015,11 +8015,11 @@ var require_request = __commonJS({
8015
8015
  maxRedirections,
8016
8016
  typeOfService
8017
8017
  }, handler) {
8018
- if (typeof path44 !== "string") {
8018
+ if (typeof path46 !== "string") {
8019
8019
  throw new InvalidArgumentError2("path must be a string");
8020
- } else if (path44[0] !== "/" && !(path44.startsWith("http://") || path44.startsWith("https://")) && method !== "CONNECT") {
8020
+ } else if (path46[0] !== "/" && !(path46.startsWith("http://") || path46.startsWith("https://")) && method !== "CONNECT") {
8021
8021
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
8022
- } else if (invalidPathRegex.test(path44)) {
8022
+ } else if (invalidPathRegex.test(path46)) {
8023
8023
  throw new InvalidArgumentError2("invalid request path");
8024
8024
  }
8025
8025
  if (typeof method !== "string") {
@@ -8094,7 +8094,7 @@ var require_request = __commonJS({
8094
8094
  this.completed = false;
8095
8095
  this.aborted = false;
8096
8096
  this.upgrade = upgrade || null;
8097
- this.path = query ? serializePathWithQuery(path44, query) : path44;
8097
+ this.path = query ? serializePathWithQuery(path46, query) : path46;
8098
8098
  this.origin = origin;
8099
8099
  this.protocol = getProtocolFromUrlString(origin);
8100
8100
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -8703,7 +8703,7 @@ var require_dispatcher_base = __commonJS({
8703
8703
  var require_connect = __commonJS({
8704
8704
  "node_modules/.pnpm/undici@7.29.1/node_modules/undici/lib/core/connect.js"(exports2, module2) {
8705
8705
  "use strict";
8706
- var net3 = require("node:net");
8706
+ var net4 = require("node:net");
8707
8707
  var assert2 = require("node:assert");
8708
8708
  var util = require_util2();
8709
8709
  var { InvalidArgumentError: InvalidArgumentError2 } = require_errors();
@@ -8786,7 +8786,7 @@ var require_connect = __commonJS({
8786
8786
  } else {
8787
8787
  assert2(!httpSocket, "httpSocket can only be sent on TLS update");
8788
8788
  port = port || 80;
8789
- socket = net3.connect({
8789
+ socket = net4.connect({
8790
8790
  highWaterMark: 64 * 1024,
8791
8791
  // Same as nodejs fs streams.
8792
8792
  ...options,
@@ -13276,7 +13276,7 @@ var require_client_h1 = __commonJS({
13276
13276
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
13277
13277
  }
13278
13278
  function writeH1(client, request7) {
13279
- const { method, path: path44, host, upgrade, blocking, reset } = request7;
13279
+ const { method, path: path46, host, upgrade, blocking, reset } = request7;
13280
13280
  let { body, headers, contentLength } = request7;
13281
13281
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
13282
13282
  if (util.isFormDataLike(body)) {
@@ -13354,7 +13354,7 @@ var require_client_h1 = __commonJS({
13354
13354
  if (socket.setTypeOfService) {
13355
13355
  socket.setTypeOfService(request7.typeOfService);
13356
13356
  }
13357
- let header = `${method} ${path44} HTTP/1.1\r
13357
+ let header = `${method} ${path46} HTTP/1.1\r
13358
13358
  `;
13359
13359
  if (typeof host === "string") {
13360
13360
  header += `host: ${host}\r
@@ -14033,7 +14033,7 @@ var require_client_h2 = __commonJS({
14033
14033
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
14034
14034
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
14035
14035
  const session = client[kHTTP2Session];
14036
- const { method, path: path44, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
14036
+ const { method, path: path46, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
14037
14037
  let { body } = request7;
14038
14038
  if (upgrade != null && upgrade !== "websocket") {
14039
14039
  util.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -14102,7 +14102,7 @@ var require_client_h2 = __commonJS({
14102
14102
  }
14103
14103
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
14104
14104
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
14105
- headers[HTTP2_HEADER_PATH] = path44;
14105
+ headers[HTTP2_HEADER_PATH] = path46;
14106
14106
  if (protocol === "ws:" || protocol === "wss:") {
14107
14107
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
14108
14108
  } else {
@@ -14144,7 +14144,7 @@ var require_client_h2 = __commonJS({
14144
14144
  stream.setTimeout(headersTimeout);
14145
14145
  return true;
14146
14146
  }
14147
- headers[HTTP2_HEADER_PATH] = path44;
14147
+ headers[HTTP2_HEADER_PATH] = path46;
14148
14148
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
14149
14149
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
14150
14150
  if (body && typeof body.read === "function") {
@@ -14463,8 +14463,8 @@ var require_client = __commonJS({
14463
14463
  "node_modules/.pnpm/undici@7.29.1/node_modules/undici/lib/dispatcher/client.js"(exports2, module2) {
14464
14464
  "use strict";
14465
14465
  var assert2 = require("node:assert");
14466
- var net3 = require("node:net");
14467
- var http7 = require("node:http");
14466
+ var net4 = require("node:net");
14467
+ var http8 = require("node:http");
14468
14468
  var util = require_util2();
14469
14469
  var { ClientStats } = require_stats();
14470
14470
  var { channels } = require_diagnostics();
@@ -14522,7 +14522,7 @@ var require_client = __commonJS({
14522
14522
  var connectH1 = require_client_h1();
14523
14523
  var connectH2 = require_client_h2();
14524
14524
  var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
14525
- var getDefaultNodeMaxHeaderSize = http7 && http7.maxHeaderSize && Number.isInteger(http7.maxHeaderSize) && http7.maxHeaderSize > 0 ? () => http7.maxHeaderSize : () => {
14525
+ var getDefaultNodeMaxHeaderSize = http8 && http8.maxHeaderSize && Number.isInteger(http8.maxHeaderSize) && http8.maxHeaderSize > 0 ? () => http8.maxHeaderSize : () => {
14526
14526
  throw new InvalidArgumentError2("http module not available or http.maxHeaderSize invalid");
14527
14527
  };
14528
14528
  var noop = () => {
@@ -14618,7 +14618,7 @@ var require_client = __commonJS({
14618
14618
  if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
14619
14619
  throw new InvalidArgumentError2("maxRequestsPerClient must be a positive number");
14620
14620
  }
14621
- if (localAddress != null && (typeof localAddress !== "string" || net3.isIP(localAddress) === 0)) {
14621
+ if (localAddress != null && (typeof localAddress !== "string" || net4.isIP(localAddress) === 0)) {
14622
14622
  throw new InvalidArgumentError2("localAddress must be valid string IP address");
14623
14623
  }
14624
14624
  if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
@@ -14798,7 +14798,7 @@ var require_client = __commonJS({
14798
14798
  const idx = hostname3.indexOf("]");
14799
14799
  assert2(idx !== -1);
14800
14800
  const ip = hostname3.substring(1, idx);
14801
- assert2(net3.isIPv6(ip));
14801
+ assert2(net4.isIPv6(ip));
14802
14802
  hostname3 = ip;
14803
14803
  }
14804
14804
  client[kConnecting] = true;
@@ -15743,10 +15743,10 @@ var require_socks5_utils = __commonJS({
15743
15743
  "node_modules/.pnpm/undici@7.29.1/node_modules/undici/lib/core/socks5-utils.js"(exports2, module2) {
15744
15744
  "use strict";
15745
15745
  var { Buffer: Buffer3 } = require("node:buffer");
15746
- var net3 = require("node:net");
15746
+ var net4 = require("node:net");
15747
15747
  var { InvalidArgumentError: InvalidArgumentError2 } = require_errors();
15748
15748
  function parseAddress(address) {
15749
- if (net3.isIPv4(address)) {
15749
+ if (net4.isIPv4(address)) {
15750
15750
  const parts = address.split(".").map(Number);
15751
15751
  return {
15752
15752
  type: 1,
@@ -15754,7 +15754,7 @@ var require_socks5_utils = __commonJS({
15754
15754
  buffer: Buffer3.from(parts)
15755
15755
  };
15756
15756
  }
15757
- if (net3.isIPv6(address)) {
15757
+ if (net4.isIPv6(address)) {
15758
15758
  return {
15759
15759
  type: 4,
15760
15760
  // IPv6
@@ -15777,7 +15777,7 @@ var require_socks5_utils = __commonJS({
15777
15777
  if (address.includes(".")) {
15778
15778
  const lastColonIndex = address.lastIndexOf(":");
15779
15779
  const ipv4Part = address.slice(lastColonIndex + 1);
15780
- if (net3.isIPv4(ipv4Part)) {
15780
+ if (net4.isIPv4(ipv4Part)) {
15781
15781
  const octets = ipv4Part.split(".").map(Number);
15782
15782
  const high = (octets[0] << 8 | octets[1]).toString(16);
15783
15783
  const low = (octets[2] << 8 | octets[3]).toString(16);
@@ -16496,10 +16496,10 @@ var require_proxy_agent = __commonJS({
16496
16496
  };
16497
16497
  const {
16498
16498
  origin,
16499
- path: path44 = "/",
16499
+ path: path46 = "/",
16500
16500
  headers = {}
16501
16501
  } = opts;
16502
- opts.path = origin + path44;
16502
+ opts.path = origin + path46;
16503
16503
  if (!("host" in headers) && !("Host" in headers)) {
16504
16504
  const { host } = new URL(origin);
16505
16505
  headers.host = host;
@@ -16658,18 +16658,18 @@ var require_proxy_agent = __commonJS({
16658
16658
  }
16659
16659
  }
16660
16660
  [kClose]() {
16661
- const promises = [this[kAgent].close()];
16661
+ const promises2 = [this[kAgent].close()];
16662
16662
  if (this[kClient]) {
16663
- promises.push(this[kClient].close());
16663
+ promises2.push(this[kClient].close());
16664
16664
  }
16665
- return Promise.all(promises);
16665
+ return Promise.all(promises2);
16666
16666
  }
16667
16667
  [kDestroy]() {
16668
- const promises = [this[kAgent].destroy()];
16668
+ const promises2 = [this[kAgent].destroy()];
16669
16669
  if (this[kClient]) {
16670
- promises.push(this[kClient].destroy());
16670
+ promises2.push(this[kClient].destroy());
16671
16671
  }
16672
- return Promise.all(promises);
16672
+ return Promise.all(promises2);
16673
16673
  }
16674
16674
  };
16675
16675
  function buildHeaders(headers) {
@@ -18608,20 +18608,20 @@ var require_mock_utils = __commonJS({
18608
18608
  }
18609
18609
  return normalizedQp;
18610
18610
  }
18611
- function safeUrl(path44) {
18612
- if (typeof path44 !== "string") {
18613
- return path44;
18611
+ function safeUrl(path46) {
18612
+ if (typeof path46 !== "string") {
18613
+ return path46;
18614
18614
  }
18615
- const pathSegments = path44.split("?", 3);
18615
+ const pathSegments = path46.split("?", 3);
18616
18616
  if (pathSegments.length !== 2) {
18617
- return path44;
18617
+ return path46;
18618
18618
  }
18619
18619
  const qp = new URLSearchParams(pathSegments.pop());
18620
18620
  qp.sort();
18621
18621
  return [...pathSegments, qp.toString()].join("?");
18622
18622
  }
18623
- function matchKey(mockDispatch2, { path: path44, method, body, headers }) {
18624
- const pathMatch = matchValue(mockDispatch2.path, path44);
18623
+ function matchKey(mockDispatch2, { path: path46, method, body, headers }) {
18624
+ const pathMatch = matchValue(mockDispatch2.path, path46);
18625
18625
  const methodMatch = matchValue(mockDispatch2.method, method);
18626
18626
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
18627
18627
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -18646,8 +18646,8 @@ var require_mock_utils = __commonJS({
18646
18646
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
18647
18647
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
18648
18648
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
18649
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path44, ignoreTrailingSlash }) => {
18650
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path44)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path44), resolvedPath);
18649
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path46, ignoreTrailingSlash }) => {
18650
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path46)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path46), resolvedPath);
18651
18651
  });
18652
18652
  if (matchedMockDispatches.length === 0) {
18653
18653
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -18686,19 +18686,19 @@ var require_mock_utils = __commonJS({
18686
18686
  mockDispatches.splice(index, 1);
18687
18687
  }
18688
18688
  }
18689
- function removeTrailingSlash(path44) {
18690
- while (path44.endsWith("/")) {
18691
- path44 = path44.slice(0, -1);
18689
+ function removeTrailingSlash(path46) {
18690
+ while (path46.endsWith("/")) {
18691
+ path46 = path46.slice(0, -1);
18692
18692
  }
18693
- if (path44.length === 0) {
18694
- path44 = "/";
18693
+ if (path46.length === 0) {
18694
+ path46 = "/";
18695
18695
  }
18696
- return path44;
18696
+ return path46;
18697
18697
  }
18698
18698
  function buildKey(opts) {
18699
- const { path: path44, method, body, headers, query } = opts;
18699
+ const { path: path46, method, body, headers, query } = opts;
18700
18700
  return {
18701
- path: path44,
18701
+ path: path46,
18702
18702
  method,
18703
18703
  body,
18704
18704
  headers,
@@ -19388,10 +19388,10 @@ var require_pending_interceptors_formatter = __commonJS({
19388
19388
  }
19389
19389
  format(pendingInterceptors) {
19390
19390
  const withPrettyHeaders = pendingInterceptors.map(
19391
- ({ method, path: path44, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
19391
+ ({ method, path: path46, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
19392
19392
  Method: method,
19393
19393
  Origin: origin,
19394
- Path: path44,
19394
+ Path: path46,
19395
19395
  "Status code": statusCode,
19396
19396
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
19397
19397
  Invocations: timesInvoked,
@@ -19473,9 +19473,9 @@ var require_mock_agent = __commonJS({
19473
19473
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
19474
19474
  const dispatchOpts = { ...opts };
19475
19475
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
19476
- const [path44, searchParams] = dispatchOpts.path.split("?");
19476
+ const [path46, searchParams] = dispatchOpts.path.split("?");
19477
19477
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
19478
- dispatchOpts.path = `${path44}?${normalizedSearchParams}`;
19478
+ dispatchOpts.path = `${path46}?${normalizedSearchParams}`;
19479
19479
  }
19480
19480
  return this[kAgent].dispatch(dispatchOpts, handler);
19481
19481
  }
@@ -19876,12 +19876,12 @@ var require_snapshot_recorder = __commonJS({
19876
19876
  * @return {Promise<void>} - Resolves when snapshots are loaded
19877
19877
  */
19878
19878
  async loadSnapshots(filePath) {
19879
- const path44 = filePath || this.#snapshotPath;
19880
- if (!path44) {
19879
+ const path46 = filePath || this.#snapshotPath;
19880
+ if (!path46) {
19881
19881
  throw new InvalidArgumentError2("Snapshot path is required");
19882
19882
  }
19883
19883
  try {
19884
- const data = await readFile(resolve(path44), "utf8");
19884
+ const data = await readFile(resolve(path46), "utf8");
19885
19885
  const parsed = JSON.parse(data);
19886
19886
  if (Array.isArray(parsed)) {
19887
19887
  this.#snapshots.clear();
@@ -19895,7 +19895,7 @@ var require_snapshot_recorder = __commonJS({
19895
19895
  if (error62.code === "ENOENT") {
19896
19896
  this.#snapshots.clear();
19897
19897
  } else {
19898
- throw new UndiciError(`Failed to load snapshots from ${path44}`, { cause: error62 });
19898
+ throw new UndiciError(`Failed to load snapshots from ${path46}`, { cause: error62 });
19899
19899
  }
19900
19900
  }
19901
19901
  }
@@ -19906,11 +19906,11 @@ var require_snapshot_recorder = __commonJS({
19906
19906
  * @returns {Promise<void>} - Resolves when snapshots are saved
19907
19907
  */
19908
19908
  async saveSnapshots(filePath) {
19909
- const path44 = filePath || this.#snapshotPath;
19910
- if (!path44) {
19909
+ const path46 = filePath || this.#snapshotPath;
19910
+ if (!path46) {
19911
19911
  throw new InvalidArgumentError2("Snapshot path is required");
19912
19912
  }
19913
- const resolvedPath = resolve(path44);
19913
+ const resolvedPath = resolve(path46);
19914
19914
  await mkdir(dirname2(resolvedPath), { recursive: true });
19915
19915
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
19916
19916
  hash: hash2,
@@ -20542,15 +20542,15 @@ var require_redirect_handler = __commonJS({
20542
20542
  return;
20543
20543
  }
20544
20544
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
20545
- const path44 = search ? `${pathname}${search}` : pathname;
20546
- const redirectUrlString = `${origin}${path44}`;
20545
+ const path46 = search ? `${pathname}${search}` : pathname;
20546
+ const redirectUrlString = `${origin}${path46}`;
20547
20547
  for (const historyUrl of this.history) {
20548
20548
  if (historyUrl.toString() === redirectUrlString) {
20549
20549
  throw new InvalidArgumentError2(`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.`);
20550
20550
  }
20551
20551
  }
20552
20552
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
20553
- this.opts.path = path44;
20553
+ this.opts.path = path46;
20554
20554
  this.opts.origin = origin;
20555
20555
  this.opts.query = null;
20556
20556
  }
@@ -20817,7 +20817,7 @@ var require_dump = __commonJS({
20817
20817
  var require_dns = __commonJS({
20818
20818
  "node_modules/.pnpm/undici@7.29.1/node_modules/undici/lib/interceptor/dns.js"(exports2, module2) {
20819
20819
  "use strict";
20820
- var { isIP: isIP2 } = require("node:net");
20820
+ var { isIP: isIP3 } = require("node:net");
20821
20821
  var { lookup } = require("node:dns");
20822
20822
  var DecoratorHandler = require_decorator_handler();
20823
20823
  var { InvalidArgumentError: InvalidArgumentError2, InformationalError } = require_errors();
@@ -21223,7 +21223,7 @@ var require_dns = __commonJS({
21223
21223
  return (dispatch) => {
21224
21224
  return function dnsInterceptor(origDispatchOpts, handler) {
21225
21225
  const origin = origDispatchOpts.origin.constructor === URL ? origDispatchOpts.origin : new URL(origDispatchOpts.origin);
21226
- if (isIP2(origin.hostname) !== 0) {
21226
+ if (isIP3(origin.hostname) !== 0) {
21227
21227
  return dispatch(origDispatchOpts, handler);
21228
21228
  }
21229
21229
  instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {
@@ -22310,10 +22310,10 @@ var require_cache_handler = __commonJS({
22310
22310
  }
22311
22311
  return locationUrl.pathname + locationUrl.search;
22312
22312
  }
22313
- function deleteCachedUri(store, cacheKey, path44) {
22313
+ function deleteCachedUri(store, cacheKey, path46) {
22314
22314
  deleteCachedValue(store, {
22315
22315
  ...cacheKey,
22316
- path: path44
22316
+ path: path46
22317
22317
  });
22318
22318
  for (let i2 = 0; i2 < util.safeHTTPMethods.length; i2++) {
22319
22319
  const method = util.safeHTTPMethods[i2];
@@ -22321,7 +22321,7 @@ var require_cache_handler = __commonJS({
22321
22321
  deleteCachedValue(store, {
22322
22322
  ...cacheKey,
22323
22323
  method,
22324
- path: path44
22324
+ path: path46
22325
22325
  });
22326
22326
  }
22327
22327
  }
@@ -22332,9 +22332,9 @@ var require_cache_handler = __commonJS({
22332
22332
  }
22333
22333
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
22334
22334
  for (let i2 = 0; i2 < values.length; i2++) {
22335
- const path44 = getSameOriginPath(cacheKey, values[i2]);
22336
- if (path44 !== void 0) {
22337
- deleteCachedUri(store, cacheKey, path44);
22335
+ const path46 = getSameOriginPath(cacheKey, values[i2]);
22336
+ if (path46 !== void 0) {
22337
+ deleteCachedUri(store, cacheKey, path46);
22338
22338
  }
22339
22339
  }
22340
22340
  }
@@ -27334,11 +27334,11 @@ var require_fetch = __commonJS({
27334
27334
  function dispatch({ body }) {
27335
27335
  const url2 = requestCurrentURL(request7);
27336
27336
  const agent = fetchParams.controller.dispatcher;
27337
- const path44 = url2.pathname + url2.search;
27337
+ const path46 = url2.pathname + url2.search;
27338
27338
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
27339
27339
  return new Promise((resolve, reject) => agent.dispatch(
27340
27340
  {
27341
- path: hasTrailingQuestionMark ? `${path44}?` : path44,
27341
+ path: hasTrailingQuestionMark ? `${path46}?` : path46,
27342
27342
  origin: url2.origin,
27343
27343
  method: request7.method,
27344
27344
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -28285,9 +28285,9 @@ var require_util5 = __commonJS({
28285
28285
  }
28286
28286
  }
28287
28287
  }
28288
- function validateCookiePath(path44) {
28289
- for (let i2 = 0; i2 < path44.length; ++i2) {
28290
- const code = path44.charCodeAt(i2);
28288
+ function validateCookiePath(path46) {
28289
+ for (let i2 = 0; i2 < path46.length; ++i2) {
28290
+ const code = path46.charCodeAt(i2);
28291
28291
  if (code < 32 || // exclude CTLs (0-31)
28292
28292
  code > 126 || // exclude DEL and non-ascii
28293
28293
  code === 59) {
@@ -31635,11 +31635,11 @@ var require_undici = __commonJS({
31635
31635
  if (typeof opts.path !== "string") {
31636
31636
  throw new InvalidArgumentError2("invalid opts.path");
31637
31637
  }
31638
- let path44 = opts.path;
31638
+ let path46 = opts.path;
31639
31639
  if (!opts.path.startsWith("/")) {
31640
- path44 = `/${path44}`;
31640
+ path46 = `/${path46}`;
31641
31641
  }
31642
- url2 = new URL(util.parseOrigin(url2).origin + path44);
31642
+ url2 = new URL(util.parseOrigin(url2).origin + path46);
31643
31643
  } else {
31644
31644
  if (!opts) {
31645
31645
  opts = typeof url2 === "object" ? url2 : {};
@@ -31749,7 +31749,7 @@ ${captureLines}` : capture.stack;
31749
31749
  });
31750
31750
 
31751
31751
  // src/cli.ts
31752
- var import_node_path42 = __toESM(require("node:path"), 1);
31752
+ var import_node_path44 = __toESM(require("node:path"), 1);
31753
31753
 
31754
31754
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
31755
31755
  var CommanderError = class extends Error {
@@ -34862,9 +34862,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
34862
34862
  * @param {string} [path]
34863
34863
  * @return {(string|null|Command)}
34864
34864
  */
34865
- executableDir(path44) {
34866
- if (path44 === void 0) return this._executableDir;
34867
- this._executableDir = path44;
34865
+ executableDir(path46) {
34866
+ if (path46 === void 0) return this._executableDir;
34867
+ this._executableDir = path46;
34868
34868
  return this;
34869
34869
  }
34870
34870
  /**
@@ -36002,15 +36002,15 @@ function mergeDefs(...defs) {
36002
36002
  function cloneDef(schema) {
36003
36003
  return mergeDefs(schema._zod.def);
36004
36004
  }
36005
- function getElementAtPath(obj, path44) {
36006
- if (!path44)
36005
+ function getElementAtPath(obj, path46) {
36006
+ if (!path46)
36007
36007
  return obj;
36008
- return path44.reduce((acc, key) => acc?.[key], obj);
36008
+ return path46.reduce((acc, key) => acc?.[key], obj);
36009
36009
  }
36010
36010
  function promiseAllObject(promisesObj) {
36011
36011
  const keys = Object.keys(promisesObj);
36012
- const promises = keys.map((key) => promisesObj[key]);
36013
- return Promise.all(promises).then((results) => {
36012
+ const promises2 = keys.map((key) => promisesObj[key]);
36013
+ return Promise.all(promises2).then((results) => {
36014
36014
  const resolvedObj = {};
36015
36015
  for (let i2 = 0; i2 < keys.length; i2++) {
36016
36016
  resolvedObj[keys[i2]] = results[i2];
@@ -36345,11 +36345,11 @@ function explicitlyAborted(x, startIndex = 0) {
36345
36345
  }
36346
36346
  return false;
36347
36347
  }
36348
- function prefixIssues(path44, issues) {
36348
+ function prefixIssues(path46, issues) {
36349
36349
  return issues.map((iss) => {
36350
36350
  var _a3;
36351
36351
  (_a3 = iss).path ?? (_a3.path = []);
36352
- iss.path.unshift(path44);
36352
+ iss.path.unshift(path46);
36353
36353
  return iss;
36354
36354
  });
36355
36355
  }
@@ -36799,16 +36799,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
36799
36799
  }
36800
36800
  function formatError(error62, mapper = (issue2) => issue2.message) {
36801
36801
  const fieldErrors = { _errors: [] };
36802
- const processError = (error63, path44 = []) => {
36802
+ const processError = (error63, path46 = []) => {
36803
36803
  for (const issue2 of error63.issues) {
36804
36804
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36805
- issue2.errors.map((issues) => processError({ issues }, [...path44, ...issue2.path]));
36805
+ issue2.errors.map((issues) => processError({ issues }, [...path46, ...issue2.path]));
36806
36806
  } else if (issue2.code === "invalid_key") {
36807
- processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36807
+ processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
36808
36808
  } else if (issue2.code === "invalid_element") {
36809
- processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36809
+ processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
36810
36810
  } else {
36811
- const fullpath = [...path44, ...issue2.path];
36811
+ const fullpath = [...path46, ...issue2.path];
36812
36812
  if (fullpath.length === 0) {
36813
36813
  fieldErrors._errors.push(mapper(issue2));
36814
36814
  } else {
@@ -36847,17 +36847,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
36847
36847
  }
36848
36848
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
36849
36849
  const result = { errors: [] };
36850
- const processError = (error63, path44 = []) => {
36850
+ const processError = (error63, path46 = []) => {
36851
36851
  var _a3;
36852
36852
  for (const issue2 of error63.issues) {
36853
36853
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36854
- issue2.errors.map((issues) => processError({ issues }, [...path44, ...issue2.path]));
36854
+ issue2.errors.map((issues) => processError({ issues }, [...path46, ...issue2.path]));
36855
36855
  } else if (issue2.code === "invalid_key") {
36856
- processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36856
+ processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
36857
36857
  } else if (issue2.code === "invalid_element") {
36858
- processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36858
+ processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
36859
36859
  } else {
36860
- const fullpath = [...path44, ...issue2.path];
36860
+ const fullpath = [...path46, ...issue2.path];
36861
36861
  if (fullpath.length === 0) {
36862
36862
  result.errors.push(mapper(issue2));
36863
36863
  continue;
@@ -36896,8 +36896,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
36896
36896
  }
36897
36897
  function toDotPath(_path) {
36898
36898
  const segs = [];
36899
- const path44 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36900
- for (const seg of path44) {
36899
+ const path46 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36900
+ for (const seg of path46) {
36901
36901
  if (typeof seg === "number")
36902
36902
  segs.push(`[${seg}]`);
36903
36903
  else if (typeof seg === "symbol")
@@ -53999,13 +53999,13 @@ function resolveRef(ref, ctx) {
53999
53999
  if (!ref.startsWith("#")) {
54000
54000
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
54001
54001
  }
54002
- const path44 = ref.slice(1).split("/").filter(Boolean);
54003
- if (path44.length === 0) {
54002
+ const path46 = ref.slice(1).split("/").filter(Boolean);
54003
+ if (path46.length === 0) {
54004
54004
  return ctx.rootSchema;
54005
54005
  }
54006
54006
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
54007
- if (path44[0] === defsKey) {
54008
- const key = path44[1] === void 0 ? void 0 : decodeJSONPointerSegment(path44[1]);
54007
+ if (path46[0] === defsKey) {
54008
+ const key = path46[1] === void 0 ? void 0 : decodeJSONPointerSegment(path46[1]);
54009
54009
  if (!key || !ctx.defs[key]) {
54010
54010
  throw new Error(`Reference not found: ${ref}`);
54011
54011
  }
@@ -55435,16 +55435,16 @@ function parseJson(raw, schema) {
55435
55435
  const parsed = schema.safeParse(JSON.parse(raw));
55436
55436
  return parsed.success ? parsed.data : void 0;
55437
55437
  }
55438
- function readHeadroomState(fs19, stateFile) {
55438
+ function readHeadroomState(fs20, stateFile) {
55439
55439
  try {
55440
- return parseJson(fs19.readFileUtf8(stateFile), HeadroomStateSchema);
55440
+ return parseJson(fs20.readFileUtf8(stateFile), HeadroomStateSchema);
55441
55441
  } catch {
55442
55442
  return void 0;
55443
55443
  }
55444
55444
  }
55445
- function writeHeadroomState(fs19, stateFile, state) {
55446
- fs19.mkdirp(import_node_path5.default.dirname(stateFile));
55447
- fs19.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55445
+ function writeHeadroomState(fs20, stateFile, state) {
55446
+ fs20.mkdirp(import_node_path5.default.dirname(stateFile));
55447
+ fs20.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55448
55448
  `);
55449
55449
  }
55450
55450
  function headroomAllowlist(providers) {
@@ -55464,14 +55464,14 @@ function headroomUpstreams(providers, frontDoorOrigin2) {
55464
55464
  function hashAllowlist(allowlist) {
55465
55465
  return (0, import_node_crypto2.createHash)("sha256").update(allowlist.join("\n")).digest("hex");
55466
55466
  }
55467
- function readAllProviders(fs19, providersDir) {
55467
+ function readAllProviders(fs20, providersDir) {
55468
55468
  const result = [];
55469
- for (const name of fs19.readdir(providersDir)) {
55469
+ for (const name of fs20.readdir(providersDir)) {
55470
55470
  if (!name.endsWith(".json")) {
55471
55471
  continue;
55472
55472
  }
55473
55473
  try {
55474
- const parsed = parseJson(fs19.readFileUtf8(import_node_path5.default.join(providersDir, name)), ProviderSchema);
55474
+ const parsed = parseJson(fs20.readFileUtf8(import_node_path5.default.join(providersDir, name)), ProviderSchema);
55475
55475
  if (parsed !== void 0) {
55476
55476
  result.push({ name: name.slice(0, -".json".length), provider: parsed });
55477
55477
  }
@@ -55481,22 +55481,22 @@ function readAllProviders(fs19, providersDir) {
55481
55481
  }
55482
55482
  return result;
55483
55483
  }
55484
- function writeSession(fs19, sessionsDir, session) {
55485
- fs19.mkdirp(sessionsDir);
55486
- fs19.writeFileUtf8(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55484
+ function writeSession(fs20, sessionsDir, session) {
55485
+ fs20.mkdirp(sessionsDir);
55486
+ fs20.writeFileUtf8(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55487
55487
  `);
55488
55488
  }
55489
- function removeSession(fs19, sessionsDir, pid) {
55490
- fs19.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
55489
+ function removeSession(fs20, sessionsDir, pid) {
55490
+ fs20.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
55491
55491
  }
55492
- function listSessions(fs19, sessionsDir) {
55492
+ function listSessions(fs20, sessionsDir) {
55493
55493
  const sessions = [];
55494
- for (const name of fs19.readdir(sessionsDir)) {
55494
+ for (const name of fs20.readdir(sessionsDir)) {
55495
55495
  if (!name.endsWith(".json")) {
55496
55496
  continue;
55497
55497
  }
55498
55498
  try {
55499
- const parsed = parseJson(fs19.readFileUtf8(import_node_path5.default.join(sessionsDir, name)), HeadroomSessionSchema);
55499
+ const parsed = parseJson(fs20.readFileUtf8(import_node_path5.default.join(sessionsDir, name)), HeadroomSessionSchema);
55500
55500
  if (parsed !== void 0) {
55501
55501
  sessions.push(parsed);
55502
55502
  }
@@ -55506,22 +55506,22 @@ function listSessions(fs19, sessionsDir) {
55506
55506
  }
55507
55507
  return sessions.sort((a2, b) => a2.pid - b.pid);
55508
55508
  }
55509
- function sessionsForSupervisor(fs19, sessionsDir, supervisorPid) {
55510
- return listSessions(fs19, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
55509
+ function sessionsForSupervisor(fs20, sessionsDir, supervisorPid) {
55510
+ return listSessions(fs20, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
55511
55511
  }
55512
- function pruneDeadSessions(fs19, sessionsDir, isRunning) {
55512
+ function pruneDeadSessions(fs20, sessionsDir, isRunning) {
55513
55513
  const removed = [];
55514
- for (const session of listSessions(fs19, sessionsDir)) {
55514
+ for (const session of listSessions(fs20, sessionsDir)) {
55515
55515
  if (!isRunning(session.pid)) {
55516
- removeSession(fs19, sessionsDir, session.pid);
55516
+ removeSession(fs20, sessionsDir, session.pid);
55517
55517
  removed.push(session.pid);
55518
55518
  }
55519
55519
  }
55520
55520
  return removed;
55521
55521
  }
55522
- function readStartLock(fs19, lockFile) {
55522
+ function readStartLock(fs20, lockFile) {
55523
55523
  try {
55524
- return parseJson(fs19.readFileUtf8(lockFile), HeadroomLockSchema);
55524
+ return parseJson(fs20.readFileUtf8(lockFile), HeadroomLockSchema);
55525
55525
  } catch {
55526
55526
  return void 0;
55527
55527
  }
@@ -55626,10 +55626,10 @@ var FrontDoorStateSchema = external_exports.strictObject({
55626
55626
  /** The last fatal error, kept across shutdowns so `frontdoor status` can explain a front door that is not running. */
55627
55627
  lastError: external_exports.string().optional()
55628
55628
  });
55629
- function readFrontDoorState(fs19, stateFile) {
55629
+ function readFrontDoorState(fs20, stateFile) {
55630
55630
  let raw;
55631
55631
  try {
55632
- raw = fs19.readFileUtf8(stateFile);
55632
+ raw = fs20.readFileUtf8(stateFile);
55633
55633
  } catch {
55634
55634
  return void 0;
55635
55635
  }
@@ -55643,28 +55643,28 @@ function readFrontDoorState(fs19, stateFile) {
55643
55643
  return void 0;
55644
55644
  }
55645
55645
  }
55646
- function writeFrontDoorState(fs19, stateFile, state) {
55647
- fs19.mkdirp(import_node_path6.default.dirname(stateFile));
55648
- fs19.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55646
+ function writeFrontDoorState(fs20, stateFile, state) {
55647
+ fs20.mkdirp(import_node_path6.default.dirname(stateFile));
55648
+ fs20.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55649
55649
  `);
55650
55650
  }
55651
55651
  function frontDoorOrigin(state) {
55652
55652
  const port = state?.directPort ?? state?.lastDirectPort;
55653
55653
  return port === void 0 ? void 0 : `http://127.0.0.1:${String(port)}`;
55654
55654
  }
55655
- function writeFrontDoorSession(fs19, sessionsDir, session) {
55656
- fs19.mkdirPrivate(sessionsDir);
55657
- fs19.writeFilePrivate(import_node_path6.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55655
+ function writeFrontDoorSession(fs20, sessionsDir, session) {
55656
+ fs20.mkdirPrivate(sessionsDir);
55657
+ fs20.writeFilePrivate(import_node_path6.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55658
55658
  `);
55659
55659
  }
55660
- function listFrontDoorSessions(fs19, sessionsDir) {
55660
+ function listFrontDoorSessions(fs20, sessionsDir) {
55661
55661
  const sessions = [];
55662
- for (const name of fs19.readdir(sessionsDir)) {
55662
+ for (const name of fs20.readdir(sessionsDir)) {
55663
55663
  if (!name.endsWith(".json")) {
55664
55664
  continue;
55665
55665
  }
55666
55666
  try {
55667
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path6.default.join(sessionsDir, name)) ?? ""));
55667
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs20.readFileUtf8(import_node_path6.default.join(sessionsDir, name)) ?? ""));
55668
55668
  if (parsed.success) {
55669
55669
  sessions.push({ pid: parsed.data.pid, startedAt: parsed.data.startedAt });
55670
55670
  }
@@ -55674,27 +55674,27 @@ function listFrontDoorSessions(fs19, sessionsDir) {
55674
55674
  }
55675
55675
  return sessions.sort((a2, b) => a2.pid - b.pid);
55676
55676
  }
55677
- function removeFrontDoorSession(fs19, sessionsDir, pid) {
55678
- fs19.removeRecursive(import_node_path6.default.join(sessionsDir, `${String(pid)}.json`));
55677
+ function removeFrontDoorSession(fs20, sessionsDir, pid) {
55678
+ fs20.removeRecursive(import_node_path6.default.join(sessionsDir, `${String(pid)}.json`));
55679
55679
  }
55680
- function pruneDeadFrontDoorSessions(fs19, sessionsDir, isRunning) {
55680
+ function pruneDeadFrontDoorSessions(fs20, sessionsDir, isRunning) {
55681
55681
  const removed = [];
55682
- for (const session of listFrontDoorSessions(fs19, sessionsDir)) {
55682
+ for (const session of listFrontDoorSessions(fs20, sessionsDir)) {
55683
55683
  if (!isRunning(session.pid)) {
55684
- removeFrontDoorSession(fs19, sessionsDir, session.pid);
55684
+ removeFrontDoorSession(fs20, sessionsDir, session.pid);
55685
55685
  removed.push(session.pid);
55686
55686
  }
55687
55687
  }
55688
55688
  return removed;
55689
55689
  }
55690
- function liveSessionTokens(fs19, sessionsDir) {
55690
+ function liveSessionTokens(fs20, sessionsDir) {
55691
55691
  const tokens = /* @__PURE__ */ new Set();
55692
- for (const name of fs19.readdir(sessionsDir)) {
55692
+ for (const name of fs20.readdir(sessionsDir)) {
55693
55693
  if (!name.endsWith(".json")) {
55694
55694
  continue;
55695
55695
  }
55696
55696
  try {
55697
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path6.default.join(sessionsDir, name)) ?? ""));
55697
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs20.readFileUtf8(import_node_path6.default.join(sessionsDir, name)) ?? ""));
55698
55698
  if (parsed.success) {
55699
55699
  tokens.add(parsed.data.token);
55700
55700
  }
@@ -55777,7 +55777,7 @@ function verifyHeadroomSocket(socketPath, ports) {
55777
55777
  const refusal = ownerOnlyRefusal("socket directory", directory, ports.lstat(directory), "dir", uid) ?? ownerOnlyRefusal("socket", socketPath, ports.lstat(socketPath), "socket", uid);
55778
55778
  return refusal === void 0 ? { socketPath } : { refused: refusal };
55779
55779
  }
55780
- function prepareHeadroomSocket(fs19, ports, paths, supervisorPid) {
55780
+ function prepareHeadroomSocket(fs20, ports, paths, supervisorPid) {
55781
55781
  const unsupported = platformRefusal(ports.platform);
55782
55782
  if (unsupported !== void 0) {
55783
55783
  return { refused: unsupported };
@@ -55792,18 +55792,18 @@ function prepareHeadroomSocket(fs19, ports, paths, supervisorPid) {
55792
55792
  if (ports.lstat(paths.headroomSocketDir)?.kind === "symlink") {
55793
55793
  return { refused: `the headroom socket directory ${paths.headroomSocketDir} is a symlink; it must be the real directory` };
55794
55794
  }
55795
- fs19.mkdirPrivate(paths.headroomSocketDir);
55795
+ fs20.mkdirPrivate(paths.headroomSocketDir);
55796
55796
  const refusal = ownerOnlyRefusal("socket directory", paths.headroomSocketDir, ports.lstat(paths.headroomSocketDir), "dir", ports.currentUid());
55797
55797
  return refusal === void 0 ? { socketPath } : { refused: refusal };
55798
55798
  }
55799
- function pruneStaleHeadroomSockets(fs19, paths, isRunning) {
55799
+ function pruneStaleHeadroomSockets(fs20, paths, isRunning) {
55800
55800
  const removed = [];
55801
- for (const name of fs19.readdir(paths.headroomSocketDir)) {
55801
+ for (const name of fs20.readdir(paths.headroomSocketDir)) {
55802
55802
  const pid = HEADROOM_SOCKET_NAME.exec(name)?.[1];
55803
55803
  if (pid === void 0 || isRunning(Number.parseInt(pid, 10))) {
55804
55804
  continue;
55805
55805
  }
55806
- fs19.removeRecursive(import_node_path7.default.join(paths.headroomSocketDir, name));
55806
+ fs20.removeRecursive(import_node_path7.default.join(paths.headroomSocketDir, name));
55807
55807
  removed.push(name);
55808
55808
  }
55809
55809
  return removed;
@@ -55933,28 +55933,28 @@ function compareVersions2(a2, b) {
55933
55933
  }
55934
55934
  var HEADROOM_SUPERVISOR_STILL_RUNNING = -1;
55935
55935
  async function runSupervisor(initialConfig, ports, options = {}) {
55936
- const { fs: fs19, paths } = ports;
55936
+ const { fs: fs20, paths } = ports;
55937
55937
  let config2 = initialConfig;
55938
- const previousState = readHeadroomState(fs19, paths.headroomStateFile);
55938
+ const previousState = readHeadroomState(fs20, paths.headroomStateFile);
55939
55939
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
55940
55940
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
55941
55941
  return 0;
55942
55942
  }
55943
55943
  let installedSource = previousState?.installedSource;
55944
55944
  const ownsState = () => {
55945
- const owner = readHeadroomState(fs19, paths.headroomStateFile)?.supervisorPid;
55945
+ const owner = readHeadroomState(fs20, paths.headroomStateFile)?.supervisorPid;
55946
55946
  return owner === void 0 || owner === ports.ownPid || !ports.isRunning(owner);
55947
55947
  };
55948
55948
  const writeOwnState = (state) => {
55949
55949
  if (!ownsState()) {
55950
55950
  return false;
55951
55951
  }
55952
- writeHeadroomState(fs19, paths.headroomStateFile, state);
55952
+ writeHeadroomState(fs20, paths.headroomStateFile, state);
55953
55953
  return true;
55954
55954
  };
55955
55955
  const fail = (message) => {
55956
55956
  if (writeOwnState({ lastError: message })) {
55957
- fs19.removeRecursive(paths.headroomLockFile);
55957
+ fs20.removeRecursive(paths.headroomLockFile);
55958
55958
  }
55959
55959
  ports.log(`agent-shim headroom supervisor: ${message}`);
55960
55960
  return 1;
@@ -55976,12 +55976,12 @@ async function runSupervisor(initialConfig, ports, options = {}) {
55976
55976
  installedSource = config2.source;
55977
55977
  return true;
55978
55978
  };
55979
- const socket = prepareHeadroomSocket(fs19, ports.socketTrust, paths, ports.ownPid);
55979
+ const socket = prepareHeadroomSocket(fs20, ports.socketTrust, paths, ports.ownPid);
55980
55980
  if (socket.refused !== void 0) {
55981
55981
  return fail(socket.refused);
55982
55982
  }
55983
55983
  const { socketPath } = socket;
55984
- pruneStaleHeadroomSockets(fs19, paths, ports.isRunning);
55984
+ pruneStaleHeadroomSockets(fs20, paths, ports.isRunning);
55985
55985
  if (!ensureInstalled()) {
55986
55986
  return fail(`could not install headroom from ${config2.source}: install failed (is uv installed and on PATH?)`);
55987
55987
  }
@@ -56009,7 +56009,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
56009
56009
  const settingsHash = hashSettings(config2.settings);
56010
56010
  const allowlist = allowlistOf(ports);
56011
56011
  const allowlistHash = hashAllowlist(allowlist);
56012
- pruneDeadSessions(fs19, paths.headroomSessionsDir, ports.isRunning);
56012
+ pruneDeadSessions(fs20, paths.headroomSessionsDir, ports.isRunning);
56013
56013
  const ownsNow = ownsState();
56014
56014
  if (!ownsNow && !superseded) {
56015
56015
  ports.log("agent-shim headroom supervisor: another supervisor now owns the state file; serving this daemon's own sessions until they end");
@@ -56051,7 +56051,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
56051
56051
  installedSource: config2.source
56052
56052
  });
56053
56053
  if (recorded) {
56054
- fs19.removeRecursive(paths.headroomLockFile);
56054
+ fs20.removeRecursive(paths.headroomLockFile);
56055
56055
  }
56056
56056
  idleSince = void 0;
56057
56057
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(pid)} ready on unix socket ${socketPath}`);
@@ -56066,7 +56066,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
56066
56066
  }
56067
56067
  } else {
56068
56068
  if (runningHash !== allowlistHash || runningSettingsHash !== settingsHash || installedSource !== config2.source) {
56069
- if (sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid).length === 0) {
56069
+ if (sessionsForSupervisor(fs20, paths.headroomSessionsDir, ports.ownPid).length === 0) {
56070
56070
  ports.log("agent-shim headroom supervisor: configuration drifted and no sessions are live; restarting headroom");
56071
56071
  ports.stopProcess(headroomPid);
56072
56072
  headroomPid = void 0;
@@ -56075,7 +56075,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
56075
56075
  continue;
56076
56076
  }
56077
56077
  }
56078
- const sessions = sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid);
56078
+ const sessions = sessionsForSupervisor(fs20, paths.headroomSessionsDir, ports.ownPid);
56079
56079
  if (sessions.length === 0) {
56080
56080
  idleSince ??= ports.now();
56081
56081
  const idleMs = ports.now() - idleSince;
@@ -56094,9 +56094,9 @@ async function runSupervisor(initialConfig, ports, options = {}) {
56094
56094
  await ports.sleep(HEADROOM_POLL_MS);
56095
56095
  }
56096
56096
  }
56097
- function currentHeadroomAllowlist(fs19, paths) {
56098
- const providers = readAllProviders(fs19, paths.providersDir).map((entry) => entry.provider);
56099
- return headroomAllowlist(headroomUpstreams(providers, frontDoorOrigin(readFrontDoorState(fs19, paths.frontdoorStateFile))));
56097
+ function currentHeadroomAllowlist(fs20, paths) {
56098
+ const providers = readAllProviders(fs20, paths.providersDir).map((entry) => entry.provider);
56099
+ return headroomAllowlist(headroomUpstreams(providers, frontDoorOrigin(readFrontDoorState(fs20, paths.frontdoorStateFile))));
56100
56100
  }
56101
56101
  function allowlistOf(ports) {
56102
56102
  return currentHeadroomAllowlist(ports.fs, ports.paths);
@@ -58142,8 +58142,8 @@ function decideConfigProfile(params) {
58142
58142
  }
58143
58143
  return { source: "none" };
58144
58144
  }
58145
- function loadIdentity(identitiesDir, name, fs19) {
58146
- return loadConfigFile(import_node_path10.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs19.readConfigFile);
58145
+ function loadIdentity(identitiesDir, name, fs20) {
58146
+ return loadConfigFile(import_node_path10.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs20.readConfigFile);
58147
58147
  }
58148
58148
 
58149
58149
  // src/configProfilesStore.ts
@@ -58311,19 +58311,19 @@ function writePools(paths, pools) {
58311
58311
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
58312
58312
  }
58313
58313
  function poolCycleOf(pools, name) {
58314
- const walk = (current, path44) => {
58314
+ const walk = (current, path46) => {
58315
58315
  for (const entry of pools[current]?.identities ?? []) {
58316
58316
  const nested = poolNameOf(entry);
58317
58317
  if (nested === void 0) {
58318
58318
  continue;
58319
58319
  }
58320
58320
  if (nested === name) {
58321
- return [...path44, nested];
58321
+ return [...path46, nested];
58322
58322
  }
58323
- if (path44.includes(nested)) {
58323
+ if (path46.includes(nested)) {
58324
58324
  continue;
58325
58325
  }
58326
- const found = walk(nested, [...path44, nested]);
58326
+ const found = walk(nested, [...path46, nested]);
58327
58327
  if (found !== void 0) {
58328
58328
  return found;
58329
58329
  }
@@ -59815,8 +59815,8 @@ var FarmManifestSchema = external_exports.strictObject({
59815
59815
  materialised: external_exports.array(external_exports.string()),
59816
59816
  links: external_exports.array(external_exports.strictObject({ rel: external_exports.string(), target: external_exports.string() }))
59817
59817
  });
59818
- function readFarmManifest(fs19, farmRoot) {
59819
- const raw = fs19.readFileUtf8(import_node_path18.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs19.readFileUtf8(import_node_path18.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
59818
+ function readFarmManifest(fs20, farmRoot) {
59819
+ const raw = fs20.readFileUtf8(import_node_path18.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs20.readFileUtf8(import_node_path18.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
59820
59820
  if (raw === void 0) {
59821
59821
  return void 0;
59822
59822
  }
@@ -59874,9 +59874,9 @@ function buildEntryFacts(params) {
59874
59874
  entries
59875
59875
  };
59876
59876
  }
59877
- function listSubtree(fs19, root, rel) {
59877
+ function listSubtree(fs20, root, rel) {
59878
59878
  const absolute = import_node_path18.default.join(root, rel);
59879
- const stat = fs19.lstat(absolute);
59879
+ const stat = fs20.lstat(absolute);
59880
59880
  if (stat === void 0) {
59881
59881
  return [];
59882
59882
  }
@@ -59884,10 +59884,10 @@ function listSubtree(fs19, root, rel) {
59884
59884
  return [{ rel, kind: "symlink" }];
59885
59885
  }
59886
59886
  if (stat.kind === "dir") {
59887
- const children = [...fs19.readdir(absolute)].sort().flatMap((name) => listSubtree(fs19, root, `${rel}/${name}`));
59887
+ const children = [...fs20.readdir(absolute)].sort().flatMap((name) => listSubtree(fs20, root, `${rel}/${name}`));
59888
59888
  return [{ rel, kind: "dir" }, ...children];
59889
59889
  }
59890
- const contentHash = fs19.hashFile(absolute);
59890
+ const contentHash = fs20.hashFile(absolute);
59891
59891
  return [{ rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } }];
59892
59892
  }
59893
59893
  function topLevelScopeRoots(roots) {
@@ -59901,25 +59901,25 @@ function topLevelScopeRoots(roots) {
59901
59901
  }
59902
59902
  return kept;
59903
59903
  }
59904
- function reconciliationScope(fs19, farmRoot, manifest) {
59904
+ function reconciliationScope(fs20, farmRoot, manifest) {
59905
59905
  if (manifest !== void 0) {
59906
59906
  return topLevelScopeRoots(manifest.materialised);
59907
59907
  }
59908
- return [...fs19.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs19.lstat(import_node_path18.default.join(farmRoot, name))?.kind === "dir").sort();
59908
+ return [...fs20.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs20.lstat(import_node_path18.default.join(farmRoot, name))?.kind === "dir").sort();
59909
59909
  }
59910
- function collectFarmListing(fs19, farmRoot, scopeRoots) {
59911
- return scopeRoots.flatMap((root) => listSubtree(fs19, farmRoot, root));
59910
+ function collectFarmListing(fs20, farmRoot, scopeRoots) {
59911
+ return scopeRoots.flatMap((root) => listSubtree(fs20, farmRoot, root));
59912
59912
  }
59913
- function collectCanonicalCounterparts(fs19, claudeHome, farmListing) {
59913
+ function collectCanonicalCounterparts(fs20, claudeHome, farmListing) {
59914
59914
  const out = [];
59915
59915
  for (const entry of farmListing) {
59916
59916
  const absolute = import_node_path18.default.join(claudeHome, entry.rel);
59917
- const stat = fs19.lstat(absolute);
59917
+ const stat = fs20.lstat(absolute);
59918
59918
  if (stat === void 0) {
59919
59919
  continue;
59920
59920
  }
59921
59921
  if (stat.kind === "file") {
59922
- const contentHash = fs19.hashFile(absolute);
59922
+ const contentHash = fs20.hashFile(absolute);
59923
59923
  out.push({ rel: entry.rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } });
59924
59924
  continue;
59925
59925
  }
@@ -61790,7 +61790,7 @@ function registerIdentityCommand(program2, deps) {
61790
61790
  // package.json
61791
61791
  var package_default = {
61792
61792
  name: "agent-shim",
61793
- version: "8.20.2",
61793
+ version: "8.21.1",
61794
61794
  description: "A profile manager and launcher for Claude Code that lets one person run multiple logins from one machine while controlling what gets shared between them.",
61795
61795
  license: "MIT",
61796
61796
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -62068,12 +62068,12 @@ function isIdentityName(name) {
62068
62068
  function claudeJsonPath(identitiesDir, identity) {
62069
62069
  return import_node_path23.default.join(identitiesDir, identity, CLAUDE_JSON);
62070
62070
  }
62071
- function readAccountMetadata(fs19, identitiesDir, identity) {
62071
+ function readAccountMetadata(fs20, identitiesDir, identity) {
62072
62072
  if (!isIdentityName(identity)) {
62073
62073
  throw new Error(`"${identity}" is not a valid identity name.`);
62074
62074
  }
62075
62075
  const file2 = claudeJsonPath(identitiesDir, identity);
62076
- const raw = fs19.readFileUtf8(file2);
62076
+ const raw = fs20.readFileUtf8(file2);
62077
62077
  if (raw === void 0) {
62078
62078
  return void 0;
62079
62079
  }
@@ -62103,19 +62103,19 @@ function readAccountMetadata(fs19, identitiesDir, identity) {
62103
62103
  }
62104
62104
  return account.data;
62105
62105
  }
62106
- function createAccountReader(fs19, identitiesDir) {
62106
+ function createAccountReader(fs20, identitiesDir) {
62107
62107
  const cache = /* @__PURE__ */ new Map();
62108
62108
  return (identity) => {
62109
62109
  if (!isIdentityName(identity)) {
62110
62110
  throw new Error(`"${identity}" is not a valid identity name.`);
62111
62111
  }
62112
- const stat = fs19.lstat(claudeJsonPath(identitiesDir, identity));
62112
+ const stat = fs20.lstat(claudeJsonPath(identitiesDir, identity));
62113
62113
  const stamp = stat === void 0 ? "absent" : `${String(stat.mtimeMs)}:${String(stat.sizeBytes)}`;
62114
62114
  const cached2 = cache.get(identity);
62115
62115
  if (cached2?.stamp === stamp) {
62116
62116
  return cached2.account;
62117
62117
  }
62118
- const account = readAccountMetadata(fs19, identitiesDir, identity);
62118
+ const account = readAccountMetadata(fs20, identitiesDir, identity);
62119
62119
  cache.set(identity, { stamp, account });
62120
62120
  return account;
62121
62121
  };
@@ -62222,11 +62222,11 @@ var PROVIDER_PATH_PREFIX = "/providers/";
62222
62222
  function directOrigin(port) {
62223
62223
  return `http://127.0.0.1:${String(port)}`;
62224
62224
  }
62225
- function parseProviderPath(path44) {
62226
- if (!path44.startsWith(PROVIDER_PATH_PREFIX)) {
62225
+ function parseProviderPath(path46) {
62226
+ if (!path46.startsWith(PROVIDER_PATH_PREFIX)) {
62227
62227
  return void 0;
62228
62228
  }
62229
- const tail = path44.slice(PROVIDER_PATH_PREFIX.length);
62229
+ const tail = path46.slice(PROVIDER_PATH_PREFIX.length);
62230
62230
  const slash = tail.indexOf("/");
62231
62231
  if (slash <= 0) {
62232
62232
  return void 0;
@@ -62626,9 +62626,9 @@ function decoderFor(encoding) {
62626
62626
  return void 0;
62627
62627
  }
62628
62628
  }
62629
- function destinationOf(path44) {
62630
- const scoped = parseProviderPath(path44);
62631
- return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path44 } : { provider: scoped.provider, endpoint: scoped.rest };
62629
+ function destinationOf(path46) {
62630
+ const scoped = parseProviderPath(path46);
62631
+ return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path46 } : { provider: scoped.provider, endpoint: scoped.rest };
62632
62632
  }
62633
62633
  function buildRecord(event, context) {
62634
62634
  const { scan } = context;
@@ -62923,8 +62923,8 @@ function segmentDay(epochMs) {
62923
62923
  function segmentName(day, pid) {
62924
62924
  return `${day}.${String(pid)}.jsonl`;
62925
62925
  }
62926
- function listLogSegments(fs19, logDir) {
62927
- return fs19.readdir(logDir).flatMap((name) => {
62926
+ function listLogSegments(fs20, logDir) {
62927
+ return fs20.readdir(logDir).flatMap((name) => {
62928
62928
  const match = SEGMENT_RE.exec(name);
62929
62929
  const day = match?.[1];
62930
62930
  if (day === void 0) {
@@ -62933,15 +62933,15 @@ function listLogSegments(fs19, logDir) {
62933
62933
  return [{ name, day, endsAt: Date.parse(`${day}T00:00:00.000Z`) + DAY_MS }];
62934
62934
  }).sort((left, right) => left.day.localeCompare(right.day) || left.name.localeCompare(right.name));
62935
62935
  }
62936
- function readUsageLog(fs19, logDir, options = {}) {
62936
+ function readUsageLog(fs20, logDir, options = {}) {
62937
62937
  const { sinceMs } = options;
62938
62938
  const records = [];
62939
62939
  let invalidLines = 0;
62940
- for (const segment of listLogSegments(fs19, logDir)) {
62940
+ for (const segment of listLogSegments(fs20, logDir)) {
62941
62941
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
62942
62942
  continue;
62943
62943
  }
62944
- const contents = fs19.readFileUtf8(import_node_path24.default.join(logDir, segment.name));
62944
+ const contents = fs20.readFileUtf8(import_node_path24.default.join(logDir, segment.name));
62945
62945
  if (contents === void 0) {
62946
62946
  continue;
62947
62947
  }
@@ -62985,9 +62985,9 @@ function snapshotPath(snapshotsDir, identity) {
62985
62985
  }
62986
62986
  return import_node_path24.default.join(snapshotsDir, `${identity}.json`);
62987
62987
  }
62988
- function readUsageSnapshot(fs19, snapshotsDir, identity) {
62988
+ function readUsageSnapshot(fs20, snapshotsDir, identity) {
62989
62989
  const file2 = snapshotPath(snapshotsDir, identity);
62990
- const raw = fs19.readFileUtf8(file2);
62990
+ const raw = fs20.readFileUtf8(file2);
62991
62991
  if (raw === void 0) {
62992
62992
  return void 0;
62993
62993
  }
@@ -63003,8 +63003,8 @@ function readUsageSnapshot(fs19, snapshotsDir, identity) {
63003
63003
  }
63004
63004
  return snapshot.data;
63005
63005
  }
63006
- function listUsageSnapshots(fs19, snapshotsDir) {
63007
- return fs19.readdir(snapshotsDir).flatMap((name) => {
63006
+ function listUsageSnapshots(fs20, snapshotsDir) {
63007
+ return fs20.readdir(snapshotsDir).flatMap((name) => {
63008
63008
  if (!name.endsWith(".json")) {
63009
63009
  return [];
63010
63010
  }
@@ -63012,7 +63012,7 @@ function listUsageSnapshots(fs19, snapshotsDir) {
63012
63012
  if (!isIdentityName(identity)) {
63013
63013
  return [];
63014
63014
  }
63015
- const snapshot = readUsageSnapshot(fs19, snapshotsDir, identity);
63015
+ const snapshot = readUsageSnapshot(fs20, snapshotsDir, identity);
63016
63016
  return snapshot === void 0 ? [] : [snapshot];
63017
63017
  }).sort((left, right) => left.identity.localeCompare(right.identity));
63018
63018
  }
@@ -63071,11 +63071,11 @@ var import_node_path25 = __toESM(require("node:path"), 1);
63071
63071
  var DAY_MS2 = 864e5;
63072
63072
  var DAYS_IN_WEEK = 7;
63073
63073
  var USAGE_RETENTION_MS = DAYS_IN_WEEK * DAY_MS2;
63074
- function pruneUsageLog(fs19, logDir, nowMs) {
63074
+ function pruneUsageLog(fs20, logDir, nowMs) {
63075
63075
  const cutoff = nowMs - USAGE_RETENTION_MS;
63076
- for (const segment of listLogSegments(fs19, logDir)) {
63076
+ for (const segment of listLogSegments(fs20, logDir)) {
63077
63077
  if (segment.endsAt <= cutoff) {
63078
- fs19.removeRecursive(import_node_path25.default.join(logDir, segment.name));
63078
+ fs20.removeRecursive(import_node_path25.default.join(logDir, segment.name));
63079
63079
  }
63080
63080
  }
63081
63081
  }
@@ -63104,7 +63104,7 @@ function foldProviderState(current, record2) {
63104
63104
  };
63105
63105
  }
63106
63106
  function createUsageStore(deps) {
63107
- const { fs: fs19, paths } = deps;
63107
+ const { fs: fs20, paths } = deps;
63108
63108
  let prunedDay;
63109
63109
  const rewriteSnapshot = (identity, fold) => {
63110
63110
  if (!isIdentityName(identity)) {
@@ -63113,7 +63113,7 @@ function createUsageStore(deps) {
63113
63113
  }
63114
63114
  let current;
63115
63115
  try {
63116
- current = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
63116
+ current = readUsageSnapshot(fs20, paths.usageSnapshotsDir, identity);
63117
63117
  } catch (error62) {
63118
63118
  if (!(error62 instanceof UsageSnapshotError)) {
63119
63119
  throw error62;
@@ -63140,8 +63140,8 @@ function createUsageStore(deps) {
63140
63140
  ...account === void 0 ? {} : { account },
63141
63141
  providers
63142
63142
  });
63143
- fs19.mkdirPrivate(paths.usageSnapshotsDir);
63144
- fs19.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
63143
+ fs20.mkdirPrivate(paths.usageSnapshotsDir);
63144
+ fs20.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
63145
63145
  `);
63146
63146
  return true;
63147
63147
  };
@@ -63149,14 +63149,14 @@ function createUsageStore(deps) {
63149
63149
  record: (input2) => {
63150
63150
  const record2 = UsageRecordSchema.parse(input2);
63151
63151
  const nowMs = deps.now();
63152
- fs19.mkdirPrivate(paths.usageDir);
63153
- fs19.mkdirPrivate(paths.usageLogDir);
63152
+ fs20.mkdirPrivate(paths.usageDir);
63153
+ fs20.mkdirPrivate(paths.usageLogDir);
63154
63154
  const day = segmentDay(nowMs);
63155
63155
  if (prunedDay !== day) {
63156
- pruneUsageLog(fs19, paths.usageLogDir, nowMs);
63156
+ pruneUsageLog(fs20, paths.usageLogDir, nowMs);
63157
63157
  prunedDay = day;
63158
63158
  }
63159
- fs19.appendFilePrivate(import_node_path25.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
63159
+ fs20.appendFilePrivate(import_node_path25.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
63160
63160
  `);
63161
63161
  if (record2.identity !== void 0) {
63162
63162
  rewriteSnapshot(record2.identity, (current) => ({ ...current?.providers, [record2.provider]: foldProviderState(current?.providers[record2.provider], record2) }));
@@ -63189,14 +63189,14 @@ var PicksFileSchema = external_exports.strictObject({
63189
63189
  function errorMessage(error62) {
63190
63190
  return error62 instanceof Error ? error62.message : String(error62);
63191
63191
  }
63192
- function loadPoolMembers(fs19, paths, identities, nowMs) {
63192
+ function loadPoolMembers(fs20, paths, identities, nowMs) {
63193
63193
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
63194
- const log = readUsageLog(fs19, paths.usageLogDir, { sinceMs: windowStartMs });
63194
+ const log = readUsageLog(fs20, paths.usageLogDir, { sinceMs: windowStartMs });
63195
63195
  return identities.map((identity) => {
63196
63196
  const records = log.records.filter((record2) => record2.identity === identity && record2.provider === ANTHROPIC_PROVIDER && Date.parse(record2.at) >= windowStartMs);
63197
63197
  try {
63198
- const snapshot = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
63199
- const account = readAccountMetadata(fs19, paths.identitiesDir, identity) ?? snapshot?.account;
63198
+ const snapshot = readUsageSnapshot(fs20, paths.usageSnapshotsDir, identity);
63199
+ const account = readAccountMetadata(fs20, paths.identitiesDir, identity) ?? snapshot?.account;
63200
63200
  return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
63201
63201
  } catch (error62) {
63202
63202
  if (error62 instanceof UsageSnapshotError || error62 instanceof AccountMetadataError) {
@@ -63264,9 +63264,9 @@ function nestedMember(input2, nestedName, childStack, sticky) {
63264
63264
  missing: nested.missing
63265
63265
  };
63266
63266
  }
63267
- function readPicksFile(fs19, file2) {
63267
+ function readPicksFile(fs20, file2) {
63268
63268
  const empty = { schemaVersion: SCHEMA_VERSION, picks: {} };
63269
- const raw = fs19.readFileUtf8(file2);
63269
+ const raw = fs20.readFileUtf8(file2);
63270
63270
  if (raw === void 0) {
63271
63271
  return { file: empty };
63272
63272
  }
@@ -63279,17 +63279,17 @@ function readPicksFile(fs19, file2) {
63279
63279
  const result = PicksFileSchema.safeParse(parsed);
63280
63280
  return result.success ? { file: result.data } : { file: empty, problem: `${file2} is not a picks file this agent-shim can read` };
63281
63281
  }
63282
- function readStickyPick(fs19, picksFile, directory) {
63283
- const read = readPicksFile(fs19, picksFile);
63282
+ function readStickyPick(fs20, picksFile, directory) {
63283
+ const read = readPicksFile(fs20, picksFile);
63284
63284
  const entry = read.file.picks[directory];
63285
63285
  return { ...entry === void 0 ? {} : { sticky: entry }, ...read.problem === void 0 ? {} : { problem: read.problem } };
63286
63286
  }
63287
- function recordStickyPick(fs19, picksFile, directory, identity, nowMs) {
63288
- const current = readPicksFile(fs19, picksFile).file.picks;
63287
+ function recordStickyPick(fs20, picksFile, directory, identity, nowMs) {
63288
+ const current = readPicksFile(fs20, picksFile).file.picks;
63289
63289
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
63290
63290
  const next = { schemaVersion: SCHEMA_VERSION, picks: { ...Object.fromEntries(kept), [directory]: { identity, at: new Date(nowMs).toISOString() } } };
63291
- fs19.mkdirPrivate(import_node_path26.default.dirname(picksFile));
63292
- fs19.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
63291
+ fs20.mkdirPrivate(import_node_path26.default.dirname(picksFile));
63292
+ fs20.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
63293
63293
  `);
63294
63294
  }
63295
63295
 
@@ -65652,8 +65652,8 @@ var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
65652
65652
  var FRONTDOOR_POLL_MS = 1e3;
65653
65653
  var MS_PER_MINUTE2 = 6e4;
65654
65654
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
65655
- const { fs: fs19, paths } = ports;
65656
- const previous = readFrontDoorState(fs19, paths.frontdoorStateFile);
65655
+ const { fs: fs20, paths } = ports;
65656
+ const previous = readFrontDoorState(fs20, paths.frontdoorStateFile);
65657
65657
  let lastPort = previous?.lastPort;
65658
65658
  let lastConnectPort = previous?.lastConnectPort;
65659
65659
  let lastDirectPort = previous?.lastDirectPort;
@@ -65664,29 +65664,29 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65664
65664
  });
65665
65665
  const fail = (message) => {
65666
65666
  ports.closeRcStreamHub();
65667
- writeFrontDoorState(fs19, paths.frontdoorStateFile, { lastError: message, ...sticky() });
65668
- fs19.removeRecursive(paths.frontdoorLockFile);
65667
+ writeFrontDoorState(fs20, paths.frontdoorStateFile, { lastError: message, ...sticky() });
65668
+ fs20.removeRecursive(paths.frontdoorLockFile);
65669
65669
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
65670
65670
  return 1;
65671
65671
  };
65672
- writeFrontDoorState(fs19, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
65672
+ writeFrontDoorState(fs20, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
65673
65673
  const previousSticky = lastPort;
65674
- let http7;
65674
+ let http8;
65675
65675
  try {
65676
- http7 = await ports.startProviderListener(lastPort);
65676
+ http8 = await ports.startProviderListener(lastPort);
65677
65677
  } catch (error62) {
65678
65678
  return fail(`could not start the provider listener: ${error62 instanceof Error ? error62.message : String(error62)}`);
65679
65679
  }
65680
- if (previousSticky !== void 0 && http7.port !== previousSticky) {
65681
- ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http7.port)} (sessions launched against the old port are stale until they relaunch)`);
65680
+ if (previousSticky !== void 0 && http8.port !== previousSticky) {
65681
+ ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http8.port)} (sessions launched against the old port are stale until they relaunch)`);
65682
65682
  }
65683
- lastPort = http7.port;
65683
+ lastPort = http8.port;
65684
65684
  const previousStickyConnect = lastConnectPort;
65685
65685
  let connect3;
65686
65686
  try {
65687
65687
  connect3 = await ports.startConnectListener(lastConnectPort);
65688
65688
  } catch (error62) {
65689
- await http7.close();
65689
+ await http8.close();
65690
65690
  return fail(`could not start the CONNECT surface: ${error62 instanceof Error ? error62.message : String(error62)}`);
65691
65691
  }
65692
65692
  if (previousStickyConnect !== void 0 && connect3.port !== previousStickyConnect) {
@@ -65699,16 +65699,16 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65699
65699
  direct = await ports.startDirectListener(lastDirectPort);
65700
65700
  } catch (error62) {
65701
65701
  await connect3.close();
65702
- await http7.close();
65702
+ await http8.close();
65703
65703
  return fail(`could not start the direct listener: ${error62 instanceof Error ? error62.message : String(error62)}`);
65704
65704
  }
65705
65705
  if (previousStickyDirect !== void 0 && direct.port !== previousStickyDirect) {
65706
65706
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom must be restarted to admit the new address)`);
65707
65707
  }
65708
65708
  lastDirectPort = direct.port;
65709
- writeFrontDoorState(fs19, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http7.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
65710
- fs19.removeRecursive(paths.frontdoorLockFile);
65711
- ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http7.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
65709
+ writeFrontDoorState(fs20, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http8.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
65710
+ fs20.removeRecursive(paths.frontdoorLockFile);
65711
+ ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http8.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
65712
65712
  let idleSince;
65713
65713
  let ticks = 0;
65714
65714
  for (; ; ) {
@@ -65716,8 +65716,8 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65716
65716
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
65717
65717
  }
65718
65718
  ticks += 1;
65719
- const listed = listFrontDoorSessions(fs19, paths.frontdoorSessionsDir);
65720
- const pruned = pruneDeadFrontDoorSessions(fs19, paths.frontdoorSessionsDir, ports.isRunning);
65719
+ const listed = listFrontDoorSessions(fs20, paths.frontdoorSessionsDir);
65720
+ const pruned = pruneDeadFrontDoorSessions(fs20, paths.frontdoorSessionsDir, ports.isRunning);
65721
65721
  ports.observeLaunchRegistry(listed, pruned);
65722
65722
  const prunedPids = new Set(pruned);
65723
65723
  if (listed.filter((session) => !prunedPids.has(session.pid)).length === 0) {
@@ -65726,9 +65726,9 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65726
65726
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
65727
65727
  await direct.close();
65728
65728
  await connect3.close();
65729
- await http7.close();
65729
+ await http8.close();
65730
65730
  ports.closeRcStreamHub();
65731
- writeFrontDoorState(fs19, paths.frontdoorStateFile, sticky());
65731
+ writeFrontDoorState(fs20, paths.frontdoorStateFile, sticky());
65732
65732
  return 0;
65733
65733
  }
65734
65734
  } else {
@@ -65781,8 +65781,8 @@ function parseConnectTarget(authority) {
65781
65781
  }
65782
65782
  return { host, port };
65783
65783
  }
65784
- function servedByPipeline(path44) {
65785
- return path44?.startsWith(ROUTED_PATH_PREFIX) === true;
65784
+ function servedByPipeline(path46) {
65785
+ return path46?.startsWith(ROUTED_PATH_PREFIX) === true;
65786
65786
  }
65787
65787
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
65788
65788
  "connection",
@@ -66308,11 +66308,11 @@ function createRcSessionTracker(deps) {
66308
66308
  };
66309
66309
  const observeExchange = (request7) => {
66310
66310
  const method = (request7.method ?? "").toUpperCase();
66311
- const path44 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
66312
- if (!path44.startsWith(RC_SESSIONS_PATH_PREFIX)) {
66311
+ const path46 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
66312
+ if (!path46.startsWith(RC_SESSIONS_PATH_PREFIX)) {
66313
66313
  return void 0;
66314
66314
  }
66315
- const tail = path44.slice(RC_SESSIONS_PATH_PREFIX.length);
66315
+ const tail = path46.slice(RC_SESSIONS_PATH_PREFIX.length);
66316
66316
  const facts = {
66317
66317
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
66318
66318
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -67052,9 +67052,9 @@ function sequenceNumsOfBody(body) {
67052
67052
  }
67053
67053
  function frontDoorRcControl(transport, token) {
67054
67054
  const headers = { authorization: `Bearer ${token}` };
67055
- const listAnswerOf = async (path44, what) => {
67055
+ const listAnswerOf = async (path46, what) => {
67056
67056
  try {
67057
- return await transport.request({ method: "GET", path: path44, headers });
67057
+ return await transport.request({ method: "GET", path: path46, headers });
67058
67058
  } catch (error62) {
67059
67059
  throw new Error(`${what}: could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}`, { cause: error62 });
67060
67060
  }
@@ -67126,10 +67126,10 @@ function frontDoorRcControl(transport, token) {
67126
67126
  }
67127
67127
  return pending;
67128
67128
  };
67129
- const writeOf = async (path44, body, describeFailure) => {
67129
+ const writeOf = async (path46, body, describeFailure) => {
67130
67130
  let answer;
67131
67131
  try {
67132
- answer = await transport.request({ method: "POST", path: path44, headers: { ...headers, "content-type": "application/json" }, body });
67132
+ answer = await transport.request({ method: "POST", path: path46, headers: { ...headers, "content-type": "application/json" }, body });
67133
67133
  } catch (error62) {
67134
67134
  return { ok: false, message: `could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}` };
67135
67135
  }
@@ -67503,12 +67503,12 @@ function lateRcStreamDial(resolve) {
67503
67503
  }
67504
67504
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
67505
67505
  const agent = new ExemptTlsAgent();
67506
- const request7 = async (method, path44, headers, body, signal) => await new Promise((resolve, reject) => {
67506
+ const request7 = async (method, path46, headers, body, signal) => await new Promise((resolve, reject) => {
67507
67507
  const options = {
67508
67508
  host: target.host,
67509
67509
  port: target.port,
67510
67510
  method,
67511
- path: path44,
67511
+ path: path46,
67512
67512
  // The Host header names the host whose API this is, not the address dialled: a redirected test dials a loopback stand-in while still speaking to the API host by name, exactly as the forwarded paths present their SNI.
67513
67513
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
67514
67514
  agent,
@@ -67545,9 +67545,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
67545
67545
  return { status, body: await readAll(response) };
67546
67546
  },
67547
67547
  openStream: async (sessionId, headers, resume, signal) => {
67548
- const path44 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
67548
+ const path46 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
67549
67549
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
67550
- const { status, response } = await request7("GET", path44, streamHeaders, void 0, signal);
67550
+ const { status, response } = await request7("GET", path46, streamHeaders, void 0, signal);
67551
67551
  if (!isSuccessful2(status)) {
67552
67552
  await readAll(response);
67553
67553
  return { status, chunks: NO_CHUNKS };
@@ -69233,9 +69233,9 @@ function resolveFriendlyClientOptions(options) {
69233
69233
  };
69234
69234
  }
69235
69235
  function createORPCClient(link, options = {}) {
69236
- const path44 = options.path ?? [];
69236
+ const path46 = options.path ?? [];
69237
69237
  const procedureClient = async (...[input2, options2 = {}]) => {
69238
- return await link.call(path44, input2, resolveFriendlyClientOptions(options2));
69238
+ return await link.call(path46, input2, resolveFriendlyClientOptions(options2));
69239
69239
  };
69240
69240
  const recursive2 = new Proxy(procedureClient, {
69241
69241
  get(target, key) {
@@ -69244,7 +69244,7 @@ function createORPCClient(link, options = {}) {
69244
69244
  }
69245
69245
  return createORPCClient(link, {
69246
69246
  ...options,
69247
- path: [...path44, key]
69247
+ path: [...path46, key]
69248
69248
  });
69249
69249
  }
69250
69250
  });
@@ -69826,19 +69826,19 @@ var StandardLink = class {
69826
69826
  }
69827
69827
  interceptors;
69828
69828
  clientInterceptors;
69829
- call(path44, input2, options) {
69829
+ call(path46, input2, options) {
69830
69830
  return runWithSpan(
69831
- { name: `${ORPC_NAME}.${path44.join("/")}`, signal: options.signal },
69831
+ { name: `${ORPC_NAME}.${path46.join("/")}`, signal: options.signal },
69832
69832
  (span) => {
69833
69833
  span?.setAttribute("rpc.system", ORPC_NAME);
69834
- span?.setAttribute("rpc.method", path44.join("."));
69834
+ span?.setAttribute("rpc.method", path46.join("."));
69835
69835
  if (isAsyncIteratorObject(input2)) {
69836
69836
  input2 = asyncIteratorWithSpan(
69837
69837
  { name: "consume_event_iterator_input", signal: options.signal },
69838
69838
  input2
69839
69839
  );
69840
69840
  }
69841
- return intercept(this.interceptors, { ...options, path: path44, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
69841
+ return intercept(this.interceptors, { ...options, path: path46, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
69842
69842
  const otelConfig = getGlobalOtelConfig();
69843
69843
  let otelContext;
69844
69844
  const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
@@ -70073,8 +70073,8 @@ var StandardRPCJsonSerializer = class {
70073
70073
  return ref.data;
70074
70074
  }
70075
70075
  };
70076
- function toHttpPath(path44) {
70077
- return `/${path44.map(encodeURIComponent).join("/")}`;
70076
+ function toHttpPath(path46) {
70077
+ return `/${path46.map(encodeURIComponent).join("/")}`;
70078
70078
  }
70079
70079
  function toStandardHeaders2(headers) {
70080
70080
  if (typeof headers.forEach === "function") {
@@ -70099,18 +70099,18 @@ var StandardRPCLinkCodec = class {
70099
70099
  fallbackMethod;
70100
70100
  expectedMethod;
70101
70101
  headers;
70102
- async encode(path44, input2, options) {
70103
- let headers = toStandardHeaders2(await value(this.headers, options, path44, input2));
70102
+ async encode(path46, input2, options) {
70103
+ let headers = toStandardHeaders2(await value(this.headers, options, path46, input2));
70104
70104
  if (options.lastEventId !== void 0) {
70105
70105
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
70106
70106
  }
70107
- const expectedMethod = await value(this.expectedMethod, options, path44, input2);
70108
- const baseUrl = await value(this.baseUrl, options, path44, input2);
70107
+ const expectedMethod = await value(this.expectedMethod, options, path46, input2);
70108
+ const baseUrl = await value(this.baseUrl, options, path46, input2);
70109
70109
  const url2 = new URL(baseUrl);
70110
- url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path44)}`;
70110
+ url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path46)}`;
70111
70111
  const serialized = this.serializer.serialize(input2);
70112
70112
  if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
70113
- const maxUrlLength = await value(this.maxUrlLength, options, path44, input2);
70113
+ const maxUrlLength = await value(this.maxUrlLength, options, path46, input2);
70114
70114
  const getUrl = new URL(url2);
70115
70115
  getUrl.searchParams.append("data", stringifyJSON(serialized));
70116
70116
  if (getUrl.toString().length <= maxUrlLength) {
@@ -70578,7 +70578,7 @@ function middlewareOutputFn(output2) {
70578
70578
  function createProcedureClient(lazyableProcedure, ...rest) {
70579
70579
  const options = resolveMaybeOptionalOptions(rest);
70580
70580
  return async (...[input2, callerOptions]) => {
70581
- const path44 = toArray(options.path);
70581
+ const path46 = toArray(options.path);
70582
70582
  const { default: procedure } = await unlazy(lazyableProcedure);
70583
70583
  const clientContext = callerOptions?.context ?? {};
70584
70584
  const context = await value(options.context ?? {}, clientContext);
@@ -70593,7 +70593,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
70593
70593
  const output2 = await runWithSpan(
70594
70594
  { name: "call_procedure", signal: callerOptions?.signal },
70595
70595
  (span) => {
70596
- span?.setAttribute("procedure.path", [...path44]);
70596
+ span?.setAttribute("procedure.path", [...path46]);
70597
70597
  return intercept(
70598
70598
  toArray(options.interceptors),
70599
70599
  {
@@ -70601,7 +70601,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
70601
70601
  input: input2,
70602
70602
  // input only optional when it undefinable so we can safely cast it
70603
70603
  errors,
70604
- path: path44,
70604
+ path: path46,
70605
70605
  procedure,
70606
70606
  signal: callerOptions?.signal,
70607
70607
  lastEventId: callerOptions?.lastEventId
@@ -70723,10 +70723,10 @@ var HIDDEN_ROUTER_CONTRACT_SYMBOL = /* @__PURE__ */ Symbol("ORPC_HIDDEN_ROUTER_C
70723
70723
  function getHiddenRouterContract(router) {
70724
70724
  return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
70725
70725
  }
70726
- function getRouter(router, path44) {
70726
+ function getRouter(router, path46) {
70727
70727
  let current = router;
70728
- for (let i2 = 0; i2 < path44.length; i2++) {
70729
- const segment = path44[i2];
70728
+ for (let i2 = 0; i2 < path46.length; i2++) {
70729
+ const segment = path46[i2];
70730
70730
  if (!current) {
70731
70731
  return void 0;
70732
70732
  }
@@ -70741,7 +70741,7 @@ function getRouter(router, path44) {
70741
70741
  continue;
70742
70742
  }
70743
70743
  const lazied = current;
70744
- const rest = path44.slice(i2);
70744
+ const rest = path46.slice(i2);
70745
70745
  return lazy2(async () => {
70746
70746
  const unwrapped = await unlazy(lazied);
70747
70747
  const next = getRouter(unwrapped.default, rest);
@@ -71205,11 +71205,11 @@ var LinkFetchClient = class {
71205
71205
  this.toFetchRequestOptions = options;
71206
71206
  this.adapterInterceptors = toArray(options.adapterInterceptors);
71207
71207
  }
71208
- async call(standardRequest, options, path44, input2) {
71208
+ async call(standardRequest, options, path46, input2) {
71209
71209
  const request7 = toFetchRequest(standardRequest, this.toFetchRequestOptions);
71210
71210
  const fetchResponse = await intercept(
71211
71211
  this.adapterInterceptors,
71212
- { ...options, request: request7, path: path44, input: input2, init: { redirect: "manual" } },
71212
+ { ...options, request: request7, path: path46, input: input2, init: { redirect: "manual" } },
71213
71213
  ({ request: request22, path: path210, input: input22, init, ...options2 }) => this.fetch(request22, init, options2, path210, input22)
71214
71214
  );
71215
71215
  const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request7.signal });
@@ -71356,8 +71356,8 @@ function toAbortSignal(stream) {
71356
71356
  function toStandardUrl(req) {
71357
71357
  const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
71358
71358
  const origin = guard(() => new URL(`${protocol}//${req.headers.host ?? "localhost"}`).origin) ?? `${protocol}//localhost`;
71359
- const path44 = req.originalUrl ?? req.url ?? "/";
71360
- return new URL(`${origin}${path44.startsWith("/") ? "" : "/"}${path44}`);
71359
+ const path46 = req.originalUrl ?? req.url ?? "/";
71360
+ return new URL(`${origin}${path46.startsWith("/") ? "" : "/"}${path46}`);
71361
71361
  }
71362
71362
  function toStandardLazyRequest(req, res) {
71363
71363
  const signal = toAbortSignal(res);
@@ -71556,8 +71556,8 @@ var StandardRPCMatcher = class {
71556
71556
  constructor(options = {}) {
71557
71557
  this.filter = options.filter ?? true;
71558
71558
  }
71559
- init(router, path44 = []) {
71560
- const laziedOptions = traverseContractProcedures({ router, path: path44 }, (traverseOptions) => {
71559
+ init(router, path46 = []) {
71560
+ const laziedOptions = traverseContractProcedures({ router, path: path46 }, (traverseOptions) => {
71561
71561
  if (!value(this.filter, traverseOptions)) {
71562
71562
  return;
71563
71563
  }
@@ -73274,8 +73274,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
73274
73274
  request7.body.resume();
73275
73275
  return;
73276
73276
  }
73277
- const path44 = new URL(request7.url, "http://127.0.0.1").pathname;
73278
- const translated = { method: request7.method, path: path44, body, signal: request7.signal };
73277
+ const path46 = new URL(request7.url, "http://127.0.0.1").pathname;
73278
+ const translated = { method: request7.method, path: path46, body, signal: request7.signal };
73279
73279
  const routed = await route(translated);
73280
73280
  if (request7.signal.aborted) {
73281
73281
  return;
@@ -73309,7 +73309,7 @@ function createPassthroughRoute(name, target) {
73309
73309
  headroomUpstream: target.headroomUpstream,
73310
73310
  serve: async (request7, response) => {
73311
73311
  const incoming = new URL(request7.url, "http://127.0.0.1");
73312
- const path44 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
73312
+ const path46 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
73313
73313
  const headers = forwardableHeaders(request7.headers);
73314
73314
  delete headers.host;
73315
73315
  await new Promise((resolve) => {
@@ -73317,7 +73317,7 @@ function createPassthroughRoute(name, target) {
73317
73317
  host: base.hostname,
73318
73318
  port: base.port === "" ? void 0 : Number(base.port),
73319
73319
  method: request7.method,
73320
- path: `${basePath}${path44}${incoming.search}`,
73320
+ path: `${basePath}${path46}${incoming.search}`,
73321
73321
  headers,
73322
73322
  agent
73323
73323
  };
@@ -73366,7 +73366,7 @@ function createPassthroughRoute(name, target) {
73366
73366
 
73367
73367
  // src/frontdoor/providerRoute.ts
73368
73368
  function createProviderRouteResolver(deps) {
73369
- const isRcSelfHostPath = (path44) => path44 === "/v1/code/sessions" || path44.startsWith("/v1/code/sessions/") || path44 === "/v1/sessions" || path44.startsWith("/v1/sessions/");
73369
+ const isRcSelfHostPath = (path46) => path46 === "/v1/code/sessions" || path46.startsWith("/v1/code/sessions/") || path46 === "/v1/sessions" || path46.startsWith("/v1/sessions/");
73370
73370
  const oauthRoute = createPassthroughRoute("anthropic", { baseUrl: `https://${CONNECT_INTERCEPT_HOST}:${String(HTTPS_PORT)}`, stripPrefix: void 0, headroomUpstream: void 0 });
73371
73371
  const passthroughByTarget = /* @__PURE__ */ new Map();
73372
73372
  const passthroughFor = (name, target) => {
@@ -73380,16 +73380,16 @@ function createProviderRouteResolver(deps) {
73380
73380
  return route;
73381
73381
  };
73382
73382
  const resolve = (request7) => {
73383
- const path44 = new URL(request7.url, "http://127.0.0.1").pathname;
73384
- const scoped = parseProviderPath(path44);
73383
+ const path46 = new URL(request7.url, "http://127.0.0.1").pathname;
73384
+ const scoped = parseProviderPath(path46);
73385
73385
  if (scoped === void 0) {
73386
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path44)) {
73386
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path46)) {
73387
73387
  return { ok: true, route: deps.rcSelfHostRoute };
73388
73388
  }
73389
- if (request7.session.provider !== void 0 && path44.startsWith("/v1/") && !isRcSelfHostPath(path44)) {
73389
+ if (request7.session.provider !== void 0 && path46.startsWith("/v1/") && !isRcSelfHostPath(path46)) {
73390
73390
  return resolve({ ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` });
73391
73391
  }
73392
- return path44.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path44}` };
73392
+ return path46.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path46}` };
73393
73393
  }
73394
73394
  const { provider } = scoped;
73395
73395
  let definition;
@@ -73478,11 +73478,11 @@ function credentialOfJson(parsed) {
73478
73478
  function sequenceNumOfJson(value2) {
73479
73479
  return typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 ? value2 : void 0;
73480
73480
  }
73481
- function createRcCredentialStore(fs19, dir) {
73482
- fs19.mkdirPrivate(dir);
73481
+ function createRcCredentialStore(fs20, dir) {
73482
+ fs20.mkdirPrivate(dir);
73483
73483
  const fileFor = (sessionId) => import_node_path34.default.join(dir, `${sessionId}.json`);
73484
73484
  const readParsed = (sessionId) => {
73485
- const raw = fs19.readFileUtf8(fileFor(sessionId));
73485
+ const raw = fs20.readFileUtf8(fileFor(sessionId));
73486
73486
  if (raw === void 0) {
73487
73487
  return void 0;
73488
73488
  }
@@ -73507,7 +73507,7 @@ function createRcCredentialStore(fs19, dir) {
73507
73507
  }
73508
73508
  const cursor3 = sequenceNumOfJson(readParsed(sessionId)?.highestSequenceNum);
73509
73509
  const record2 = { ...credential, ...cursor3 === void 0 ? {} : { highestSequenceNum: cursor3 } };
73510
- fs19.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
73510
+ fs20.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
73511
73511
  `);
73512
73512
  },
73513
73513
  readCursor: (sessionId) => {
@@ -73522,14 +73522,14 @@ function createRcCredentialStore(fs19, dir) {
73522
73522
  }
73523
73523
  const credential = credentialOfJson(readParsed(sessionId));
73524
73524
  const record2 = credential === void 0 ? { highestSequenceNum } : { ...credential, highestSequenceNum };
73525
- fs19.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
73525
+ fs20.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
73526
73526
  `);
73527
73527
  },
73528
73528
  remove: (sessionId) => {
73529
73529
  if (!isSafeSessionId(sessionId)) {
73530
73530
  return;
73531
73531
  }
73532
- fs19.removeRecursive(fileFor(sessionId));
73532
+ fs20.removeRecursive(fileFor(sessionId));
73533
73533
  }
73534
73534
  };
73535
73535
  }
@@ -73994,6 +73994,252 @@ function createRcClientPage(expectedToken) {
73994
73994
  };
73995
73995
  }
73996
73996
 
73997
+ // src/frontdoor/rcWebFetch.ts
73998
+ var dns2 = __toESM(require("node:dns"), 1);
73999
+ var http6 = __toESM(require("node:http"), 1);
74000
+ var https5 = __toESM(require("node:https"), 1);
74001
+ var net3 = __toESM(require("node:net"), 1);
74002
+ var RC_WEB_FETCH_MAX_BYTES = 12582912;
74003
+ var RC_WEB_FETCH_DEADLINE_MS = 4e4;
74004
+ var RC_WEB_FETCH_MAX_REDIRECTS = 20;
74005
+ var RC_WEB_FETCH_ALLOW_PRIVATE_ENV = "AGENT_SHIM_FRONTDOOR_RC_SELF_HOST_WEB_FETCH_ALLOW_PRIVATE";
74006
+ function rcWebFetchAllowsPrivateFromEnv(env) {
74007
+ return env[RC_WEB_FETCH_ALLOW_PRIVATE_ENV] === "1";
74008
+ }
74009
+ var WEB_FETCH_USER_AGENT = "agent-shim-frontdoor";
74010
+ var ERROR_PREFIX = "web_fetch_";
74011
+ var V4_THIS_NETWORK_OCTET = 0;
74012
+ var V4_PRIVATE_A_OCTET = 10;
74013
+ var V4_LOOPBACK_OCTET = 127;
74014
+ var V4_CGNAT_OCTET = 100;
74015
+ var V4_CGNAT_SECOND_FROM = 64;
74016
+ var V4_CGNAT_SECOND_TO = 127;
74017
+ var V4_LINK_LOCAL_OCTET = 169;
74018
+ var V4_LINK_LOCAL_SECOND = 254;
74019
+ var V4_PRIVATE_B_OCTET = 172;
74020
+ var V4_PRIVATE_B_SECOND_FROM = 16;
74021
+ var V4_PRIVATE_B_SECOND_TO = 31;
74022
+ var V4_PRIVATE_C_OCTET = 192;
74023
+ var V4_PRIVATE_C_SECOND = 168;
74024
+ var V4_MULTICAST_FROM_OCTET = 224;
74025
+ var V6_UNIQUE_LOCAL_FROM = 64512;
74026
+ var V6_UNIQUE_LOCAL_TO = 65023;
74027
+ var V6_LINK_LOCAL_FROM = 65152;
74028
+ var V6_LINK_LOCAL_TO = 65215;
74029
+ var V6_MULTICAST_FROM = 65280;
74030
+ var IP_VERSION_4 = 4;
74031
+ var IP_VERSION_6 = 6;
74032
+ var HTTP_MOVED_PERMANENTLY = 301;
74033
+ var HTTP_FOUND = 302;
74034
+ var HTTP_SEE_OTHER = 303;
74035
+ var HTTP_TEMPORARY_REDIRECT = 307;
74036
+ var HTTP_PERMANENT_REDIRECT = 308;
74037
+ var SUCCESS_STATUS_MAX_EXCLUSIVE3 = 300;
74038
+ function refused(errorType, errorMessage2) {
74039
+ return { kind: "refused", errorType: `${ERROR_PREFIX}${errorType}`, errorMessage: errorMessage2 };
74040
+ }
74041
+ function isPrivateAddress(address) {
74042
+ const version2 = net3.isIP(address);
74043
+ if (version2 === IP_VERSION_4) {
74044
+ const octets = address.split(".").map((part) => Number(part));
74045
+ const first = octets[0] ?? -1;
74046
+ const second = octets[1] ?? -1;
74047
+ if (first === V4_THIS_NETWORK_OCTET || first === V4_PRIVATE_A_OCTET || first === V4_LOOPBACK_OCTET) {
74048
+ return true;
74049
+ }
74050
+ if (first === V4_CGNAT_OCTET && second >= V4_CGNAT_SECOND_FROM && second <= V4_CGNAT_SECOND_TO) {
74051
+ return true;
74052
+ }
74053
+ if (first === V4_LINK_LOCAL_OCTET && second === V4_LINK_LOCAL_SECOND) {
74054
+ return true;
74055
+ }
74056
+ if (first === V4_PRIVATE_B_OCTET && second >= V4_PRIVATE_B_SECOND_FROM && second <= V4_PRIVATE_B_SECOND_TO) {
74057
+ return true;
74058
+ }
74059
+ if (first === V4_PRIVATE_C_OCTET && second === V4_PRIVATE_C_SECOND) {
74060
+ return true;
74061
+ }
74062
+ return first >= V4_MULTICAST_FROM_OCTET;
74063
+ }
74064
+ if (version2 === IP_VERSION_6) {
74065
+ const lower = address.toLowerCase();
74066
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(lower);
74067
+ if (mapped !== null) {
74068
+ return isPrivateAddress(mapped[1] ?? "");
74069
+ }
74070
+ if (lower === "::" || lower === "::1") {
74071
+ return true;
74072
+ }
74073
+ const firstGroup = Number.parseInt(/^([0-9a-f]+):/.exec(lower)?.[1] ?? "0", 16);
74074
+ if (Number.isNaN(firstGroup)) {
74075
+ return true;
74076
+ }
74077
+ if (firstGroup >= V6_UNIQUE_LOCAL_FROM && firstGroup <= V6_UNIQUE_LOCAL_TO) {
74078
+ return true;
74079
+ }
74080
+ if (firstGroup >= V6_LINK_LOCAL_FROM && firstGroup <= V6_LINK_LOCAL_TO) {
74081
+ return true;
74082
+ }
74083
+ return firstGroup >= V6_MULTICAST_FROM;
74084
+ }
74085
+ return true;
74086
+ }
74087
+ function isSuccessful3(status) {
74088
+ return status >= HTTP_STATUS.ok && status < SUCCESS_STATUS_MAX_EXCLUSIVE3;
74089
+ }
74090
+ function isRedirect(status) {
74091
+ return status === HTTP_MOVED_PERMANENTLY || status === HTTP_FOUND || status === HTTP_SEE_OTHER || status === HTTP_TEMPORARY_REDIRECT || status === HTTP_PERMANENT_REDIRECT;
74092
+ }
74093
+ function readableContentType(contentType) {
74094
+ if (contentType === void 0 || contentType.trim() === "") {
74095
+ return true;
74096
+ }
74097
+ const normalised = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
74098
+ const slash = normalised.indexOf("/");
74099
+ const main2 = slash === -1 ? normalised : normalised.slice(0, slash);
74100
+ const sub = slash === -1 ? "" : normalised.slice(slash + 1);
74101
+ if (main2 === "text") {
74102
+ return true;
74103
+ }
74104
+ return /json|xml|javascript|ecmascript|yaml|csv/.test(sub);
74105
+ }
74106
+ async function readCapped(chunks) {
74107
+ const collected = [];
74108
+ let total = 0;
74109
+ for await (const chunk of chunks) {
74110
+ total += chunk.byteLength;
74111
+ if (total > RC_WEB_FETCH_MAX_BYTES) {
74112
+ return { tooLarge: true, text: "" };
74113
+ }
74114
+ collected.push(Buffer.from(chunk));
74115
+ }
74116
+ return { tooLarge: false, text: Buffer.concat(collected).toString("utf8") };
74117
+ }
74118
+ async function checkTarget(url2, deps) {
74119
+ if (url2.protocol !== "http:" && url2.protocol !== "https:") {
74120
+ return refused("scheme", `the web-fetch proxy dials http and https only, not ${url2.protocol}`);
74121
+ }
74122
+ if (deps.allowPrivate) {
74123
+ return void 0;
74124
+ }
74125
+ const hostname3 = url2.hostname.replace(/^\[|\]$/g, "");
74126
+ let addresses;
74127
+ try {
74128
+ addresses = net3.isIP(hostname3) === 0 ? await deps.lookup(hostname3) : [hostname3];
74129
+ } catch {
74130
+ return refused("resolve", `${hostname3} did not resolve`);
74131
+ }
74132
+ for (const address of addresses) {
74133
+ if (isPrivateAddress(address)) {
74134
+ return refused("private_address", `${hostname3} resolves to ${address}, a private address this web-fetch proxy refuses; set ${RC_WEB_FETCH_ALLOW_PRIVATE_ENV}=1 on the door if serving internal targets is intended`);
74135
+ }
74136
+ }
74137
+ return void 0;
74138
+ }
74139
+ async function fetchThroughWebProxy(url2, deps) {
74140
+ let current;
74141
+ try {
74142
+ current = new URL(url2);
74143
+ } catch {
74144
+ return refused("malformed_url", `${url2} is not a URL this proxy can dial`);
74145
+ }
74146
+ const controller = new AbortController();
74147
+ const timer = setTimeout(() => {
74148
+ controller.abort();
74149
+ }, deps.deadlineMs);
74150
+ timer.unref();
74151
+ try {
74152
+ let redirects = 0;
74153
+ for (; ; ) {
74154
+ const refusal = await checkTarget(current, deps);
74155
+ if (refusal !== void 0) {
74156
+ return refusal;
74157
+ }
74158
+ let hop;
74159
+ try {
74160
+ hop = await deps.dial(current, controller.signal);
74161
+ } catch (error62) {
74162
+ if (controller.signal.aborted) {
74163
+ return refused("deadline", `the fetch of ${url2} did not settle within its deadline`);
74164
+ }
74165
+ return refused("transport", `the dial of ${current.toString()} failed: ${error62 instanceof Error ? error62.message : "unknown error"}`);
74166
+ }
74167
+ if (isRedirect(hop.status) && hop.location !== void 0) {
74168
+ if (redirects >= RC_WEB_FETCH_MAX_REDIRECTS) {
74169
+ controller.abort();
74170
+ return refused("too_many_redirects", `${url2} followed more than ${String(RC_WEB_FETCH_MAX_REDIRECTS)} redirects without settling`);
74171
+ }
74172
+ let next;
74173
+ try {
74174
+ next = new URL(hop.location, current);
74175
+ } catch {
74176
+ controller.abort();
74177
+ return refused("malformed_url", `a redirect of ${current.toString()} named ${hop.location}, which is not a URL this proxy can dial`);
74178
+ }
74179
+ const drained = await readCapped(hop.chunks);
74180
+ if (drained.tooLarge) {
74181
+ controller.abort();
74182
+ return refused("too_large", `the body of a redirect from ${url2} exceeds the ${String(RC_WEB_FETCH_MAX_BYTES)} byte cap the CLI's proxy client reads`);
74183
+ }
74184
+ redirects += 1;
74185
+ current = next;
74186
+ continue;
74187
+ }
74188
+ if (!isSuccessful3(hop.status)) {
74189
+ controller.abort();
74190
+ return refused("status", `the target answered HTTP ${String(hop.status)} for ${current.toString()}`);
74191
+ }
74192
+ const contentType = hop.contentType ?? "";
74193
+ if (!readableContentType(contentType)) {
74194
+ controller.abort();
74195
+ return refused("content_type", `the target at ${current.toString()} served a ${contentType} answer, which the proxy's text field cannot carry`);
74196
+ }
74197
+ const read = await readCapped(hop.chunks);
74198
+ if (read.tooLarge) {
74199
+ controller.abort();
74200
+ return refused("too_large", `the body of ${current.toString()} exceeds the ${String(RC_WEB_FETCH_MAX_BYTES)} byte cap the CLI's proxy client reads`);
74201
+ }
74202
+ return { kind: "fetched", url: url2, destinationUrl: current.toString(), contentType: hop.contentType, text: read.text };
74203
+ }
74204
+ } finally {
74205
+ clearTimeout(timer);
74206
+ }
74207
+ }
74208
+ function realRcWebFetch(options) {
74209
+ const plainAgent = new ExemptHttpAgent();
74210
+ const tlsAgent = new ExemptTlsAgent();
74211
+ const deps = {
74212
+ dial: async (url2, signal) => await new Promise((resolve, reject) => {
74213
+ const request7 = (url2.protocol === "https:" ? https5 : http6).request(
74214
+ {
74215
+ hostname: url2.hostname,
74216
+ port: url2.port === "" ? void 0 : Number(url2.port),
74217
+ method: "GET",
74218
+ path: `${url2.pathname}${url2.search}`,
74219
+ headers: { accept: "*/*", "accept-encoding": "identity", "user-agent": WEB_FETCH_USER_AGENT },
74220
+ agent: url2.protocol === "https:" ? tlsAgent : plainAgent,
74221
+ signal
74222
+ },
74223
+ (response) => {
74224
+ const location = response.headers.location;
74225
+ resolve({
74226
+ status: response.statusCode ?? 0,
74227
+ location: typeof location === "string" ? location : void 0,
74228
+ contentType: typeof response.headers["content-type"] === "string" ? response.headers["content-type"] : void 0,
74229
+ chunks: response
74230
+ });
74231
+ }
74232
+ );
74233
+ request7.once("error", reject);
74234
+ request7.end();
74235
+ }),
74236
+ lookup: async (hostname3) => (await dns2.promises.lookup(hostname3, { all: true })).map((entry) => entry.address),
74237
+ allowPrivate: options.allowPrivate,
74238
+ deadlineMs: RC_WEB_FETCH_DEADLINE_MS
74239
+ };
74240
+ return async (url2) => await fetchThroughWebProxy(url2, deps);
74241
+ }
74242
+
73997
74243
  // src/frontdoor/rcSelfHost.ts
73998
74244
  var RC_SELF_HOST_ENV = "AGENT_SHIM_FRONTDOOR_RC_SELF_HOST";
73999
74245
  function rcSelfHostFromEnv(env) {
@@ -74023,6 +74269,9 @@ var CONFLICT_REASON_EPOCH_STALE = "epoch_stale";
74023
74269
  function isRecord5(value2) {
74024
74270
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
74025
74271
  }
74272
+ function isWebSearchRefusal(value2) {
74273
+ return !Array.isArray(value2);
74274
+ }
74026
74275
  function nonEmptyString2(record2, field) {
74027
74276
  const value2 = record2 === void 0 ? void 0 : record2[field];
74028
74277
  return typeof value2 === "string" && value2 !== "" ? value2 : void 0;
@@ -74037,6 +74286,20 @@ function numberOf(record2, field) {
74037
74286
  }
74038
74287
  return void 0;
74039
74288
  }
74289
+ function stringArray(record2, field) {
74290
+ const value2 = record2 === void 0 ? void 0 : record2[field];
74291
+ if (!Array.isArray(value2)) {
74292
+ return void 0;
74293
+ }
74294
+ const members2 = [];
74295
+ for (const member of value2) {
74296
+ if (typeof member !== "string") {
74297
+ return void 0;
74298
+ }
74299
+ members2.push(member);
74300
+ }
74301
+ return members2;
74302
+ }
74040
74303
  function singleHeader2(headers, name) {
74041
74304
  const value2 = headers[name];
74042
74305
  return typeof value2 === "string" ? value2 : void 0;
@@ -74048,6 +74311,17 @@ function bearerOf(headers) {
74048
74311
  }
74049
74312
  return presented.slice(0, "bearer ".length).toLowerCase() === "bearer " ? presented.slice("bearer ".length) : void 0;
74050
74313
  }
74314
+ function presentationRefusal(headers) {
74315
+ const presented = singleHeader2(headers, "authorization");
74316
+ if (presented === void 0) {
74317
+ return "absent";
74318
+ }
74319
+ if (presented.slice(0, "bearer ".length).toLowerCase() !== "bearer ") {
74320
+ return "not-a-bearer";
74321
+ }
74322
+ const bearer = presented.slice("bearer ".length);
74323
+ return bearer.slice(0, "bearer ".length).toLowerCase() === "bearer " ? "doubled-scheme-word" : "unrecognised";
74324
+ }
74051
74325
  async function readBody3(request7, capBytes) {
74052
74326
  return await new Promise((resolve, reject) => {
74053
74327
  const chunks = [];
@@ -74136,6 +74410,9 @@ function createRcSelfHostSurface(deps) {
74136
74410
  }
74137
74411
  return false;
74138
74412
  };
74413
+ const credentialRefusal = (headers) => presentsCredential(headers) ? void 0 : presentationRefusal(headers);
74414
+ const workerRefusal = (headers, session) => presentsWorkerJwt(headers, session) ? void 0 : presentationRefusal(headers);
74415
+ const workerOrCredentialRefusal = (headers, session) => presentsWorkerJwt(headers, session) || presentsCredential(headers) ? void 0 : presentationRefusal(headers);
74139
74416
  const frameOf = (event) => {
74140
74417
  const envelope = {
74141
74418
  event_id: event.eventId,
@@ -74224,8 +74501,14 @@ data: ${JSON.stringify(envelope)}
74224
74501
  const epochStale = async (response) => {
74225
74502
  await answerJson2(response, HTTP_CONFLICT, { type: "error", error: { type: "api_error", message: "worker_epoch does not match the session's live epoch" } }, { [CONFLICT_REASON_HEADER2]: CONFLICT_REASON_EPOCH_STALE });
74226
74503
  };
74227
- const unauthorized = async (response) => {
74228
- await answerJson2(response, HTTP_STATUS.unauthorized, { type: "error", error: { type: "authentication_error", message: "the self-hosted Remote Control surface did not recognise the presented credential" } });
74504
+ const refusalMessages = {
74505
+ absent: "the self-hosted Remote Control surface authenticates by the Authorization header, and this call carried none",
74506
+ "not-a-bearer": "the self-hosted Remote Control surface reads a Bearer authorization, and this call's Authorization header did not carry the Bearer scheme word",
74507
+ "doubled-scheme-word": "the self-hosted Remote Control surface reads one Bearer scheme word, and this call's Authorization header carried it twice: a persisted session record holds the whole header value with the scheme word included, so prefixing Bearer onto it presents a different credential",
74508
+ unrecognised: "the self-hosted Remote Control surface did not recognise the presented credential"
74509
+ };
74510
+ const unauthorized = async (response, refusal) => {
74511
+ await answerJson2(response, HTTP_STATUS.unauthorized, { type: "error", error: { type: "authentication_error", message: refusalMessages[refusal] } });
74229
74512
  };
74230
74513
  const serveSessionPath = async (session, tail, request7, response) => {
74231
74514
  const method = request7.method.toUpperCase();
@@ -74243,8 +74526,9 @@ data: ${JSON.stringify(envelope)}
74243
74526
  return;
74244
74527
  }
74245
74528
  if (tail === "bridge" && method === "POST") {
74246
- if (!presentsCredential(request7.headers)) {
74247
- await unauthorized(response);
74529
+ const refusal = credentialRefusal(request7.headers);
74530
+ if (refusal !== void 0) {
74531
+ await unauthorized(response, refusal);
74248
74532
  return;
74249
74533
  }
74250
74534
  const workerJwt = mintWorkerJwt(deps.randomToken, deps.now());
@@ -74254,8 +74538,9 @@ data: ${JSON.stringify(envelope)}
74254
74538
  return;
74255
74539
  }
74256
74540
  if (tail === "archive" && method === "POST") {
74257
- if (!presentsCredential(request7.headers)) {
74258
- await unauthorized(response);
74541
+ const refusal = credentialRefusal(request7.headers);
74542
+ if (refusal !== void 0) {
74543
+ await unauthorized(response, refusal);
74259
74544
  return;
74260
74545
  }
74261
74546
  for (const sink of [...session.workerStreams, ...session.clientStreams]) {
@@ -74267,11 +74552,13 @@ data: ${JSON.stringify(envelope)}
74267
74552
  return;
74268
74553
  }
74269
74554
  if (tail === "worker" || tail.startsWith("worker/")) {
74270
- if (!presentsWorkerJwt(request7.headers, session)) {
74271
- await unauthorized(response);
74555
+ const workerTail = tail === "worker" ? "" : tail.slice("worker/".length);
74556
+ const webProxy = workerTail === "web-fetch" || workerTail === "web-search";
74557
+ const refusal = webProxy ? workerOrCredentialRefusal(request7.headers, session) : workerRefusal(request7.headers, session);
74558
+ if (refusal !== void 0) {
74559
+ await unauthorized(response, refusal);
74272
74560
  return;
74273
74561
  }
74274
- const workerTail = tail === "worker" ? "" : tail.slice("worker/".length);
74275
74562
  if (workerTail === "" && method === "GET") {
74276
74563
  await answerJson2(response, HTTP_STATUS.ok, { worker: { external_metadata: session.externalMetadata ?? null } });
74277
74564
  return;
@@ -74370,11 +74657,64 @@ data: ${JSON.stringify(envelope)}
74370
74657
  await answerJson2(response, HTTP_STATUS.ok, {});
74371
74658
  return;
74372
74659
  }
74660
+ if (workerTail === "web-fetch" && method === "POST") {
74661
+ const body = parseJsonObject2(await readBody3(request7.body, CONTROL_BODY_CAP_BYTES));
74662
+ const target = nonEmptyString2(body, "url");
74663
+ if (target === void 0) {
74664
+ await answerJson2(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "a worker web-fetch carries one url" } });
74665
+ return;
74666
+ }
74667
+ const outcome = await deps.webFetch(target);
74668
+ if (outcome.kind === "fetched") {
74669
+ const answer = { url: target, destination_url: outcome.destinationUrl, text: outcome.text, ...outcome.contentType === void 0 ? {} : { content_type: outcome.contentType } };
74670
+ if (Buffer.byteLength(JSON.stringify(answer), "utf8") > RC_WEB_FETCH_MAX_BYTES) {
74671
+ deps.log?.(`rc selfhost ${session.id}: worker web-fetch of ${target} escaped past the reader cap when framed`);
74672
+ await answerJson2(response, HTTP_STATUS.ok, { error: { error_type: "web_fetch_too_large", error_message: `the answer for ${target} exceeds the ${String(RC_WEB_FETCH_MAX_BYTES)} byte cap the CLI's proxy client reads` } });
74673
+ return;
74674
+ }
74675
+ deps.log?.(`rc selfhost ${session.id}: worker web-fetch served ${target} as ${outcome.destinationUrl}`);
74676
+ await answerJson2(response, HTTP_STATUS.ok, answer);
74677
+ return;
74678
+ }
74679
+ deps.log?.(`rc selfhost ${session.id}: worker web-fetch of ${target} refused: ${outcome.errorType}`);
74680
+ await answerJson2(response, HTTP_STATUS.ok, { error: { error_type: outcome.errorType, error_message: outcome.errorMessage } });
74681
+ return;
74682
+ }
74683
+ if (workerTail === "web-search" && method === "POST") {
74684
+ const body = parseJsonObject2(await readBody3(request7.body, CONTROL_BODY_CAP_BYTES));
74685
+ const query = nonEmptyString2(body, "query");
74686
+ if (query === void 0) {
74687
+ await answerJson2(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "a worker web-search carries one query" } });
74688
+ return;
74689
+ }
74690
+ const allowedDomains = stringArray(body, "allowed_domains");
74691
+ const blockedDomains = stringArray(body, "blocked_domains");
74692
+ if (body?.allowed_domains !== void 0 && allowedDomains === void 0 || body?.blocked_domains !== void 0 && blockedDomains === void 0) {
74693
+ await answerJson2(response, HTTP_STATUS.badRequest, { type: "error", error: { type: "invalid_request_error", message: "the domain filters of a worker web-search are string arrays" } });
74694
+ return;
74695
+ }
74696
+ const searchProfile = nonEmptyString2(body, "search_profile");
74697
+ const backend = deps.webSearch;
74698
+ if (backend === void 0) {
74699
+ deps.log?.(`rc selfhost ${session.id}: worker web-search of "${query}" refused: no search backend serves this door`);
74700
+ await answerJson2(response, HTTP_STATUS.ok, { results: [], error: { error_type: "web_search_unavailable", error_message: "this front door serves the Remote Control web-search proxy without a search backend, so no query can be served here" } });
74701
+ return;
74702
+ }
74703
+ const answered = await backend({ query, ...allowedDomains === void 0 ? {} : { allowedDomains }, ...blockedDomains === void 0 ? {} : { blockedDomains }, ...searchProfile === void 0 ? {} : { searchProfile } });
74704
+ deps.log?.(`rc selfhost ${session.id}: worker web-search of "${query}" answered by its backend`);
74705
+ if (isWebSearchRefusal(answered)) {
74706
+ await answerJson2(response, HTTP_STATUS.ok, { results: [], error: { error_type: answered.errorType, error_message: answered.errorMessage } });
74707
+ return;
74708
+ }
74709
+ await answerJson2(response, HTTP_STATUS.ok, { results: answered.map((result) => ({ title: result.title ?? "", url: result.url, snippet: result.snippet ?? "" })) });
74710
+ return;
74711
+ }
74373
74712
  await answerJson2(response, HTTP_STATUS.notFound, { type: "error", error: { type: "api_error", message: `the self-hosted Remote Control surface serves no worker path "${workerTail}"` } });
74374
74713
  return;
74375
74714
  }
74376
- if (!presentsCredential(request7.headers)) {
74377
- await unauthorized(response);
74715
+ const clientRefusal = credentialRefusal(request7.headers);
74716
+ if (clientRefusal !== void 0) {
74717
+ await unauthorized(response, clientRefusal);
74378
74718
  return;
74379
74719
  }
74380
74720
  if (tail === "events" && method === "POST") {
@@ -74439,8 +74779,9 @@ data: ${JSON.stringify(envelope)}
74439
74779
  await answerJson2(response, HTTP_STATUS.methodNotAllowed, { type: "error", error: { type: "api_error", message: "the compatibility session list is a GET" } });
74440
74780
  return;
74441
74781
  }
74442
- if (!presentsCredential(request7.headers)) {
74443
- await unauthorized(response);
74782
+ const listRefusal = credentialRefusal(request7.headers);
74783
+ if (listRefusal !== void 0) {
74784
+ await unauthorized(response, listRefusal);
74444
74785
  return;
74445
74786
  }
74446
74787
  await answerJson2(response, HTTP_STATUS.ok, { data: [] });
@@ -74452,8 +74793,9 @@ data: ${JSON.stringify(envelope)}
74452
74793
  }
74453
74794
  if (pathname === RC_SESSIONS_PATH_PREFIX2) {
74454
74795
  if (method === "POST") {
74455
- if (!presentsCredential(request7.headers)) {
74456
- await unauthorized(response);
74796
+ const createRefusal = credentialRefusal(request7.headers);
74797
+ if (createRefusal !== void 0) {
74798
+ await unauthorized(response, createRefusal);
74457
74799
  return;
74458
74800
  }
74459
74801
  const body = parseJsonObject2(await readBody3(request7.body, CONTROL_BODY_CAP_BYTES));
@@ -74478,8 +74820,9 @@ data: ${JSON.stringify(envelope)}
74478
74820
  return;
74479
74821
  }
74480
74822
  if (method === "GET") {
74481
- if (!presentsCredential(request7.headers)) {
74482
- await unauthorized(response);
74823
+ const readRefusal = credentialRefusal(request7.headers);
74824
+ if (readRefusal !== void 0) {
74825
+ await unauthorized(response, readRefusal);
74483
74826
  return;
74484
74827
  }
74485
74828
  await answerJson2(response, HTTP_STATUS.ok, { data: [...sessions.values()].map((session) => ({ id: session.id, title: session.title, created_at: new Date(session.createdAt).toISOString(), updated_at: new Date(session.lastTrafficAt).toISOString(), session_status: "active" })) });
@@ -74600,8 +74943,8 @@ var SELF_HOST_SUBSCRIPTION_TYPE = "max";
74600
74943
  function isRecord6(value2) {
74601
74944
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
74602
74945
  }
74603
- function readJsonObject(fs19, file2) {
74604
- const raw = fs19.readFileUtf8(file2);
74946
+ function readJsonObject(fs20, file2) {
74947
+ const raw = fs20.readFileUtf8(file2);
74605
74948
  if (raw === void 0) {
74606
74949
  return void 0;
74607
74950
  }
@@ -74613,8 +74956,8 @@ function readJsonObject(fs19, file2) {
74613
74956
  }
74614
74957
  return isRecord6(parsed) ? parsed : void 0;
74615
74958
  }
74616
- function readRcSelfHostRecord(fs19, frontdoorDir) {
74617
- const parsed = readJsonObject(fs19, import_node_path35.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
74959
+ function readRcSelfHostRecord(fs20, frontdoorDir) {
74960
+ const parsed = readJsonObject(fs20, import_node_path35.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
74618
74961
  if (parsed === void 0) {
74619
74962
  return void 0;
74620
74963
  }
@@ -74684,9 +75027,9 @@ function mintRcSelfHostCredential(deps) {
74684
75027
  var RC_STREAM_EVENT_NAME2 = "client_event";
74685
75028
  var SSE_BYTE_ORDER_MARK = 65279;
74686
75029
  var RC_STREAM_BACKOFF_MS = 45e3;
74687
- var SUCCESS_STATUS_MAX_EXCLUSIVE3 = 300;
74688
- function isSuccessful3(status) {
74689
- return status >= HTTP_STATUS.ok && status < SUCCESS_STATUS_MAX_EXCLUSIVE3;
75030
+ var SUCCESS_STATUS_MAX_EXCLUSIVE4 = 300;
75031
+ function isSuccessful4(status) {
75032
+ return status >= HTTP_STATUS.ok && status < SUCCESS_STATUS_MAX_EXCLUSIVE4;
74690
75033
  }
74691
75034
  function createSseParser() {
74692
75035
  let buffer = "";
@@ -74853,7 +75196,7 @@ function createRcStreamHub(deps) {
74853
75196
  if (presence.status === HTTP_STATUS.unauthorized) {
74854
75197
  return "unauthorized";
74855
75198
  }
74856
- if (!isSuccessful3(presence.status)) {
75199
+ if (!isSuccessful4(presence.status)) {
74857
75200
  throw new Error(`the presence call answered HTTP ${String(presence.status)}: ${presence.body}`);
74858
75201
  }
74859
75202
  const cursor3 = deps.sequenceNumOf(attachment.sessionId) ?? deps.storedSequenceNumOf?.(attachment.sessionId);
@@ -74862,7 +75205,7 @@ function createRcStreamHub(deps) {
74862
75205
  if (answer.status === HTTP_STATUS.unauthorized) {
74863
75206
  return "unauthorized";
74864
75207
  }
74865
- if (!isSuccessful3(answer.status)) {
75208
+ if (!isSuccessful4(answer.status)) {
74866
75209
  throw new Error(`the client read stream answered HTTP ${String(answer.status)}`);
74867
75210
  }
74868
75211
  deps.log?.(`rc stream ${attachment.sessionId}: attached as client ${attachment.clientId}${resume === void 0 ? ", reading from the stream's own head" : `, resuming after sequence number ${String(resume.fromSequenceNum)}`}`);
@@ -75066,8 +75409,8 @@ function zaiWindow(limit) {
75066
75409
  var zaiQuotaAdapter = {
75067
75410
  source: ZAI_SOURCE,
75068
75411
  matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === ZAI_HOST,
75069
- fetch: async (apiKey, http7, signal, nowMs) => {
75070
- const response = await http7(ZAI_QUOTA_URL, { authorization: apiKey, accept: "application/json" }, signal);
75412
+ fetch: async (apiKey, http8, signal, nowMs) => {
75413
+ const response = await http8(ZAI_QUOTA_URL, { authorization: apiKey, accept: "application/json" }, signal);
75071
75414
  if (response.status !== HTTP_OK) {
75072
75415
  throw new ProviderQuotaError(ZAI_SOURCE, `answered HTTP ${String(response.status)}`);
75073
75416
  }
@@ -75108,8 +75451,8 @@ var OpenRouterKeySchema = external_exports.object({
75108
75451
  })
75109
75452
  });
75110
75453
  var OpenRouterCreditsSchema = external_exports.object({ data: external_exports.object({ total_credits: external_exports.number().nonnegative(), total_usage: external_exports.number().nonnegative() }) });
75111
- async function openRouterGet(url2, schema, apiKey, http7, signal) {
75112
- const response = await http7(url2, { authorization: `Bearer ${apiKey}`, accept: "application/json" }, signal);
75454
+ async function openRouterGet(url2, schema, apiKey, http8, signal) {
75455
+ const response = await http8(url2, { authorization: `Bearer ${apiKey}`, accept: "application/json" }, signal);
75113
75456
  if (response.status === HTTP_FORBIDDEN) {
75114
75457
  return "forbidden";
75115
75458
  }
@@ -75134,12 +75477,12 @@ function nextUtcMidnight(nowMs) {
75134
75477
  var openRouterQuotaAdapter = {
75135
75478
  source: OPENROUTER_SOURCE,
75136
75479
  matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === OPENROUTER_HOST,
75137
- fetch: async (apiKey, http7, signal, nowMs) => {
75138
- const key = await openRouterGet(OPENROUTER_KEY_URL, OpenRouterKeySchema, apiKey, http7, signal);
75480
+ fetch: async (apiKey, http8, signal, nowMs) => {
75481
+ const key = await openRouterGet(OPENROUTER_KEY_URL, OpenRouterKeySchema, apiKey, http8, signal);
75139
75482
  if (key === "forbidden") {
75140
75483
  throw new ProviderQuotaError(OPENROUTER_SOURCE, "/api/v1/key refused the key (HTTP 403)");
75141
75484
  }
75142
- const credits = await openRouterGet(OPENROUTER_CREDITS_URL, OpenRouterCreditsSchema, apiKey, http7, signal);
75485
+ const credits = await openRouterGet(OPENROUTER_CREDITS_URL, OpenRouterCreditsSchema, apiKey, http8, signal);
75143
75486
  const { limit, limit_remaining: limitRemaining, limit_reset: limitReset, free_model_daily_requests: free, is_free_tier: isFreeTier } = key.data;
75144
75487
  const windows = [];
75145
75488
  if (limit !== null && limit > 0) {
@@ -75335,6 +75678,7 @@ function realFrontDoorSupervisorPorts(paths) {
75335
75678
  newUuid: import_node_crypto14.randomUUID,
75336
75679
  randomToken: () => (0, import_node_crypto14.randomBytes)(MINTED_TOKEN_RANDOM_BYTES).toString("base64url"),
75337
75680
  credentialRecord: () => readRcSelfHostRecord(realFarmFs, paths.frontdoorDir),
75681
+ webFetch: realRcWebFetch({ allowPrivate: rcWebFetchAllowsPrivateFromEnv(process.env) }),
75338
75682
  log
75339
75683
  }) : void 0;
75340
75684
  const rcCredentialStore = createRcCredentialStore(realFarmFs, paths.frontdoorRcCredentialsDir);
@@ -76471,14 +76815,14 @@ var import_node_crypto16 = require("node:crypto");
76471
76815
  var import_node_path38 = __toESM(require("node:path"), 1);
76472
76816
  var BUNDLE_NAME_HEX_DIGITS = 16;
76473
76817
  function resolveTrustBundle(params) {
76474
- const { caCertFile, bundlesDir, variable, inherited, fs: fs19 } = params;
76818
+ const { caCertFile, bundlesDir, variable, inherited, fs: fs20 } = params;
76475
76819
  if (inherited === void 0 || inherited === "" || import_node_path38.default.resolve(inherited) === import_node_path38.default.resolve(caCertFile)) {
76476
76820
  return { path: caCertFile };
76477
76821
  }
76478
- const caPem = fs19.readFileUtf8(caCertFile);
76822
+ const caPem = fs20.readFileUtf8(caCertFile);
76479
76823
  let inheritedPem;
76480
76824
  try {
76481
- inheritedPem = fs19.readFileUtf8(inherited);
76825
+ inheritedPem = fs20.readFileUtf8(inherited);
76482
76826
  } catch (error62) {
76483
76827
  return {
76484
76828
  path: caCertFile,
@@ -76491,9 +76835,9 @@ function resolveTrustBundle(params) {
76491
76835
  const combined = `${inheritedPem.trimEnd()}
76492
76836
  ${caPem}`;
76493
76837
  const bundle = import_node_path38.default.join(bundlesDir, `${(0, import_node_crypto16.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
76494
- if (!fs19.exists(bundle)) {
76495
- fs19.mkdirp(bundlesDir);
76496
- fs19.writeFileAtomic(bundle, combined);
76838
+ if (!fs20.exists(bundle)) {
76839
+ fs20.mkdirp(bundlesDir);
76840
+ fs20.writeFileAtomic(bundle, combined);
76497
76841
  }
76498
76842
  return { path: bundle };
76499
76843
  }
@@ -77194,6 +77538,366 @@ function registerRunCommand(program2, handler) {
77194
77538
  });
77195
77539
  }
77196
77540
 
77541
+ // src/update/commands.ts
77542
+ var import_node_fs17 = __toESM(require("node:fs"), 1);
77543
+ var import_node_os7 = __toESM(require("node:os"), 1);
77544
+ var import_node_path41 = __toESM(require("node:path"), 1);
77545
+
77546
+ // src/update/update.ts
77547
+ var import_node_crypto17 = require("node:crypto");
77548
+ var import_node_path40 = __toESM(require("node:path"), 1);
77549
+ var LATEST_RELEASE_URL = "https://github.com/ExaDev/agent-shim/releases/latest";
77550
+ var DOWNLOAD_BASE_URL = "https://github.com/ExaDev/agent-shim/releases/latest/download";
77551
+ var MACOS_X64_NOTE = "the standalone macOS x64 binary is currently broken upstream (see https://github.com/ExaDev/agent-shim#build-node-sea)";
77552
+ var BREW_PREFIXES = ["/opt/homebrew", "/usr/local/Cellar", "/home/linuxbrew/.linuxbrew"];
77553
+ var EXECUTABLE_MODE = 493;
77554
+ var UpdateChannelError = class extends CliError {
77555
+ constructor(message) {
77556
+ super(message);
77557
+ this.name = "UpdateChannelError";
77558
+ }
77559
+ };
77560
+ var UpdateConflictError = class extends CliError {
77561
+ constructor(message) {
77562
+ super(message);
77563
+ this.name = "UpdateConflictError";
77564
+ }
77565
+ };
77566
+ var UpdateDownloadError = class extends CliError {
77567
+ constructor(message) {
77568
+ super(message);
77569
+ this.name = "UpdateDownloadError";
77570
+ }
77571
+ };
77572
+ function compareVersions3(left, right) {
77573
+ const parse3 = (version2) => {
77574
+ const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version2);
77575
+ if (match === null) {
77576
+ throw new Error(`not a plain release version: ${version2}`);
77577
+ }
77578
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
77579
+ };
77580
+ const leftParts = parse3(left);
77581
+ const rightParts = parse3(right);
77582
+ return leftParts.map((part, index) => part - (rightParts[index] ?? 0)).find((difference) => difference !== 0) ?? 0;
77583
+ }
77584
+ function releaseTagFromUrl(url2) {
77585
+ const segment = url2.split("?")[0]?.split("/").at(-1);
77586
+ const candidate = segment?.startsWith("v") === true ? segment.slice(1) : void 0;
77587
+ return candidate !== void 0 && /^\d+\.\d+\.\d+$/.test(candidate) ? candidate : void 0;
77588
+ }
77589
+ function selectAsset(platform, arch) {
77590
+ if (platform === "darwin") {
77591
+ return arch === "arm64" ? "agent-shim-macos-arm64" : void 0;
77592
+ }
77593
+ if (platform === "linux") {
77594
+ if (arch === "arm64" || arch === "aarch64") {
77595
+ return "agent-shim-linux-arm64";
77596
+ }
77597
+ return arch === "x64" ? "agent-shim-linux-x64" : void 0;
77598
+ }
77599
+ return void 0;
77600
+ }
77601
+ function channelUpgradeCommand(channel) {
77602
+ switch (channel.kind) {
77603
+ case "brew":
77604
+ return "brew upgrade agent-shim";
77605
+ case "npm":
77606
+ return "npm install -g agent-shim@latest";
77607
+ case "scoop":
77608
+ return "scoop update agent-shim";
77609
+ default:
77610
+ return channel;
77611
+ }
77612
+ }
77613
+ function channelRefusalMessage(channel) {
77614
+ const command = channelUpgradeCommand(channel);
77615
+ switch (channel.kind) {
77616
+ case "brew":
77617
+ return `this agent-shim was installed by Homebrew, so it updates through Homebrew instead: ${command}`;
77618
+ case "npm":
77619
+ switch (channel.reason) {
77620
+ case "node_modules":
77621
+ return `this agent-shim was installed by npm, so it updates through npm instead: ${command}`;
77622
+ case "script":
77623
+ return `the running agent-shim is a script rather than a release binary, so it updates through npm instead: ${command}`;
77624
+ case "macos-x64":
77625
+ return `${MACOS_X64_NOTE}, so it updates through npm instead: ${command}`;
77626
+ default:
77627
+ return channel.reason;
77628
+ }
77629
+ case "scoop":
77630
+ return `this agent-shim was installed by Scoop, so it updates through Scoop instead: ${command}`;
77631
+ default:
77632
+ return channel;
77633
+ }
77634
+ }
77635
+ function underBrewPrefix(executableRealPath) {
77636
+ return BREW_PREFIXES.some((prefix) => executableRealPath === prefix || executableRealPath.startsWith(`${prefix}/`));
77637
+ }
77638
+ function detectChannel(env) {
77639
+ if (env.platform === "win32") {
77640
+ return { kind: "scoop" };
77641
+ }
77642
+ if (underBrewPrefix(env.executableRealPath)) {
77643
+ return { kind: "brew" };
77644
+ }
77645
+ if (env.executableRealPath.split(/[\\/]/).includes("node_modules")) {
77646
+ return { kind: "npm", reason: "node_modules" };
77647
+ }
77648
+ if ((env.fileHead ?? "").startsWith("#!")) {
77649
+ return { kind: "npm", reason: "script" };
77650
+ }
77651
+ if (env.platform === "darwin" && env.arch === "x64") {
77652
+ return { kind: "npm", reason: "macos-x64" };
77653
+ }
77654
+ return { kind: "self" };
77655
+ }
77656
+ function lockHolder(contents) {
77657
+ const pid = Number((contents ?? "").trim());
77658
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
77659
+ }
77660
+ function acquireUpdateLock(fs20, isProcessAlive, pid, lockPath) {
77661
+ const take = () => fs20.writeFileExclusive(lockPath, `${String(pid)}
77662
+ `);
77663
+ const release = () => {
77664
+ fs20.unlink(lockPath);
77665
+ };
77666
+ if (take()) {
77667
+ return release;
77668
+ }
77669
+ const holder = lockHolder(fs20.readFileUtf8(lockPath));
77670
+ if (holder !== void 0 && holder !== pid && isProcessAlive(holder)) {
77671
+ throw new UpdateConflictError(`another agent-shim update (pid ${String(holder)}) is already running`);
77672
+ }
77673
+ fs20.unlink(lockPath);
77674
+ if (!take()) {
77675
+ throw new UpdateConflictError("another agent-shim update took the lock while it was being replaced");
77676
+ }
77677
+ return release;
77678
+ }
77679
+ function expectedSha256(sidecar) {
77680
+ const first = sidecar.trim().split(/\s+/)[0];
77681
+ return first === "" ? void 0 : first;
77682
+ }
77683
+ async function mustDownload(http8, url2) {
77684
+ try {
77685
+ return await http8.download(url2);
77686
+ } catch (error62) {
77687
+ throw new UpdateDownloadError(`could not download ${url2}: ${error62 instanceof Error ? error62.message : String(error62)}`);
77688
+ }
77689
+ }
77690
+ async function downloadAndInstall(ports, asset, target) {
77691
+ const tempDir = ports.fs.mkdtemp();
77692
+ try {
77693
+ const assetUrl = `${DOWNLOAD_BASE_URL}/${asset}`;
77694
+ ports.fs.writeFileBytes(import_node_path40.default.join(tempDir, asset), await mustDownload(ports.http, assetUrl));
77695
+ ports.fs.writeFileUtf8(import_node_path40.default.join(tempDir, `${asset}.sha256`), Buffer.from(await mustDownload(ports.http, `${assetUrl}.sha256`)).toString("utf8"));
77696
+ const downloaded = ports.fs.readFileBytes(import_node_path40.default.join(tempDir, asset));
77697
+ const sidecar = ports.fs.readFileUtf8(import_node_path40.default.join(tempDir, `${asset}.sha256`));
77698
+ if (downloaded === void 0 || sidecar === void 0) {
77699
+ throw new UpdateDownloadError(`the downloaded files for ${asset} are missing from ${tempDir}`);
77700
+ }
77701
+ const expected = expectedSha256(sidecar);
77702
+ const actual = (0, import_node_crypto17.createHash)("sha256").update(downloaded).digest("hex");
77703
+ if (expected === void 0 || expected !== actual) {
77704
+ throw new UpdateDownloadError(`checksum mismatch for ${asset} (expected ${expected ?? "(none)"}, got ${actual})`);
77705
+ }
77706
+ const tempBinary = import_node_path40.default.join(import_node_path40.default.dirname(target), `.${import_node_path40.default.basename(target)}.${String(process.pid)}.${(0, import_node_crypto17.randomUUID)()}.tmp`);
77707
+ ports.fs.writeFileBytes(tempBinary, downloaded);
77708
+ try {
77709
+ ports.fs.chmod(tempBinary, EXECUTABLE_MODE);
77710
+ ports.fs.rename(tempBinary, target);
77711
+ } catch (error62) {
77712
+ ports.fs.unlink(tempBinary);
77713
+ throw error62;
77714
+ }
77715
+ } finally {
77716
+ ports.fs.rmRecursive(tempDir);
77717
+ }
77718
+ }
77719
+ async function runSelfUpdate(ports, options) {
77720
+ const executableRealPath = ports.fs.realpath(options.executablePath);
77721
+ const channel = detectChannel({ platform: options.platform, arch: options.arch, executableRealPath, fileHead: ports.fs.readFileHead(executableRealPath, 2) });
77722
+ if (channel.kind !== "self") {
77723
+ throw new UpdateChannelError(channelRefusalMessage(channel));
77724
+ }
77725
+ const asset = selectAsset(options.platform, options.arch);
77726
+ if (asset === void 0) {
77727
+ throw new UpdateChannelError(`no release binary exists for ${options.platform} ${options.arch}; install agent-shim through one of the documented channels instead (see docs/installation.md)`);
77728
+ }
77729
+ let effectiveUrl;
77730
+ try {
77731
+ effectiveUrl = await ports.http.effectiveUrl(LATEST_RELEASE_URL);
77732
+ } catch (error62) {
77733
+ throw new UpdateDownloadError(`could not resolve the latest release from ${LATEST_RELEASE_URL}: ${error62 instanceof Error ? error62.message : String(error62)}`);
77734
+ }
77735
+ const latest = releaseTagFromUrl(effectiveUrl);
77736
+ if (latest === void 0) {
77737
+ throw new UpdateDownloadError(`could not read the latest release version from ${effectiveUrl}`);
77738
+ }
77739
+ if (compareVersions3(latest, options.currentVersion) <= 0) {
77740
+ return { current: options.currentVersion, latest: options.currentVersion, action: "current" };
77741
+ }
77742
+ if (options.checkOnly) {
77743
+ return { current: options.currentVersion, latest, action: "available" };
77744
+ }
77745
+ const releaseLock = acquireUpdateLock(ports.fs, ports.isProcessAlive, options.pid, options.lockPath);
77746
+ try {
77747
+ await downloadAndInstall(ports, asset, executableRealPath);
77748
+ } finally {
77749
+ releaseLock();
77750
+ }
77751
+ return { current: options.currentVersion, latest, action: "updated" };
77752
+ }
77753
+
77754
+ // src/update/commands.ts
77755
+ function isEnoent6(error62) {
77756
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === "ENOENT";
77757
+ }
77758
+ function isErrorWithCode2(error62, code) {
77759
+ return typeof error62 === "object" && error62 !== null && "code" in error62 && error62.code === code;
77760
+ }
77761
+ var realUpdatePorts = {
77762
+ http: {
77763
+ effectiveUrl: async (url2) => {
77764
+ const response = await fetch(url2, { redirect: "follow" });
77765
+ if (!response.ok) {
77766
+ throw new Error(`HTTP ${String(response.status)}`);
77767
+ }
77768
+ return response.url;
77769
+ },
77770
+ download: async (url2) => {
77771
+ const response = await fetch(url2, { redirect: "follow" });
77772
+ if (!response.ok) {
77773
+ throw new Error(`HTTP ${String(response.status)}`);
77774
+ }
77775
+ return new Uint8Array(await response.arrayBuffer());
77776
+ }
77777
+ },
77778
+ fs: {
77779
+ realpath: (target) => import_node_fs17.default.realpathSync(target),
77780
+ readFileUtf8: (filePath) => {
77781
+ try {
77782
+ return import_node_fs17.default.readFileSync(filePath, "utf8");
77783
+ } catch (error62) {
77784
+ if (isEnoent6(error62)) {
77785
+ return void 0;
77786
+ }
77787
+ throw error62;
77788
+ }
77789
+ },
77790
+ readFileBytes: (filePath) => {
77791
+ try {
77792
+ return new Uint8Array(import_node_fs17.default.readFileSync(filePath));
77793
+ } catch (error62) {
77794
+ if (isEnoent6(error62)) {
77795
+ return void 0;
77796
+ }
77797
+ throw error62;
77798
+ }
77799
+ },
77800
+ readFileHead: (filePath, length) => {
77801
+ let descriptor;
77802
+ try {
77803
+ descriptor = import_node_fs17.default.openSync(filePath, "r");
77804
+ } catch (error62) {
77805
+ if (isEnoent6(error62)) {
77806
+ return void 0;
77807
+ }
77808
+ throw error62;
77809
+ }
77810
+ try {
77811
+ const buffer = Buffer.alloc(length);
77812
+ const read = import_node_fs17.default.readSync(descriptor, buffer, 0, length, 0);
77813
+ return read === 0 ? "" : buffer.toString("latin1", 0, read);
77814
+ } finally {
77815
+ import_node_fs17.default.closeSync(descriptor);
77816
+ }
77817
+ },
77818
+ writeFileUtf8: (filePath, contents) => {
77819
+ import_node_fs17.default.writeFileSync(filePath, contents, "utf8");
77820
+ },
77821
+ writeFileBytes: (filePath, contents) => {
77822
+ import_node_fs17.default.writeFileSync(filePath, contents);
77823
+ },
77824
+ writeFileExclusive: (filePath, contents) => {
77825
+ try {
77826
+ import_node_fs17.default.writeFileSync(filePath, contents, { encoding: "utf8", flag: "wx" });
77827
+ return true;
77828
+ } catch (error62) {
77829
+ if (isErrorWithCode2(error62, "EEXIST")) {
77830
+ return false;
77831
+ }
77832
+ throw error62;
77833
+ }
77834
+ },
77835
+ unlink: (filePath) => {
77836
+ try {
77837
+ import_node_fs17.default.unlinkSync(filePath);
77838
+ } catch (error62) {
77839
+ if (!isEnoent6(error62)) {
77840
+ throw error62;
77841
+ }
77842
+ }
77843
+ },
77844
+ rename: (from, to) => {
77845
+ import_node_fs17.default.renameSync(from, to);
77846
+ },
77847
+ chmod: (filePath, mode) => {
77848
+ import_node_fs17.default.chmodSync(filePath, mode);
77849
+ },
77850
+ mkdtemp: () => import_node_fs17.default.mkdtempSync(import_node_path41.default.join(import_node_os7.default.tmpdir(), "agent-shim-update-")),
77851
+ rmRecursive: (targetPath) => {
77852
+ import_node_fs17.default.rmSync(targetPath, { recursive: true, force: true });
77853
+ }
77854
+ },
77855
+ // Signal 0 performs the permission and existence checks without delivering anything; EPERM means the process exists but belongs to another user.
77856
+ isProcessAlive: (pid) => {
77857
+ try {
77858
+ process.kill(pid, 0);
77859
+ return true;
77860
+ } catch (error62) {
77861
+ return isErrorWithCode2(error62, "EPERM");
77862
+ }
77863
+ }
77864
+ };
77865
+ function formatUpdateReport(report) {
77866
+ switch (report.action) {
77867
+ case "current":
77868
+ return `already at the latest release (${report.latest})`;
77869
+ case "available":
77870
+ return `update available: ${report.current} -> ${report.latest} (run \`agent-shim update\` to install it)`;
77871
+ case "updated":
77872
+ return `updated agent-shim: ${report.current} -> ${report.latest}`;
77873
+ default:
77874
+ return report.action;
77875
+ }
77876
+ }
77877
+ function registerUpdateCommand(program2, deps, ports = realUpdatePorts) {
77878
+ withExamples(
77879
+ program2.command("update").description(
77880
+ "Download the newest release binary and install it over the running one. An installation that belongs to a package manager (Homebrew, npm, Scoop) names its channel and its upgrade command instead of updating in place."
77881
+ ).option("--check", "Only report whether a newer release exists; download and change nothing.").option("--json", "Print the result as JSON.").action(async (options) => {
77882
+ const report = await runSelfUpdate(ports, {
77883
+ currentVersion: package_default.version,
77884
+ platform: process.platform,
77885
+ arch: process.arch,
77886
+ executablePath: realOwnExecutablePath(),
77887
+ lockPath: import_node_path41.default.join(deps.paths.root, "update.lock"),
77888
+ checkOnly: options.check === true,
77889
+ pid: process.pid
77890
+ });
77891
+ if (options.json === true) {
77892
+ printJson(report);
77893
+ return;
77894
+ }
77895
+ console.log(formatUpdateReport(report));
77896
+ }),
77897
+ ["agent-shim update", "agent-shim update --check", "agent-shim update --json"]
77898
+ );
77899
+ }
77900
+
77197
77901
  // src/usage/commands.ts
77198
77902
  var DAY_MS3 = 864e5;
77199
77903
  function requireIdentity(paths, name) {
@@ -77201,14 +77905,14 @@ function requireIdentity(paths, name) {
77201
77905
  throw new IdentityNotFoundError(name);
77202
77906
  }
77203
77907
  }
77204
- function collectUsageReport(fs19, paths, filters) {
77908
+ function collectUsageReport(fs20, paths, filters) {
77205
77909
  const { identity, provider, sinceMs } = filters;
77206
77910
  if (identity !== void 0) {
77207
77911
  requireIdentity(paths, identity);
77208
77912
  }
77209
- const log = readUsageLog(fs19, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
77913
+ const log = readUsageLog(fs20, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
77210
77914
  const records = log.records.filter((record2) => (identity === void 0 || record2.identity === identity) && (provider === void 0 || record2.provider === provider));
77211
- const snapshots = (identity === void 0 ? listUsageSnapshots(fs19, paths.usageSnapshotsDir) : [readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
77915
+ const snapshots = (identity === void 0 ? listUsageSnapshots(fs20, paths.usageSnapshotsDir) : [readUsageSnapshot(fs20, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
77212
77916
  return {
77213
77917
  since: sinceMs === void 0 ? void 0 : new Date(sinceMs).toISOString(),
77214
77918
  logDir: paths.usageLogDir,
@@ -77304,15 +78008,15 @@ function formatUsageReport(report) {
77304
78008
  }
77305
78009
  return lines;
77306
78010
  }
77307
- function collectAccounts(fs19, paths, identity) {
78011
+ function collectAccounts(fs20, paths, identity) {
77308
78012
  if (identity !== void 0) {
77309
78013
  requireIdentity(paths, identity);
77310
78014
  }
77311
78015
  const names = identity === void 0 ? listIdentities(paths).map((entry) => entry.name) : [identity];
77312
78016
  return names.map((name) => ({
77313
78017
  identity: name,
77314
- account: readAccountMetadata(fs19, paths.identitiesDir, name),
77315
- usage: readUsageSnapshot(fs19, paths.usageSnapshotsDir, name)
78018
+ account: readAccountMetadata(fs20, paths.identitiesDir, name),
78019
+ usage: readUsageSnapshot(fs20, paths.usageSnapshotsDir, name)
77316
78020
  }));
77317
78021
  }
77318
78022
  function formatAccounts(views) {
@@ -77471,17 +78175,18 @@ function buildProgram(deps) {
77471
78175
  registerFrontDoorCommand(program2, deps);
77472
78176
  registerUsageCommands(program2, deps);
77473
78177
  registerRunCommand(program2, deps.runClaude);
78178
+ registerUpdateCommand(program2, deps, deps.updatePorts);
77474
78179
  registerCompletionCommand(program2);
77475
78180
  return program2;
77476
78181
  }
77477
78182
 
77478
78183
  // src/launchWiring.ts
77479
- var import_node_os8 = __toESM(require("node:os"), 1);
77480
- var import_node_crypto18 = require("node:crypto");
78184
+ var import_node_os9 = __toESM(require("node:os"), 1);
78185
+ var import_node_crypto19 = require("node:crypto");
77481
78186
 
77482
78187
  // src/launcher.ts
77483
- var import_node_crypto17 = require("node:crypto");
77484
- var import_node_path41 = __toESM(require("node:path"), 1);
78188
+ var import_node_crypto18 = require("node:crypto");
78189
+ var import_node_path43 = __toESM(require("node:path"), 1);
77485
78190
 
77486
78191
  // src/launcher/cliOverride.ts
77487
78192
  var InvalidCliCategoryError = class extends CliError {
@@ -77565,7 +78270,7 @@ function buildCliOverride(params) {
77565
78270
  }
77566
78271
 
77567
78272
  // src/launcher/flags.ts
77568
- var import_node_path40 = __toESM(require("node:path"), 1);
78273
+ var import_node_path42 = __toESM(require("node:path"), 1);
77569
78274
 
77570
78275
  // src/headroom/headers.ts
77571
78276
  function mergeAnthropicCustomHeaders(existing, additions) {
@@ -77626,7 +78331,7 @@ function buildEnv(params) {
77626
78331
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
77627
78332
  let providerCustomHeaders;
77628
78333
  if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
77629
- env.CLAUDE_CONFIG_DIR = import_node_path40.default.join(params.identitiesDir, params.resolvedIdentityName);
78334
+ env.CLAUDE_CONFIG_DIR = import_node_path42.default.join(params.identitiesDir, params.resolvedIdentityName);
77630
78335
  }
77631
78336
  if (params.provider !== void 0) {
77632
78337
  const providerEnv = params.provider.definition.env ?? {};
@@ -77752,14 +78457,14 @@ function resolvePoolLaunch(params) {
77752
78457
  }
77753
78458
 
77754
78459
  // src/launcher/spawn.ts
77755
- var import_node_os7 = __toESM(require("node:os"), 1);
78460
+ var import_node_os8 = __toESM(require("node:os"), 1);
77756
78461
  var SIGNAL_EXIT_CODE_OFFSET = 128;
77757
78462
  function exitCodeFor(result) {
77758
78463
  if (result.status !== null) {
77759
78464
  return result.status;
77760
78465
  }
77761
78466
  if (result.signal !== null) {
77762
- return SIGNAL_EXIT_CODE_OFFSET + import_node_os7.default.constants.signals[result.signal];
78467
+ return SIGNAL_EXIT_CODE_OFFSET + import_node_os8.default.constants.signals[result.signal];
77763
78468
  }
77764
78469
  return 1;
77765
78470
  }
@@ -77783,7 +78488,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
77783
78488
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: resolution.message };
77784
78489
  }
77785
78490
  function pickFromPool(decided, params, parsedArgv) {
77786
- const { paths, fs: fs19, proc, log } = params;
78491
+ const { paths, fs: fs20, proc, log } = params;
77787
78492
  if (decided.pool === void 0) {
77788
78493
  return { identityDecision: decided };
77789
78494
  }
@@ -77797,7 +78502,7 @@ function pickFromPool(decided, params, parsedArgv) {
77797
78502
  selectedVia: decided.source,
77798
78503
  pools: params.pools,
77799
78504
  paths,
77800
- fs: fs19,
78505
+ fs: fs20,
77801
78506
  usageFs: farmRuntime.fs,
77802
78507
  cwd: farmRuntime.cwd,
77803
78508
  now: farmRuntime.now,
@@ -77813,7 +78518,7 @@ function pickFromPool(decided, params, parsedArgv) {
77813
78518
  return { identityDecision: { ...decided, name: resolution.identity }, poolExplanation: resolution.explanation };
77814
78519
  }
77815
78520
  function prepareLaunch(params) {
77816
- const { paths, fs: fs19, proc, log } = params;
78521
+ const { paths, fs: fs20, proc, log } = params;
77817
78522
  const { env, argv } = proc;
77818
78523
  const parsedArgv = parseLauncherArgv(argv);
77819
78524
  const cliOverride = buildCliOverride({
@@ -77828,7 +78533,7 @@ function prepareLaunch(params) {
77828
78533
  argv0Identity: parsedArgv.identity,
77829
78534
  directoryPinnedIdentity: params.directoryPinnedIdentity,
77830
78535
  readActiveIdentityFile: () => {
77831
- const raw = fs19.readFileUtf8(paths.activeIdentityFile);
78536
+ const raw = fs20.readFileUtf8(paths.activeIdentityFile);
77832
78537
  if (raw === void 0) {
77833
78538
  return void 0;
77834
78539
  }
@@ -77863,7 +78568,7 @@ function prepareLaunch(params) {
77863
78568
  }
77864
78569
  let loadedIdentity;
77865
78570
  if (identityDecision.name !== void 0) {
77866
- loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs19);
78571
+ loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs20);
77867
78572
  if (loadedIdentity === void 0) {
77868
78573
  log.error(
77869
78574
  `agent-shim: no identity named "${identityDecision.name}" (selected via ${identityDecision.source}). Run \`agent-shim identity add ${identityDecision.name}\` first.`
@@ -77878,7 +78583,7 @@ function prepareLaunch(params) {
77878
78583
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
77879
78584
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
77880
78585
  });
77881
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs19.readConfigFile(import_node_path41.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
78586
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs20.readConfigFile(import_node_path43.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
77882
78587
  log.error(
77883
78588
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
77884
78589
  );
@@ -77887,7 +78592,7 @@ function prepareLaunch(params) {
77887
78592
  const farmContext = farm !== void 0 && farmIdentity !== void 0 ? { farm, identity: farmIdentity, cascade: farm.loadCascade(configProfileDecision.name, cliOverride) } : void 0;
77888
78593
  const provider = parsedArgv.provider === false ? void 0 : resolveProvider({
77889
78594
  paths,
77890
- port: fs19,
78595
+ port: fs20,
77891
78596
  env,
77892
78597
  ...params.credentials === void 0 ? {} : { credentials: params.credentials },
77893
78598
  ...parsedArgv.provider === void 0 ? {} : { cliProvider: parsedArgv.provider },
@@ -78036,7 +78741,7 @@ function prepareLaunch(params) {
78036
78741
  ...identityCredential === void 0 ? {} : { identityCredential },
78037
78742
  ...frontDoor === void 0 ? {} : { frontdoor: frontDoor },
78038
78743
  ...headroom === void 0 ? {} : { headroom },
78039
- sessionId: (0, import_node_crypto17.randomUUID)()
78744
+ sessionId: (0, import_node_crypto18.randomUUID)()
78040
78745
  });
78041
78746
  const releases = [...headroom === void 0 || headroomPort === void 0 ? [] : [headroomPort.release], ...frontDoorRelease === void 0 ? [] : [frontDoorRelease]];
78042
78747
  const release = () => {
@@ -78057,7 +78762,7 @@ function runLauncher(params) {
78057
78762
 
78058
78763
  // src/launchWiring.ts
78059
78764
  function buildFarmRuntime(paths, cwd) {
78060
- const home = import_node_os8.default.homedir();
78765
+ const home = import_node_os9.default.homedir();
78061
78766
  const read = cosmiconfigReader();
78062
78767
  const classification = loadClassification(paths);
78063
78768
  const loaded = loadCascadeInput({ paths, home, cwd, read });
@@ -78081,7 +78786,7 @@ function buildFarmRuntime(paths, cwd) {
78081
78786
  ...cliOverride === void 0 ? {} : { cliOverride }
78082
78787
  }).input,
78083
78788
  now: () => Date.now(),
78084
- uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto18.randomUUID)()}`,
78789
+ uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto19.randomUUID)()}`,
78085
78790
  // Zombie-aware on purpose: a previous launcher that crashed out of a resync without releasing the lock may sit unreaped, still answering signal 0 as alive, and must read as a dead holder so this launch takes the lock over instead of timing out.
78086
78791
  lock: { pid: process.pid, isRunning: realIsProcessRunning, sleep: realSleepSync }
78087
78792
  },
@@ -78220,7 +78925,7 @@ async function runClaude(argvOverride) {
78220
78925
  // src/cli.ts
78221
78926
  async function main() {
78222
78927
  aliasLegacyEnv(process.env);
78223
- const invokedName = import_node_path42.default.basename(process.argv[1] ?? "agent-shim");
78928
+ const invokedName = import_node_path44.default.basename(process.argv[1] ?? "agent-shim");
78224
78929
  if (isInvokedAsClaude(invokedName)) {
78225
78930
  await runClaude();
78226
78931
  return;