agent-shim 8.43.0 → 9.0.0

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
@@ -318,10 +318,10 @@ function mergeDefs(...defs) {
318
318
  function cloneDef(schema) {
319
319
  return mergeDefs(schema._zod.def);
320
320
  }
321
- function getElementAtPath(obj, path46) {
322
- if (!path46)
321
+ function getElementAtPath(obj, path47) {
322
+ if (!path47)
323
323
  return obj;
324
- return path46.reduce((acc, key) => acc?.[key], obj);
324
+ return path47.reduce((acc, key) => acc?.[key], obj);
325
325
  }
326
326
  function promiseAllObject(promisesObj) {
327
327
  const keys = Object.keys(promisesObj);
@@ -580,11 +580,11 @@ function explicitlyAborted(x, startIndex = 0) {
580
580
  }
581
581
  return false;
582
582
  }
583
- function prefixIssues(path46, issues) {
583
+ function prefixIssues(path47, issues) {
584
584
  return issues.map((iss) => {
585
585
  var _a4;
586
586
  (_a4 = iss).path ?? (_a4.path = []);
587
- iss.path.unshift(path46);
587
+ iss.path.unshift(path47);
588
588
  return iss;
589
589
  });
590
590
  }
@@ -1105,16 +1105,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
1105
1105
  }
1106
1106
  function formatError(error62, mapper = (issue2) => issue2.message) {
1107
1107
  const fieldErrors = { _errors: [] };
1108
- const processError = (error63, path46 = []) => {
1108
+ const processError = (error63, path47 = []) => {
1109
1109
  for (const issue2 of error63.issues) {
1110
1110
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1111
- issue2.errors.map((issues) => processError({ issues }, [...path46, ...issue2.path]));
1111
+ issue2.errors.map((issues) => processError({ issues }, [...path47, ...issue2.path]));
1112
1112
  } else if (issue2.code === "invalid_key") {
1113
- processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
1113
+ processError({ issues: issue2.issues }, [...path47, ...issue2.path]);
1114
1114
  } else if (issue2.code === "invalid_element") {
1115
- processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
1115
+ processError({ issues: issue2.issues }, [...path47, ...issue2.path]);
1116
1116
  } else {
1117
- const fullpath = [...path46, ...issue2.path];
1117
+ const fullpath = [...path47, ...issue2.path];
1118
1118
  if (fullpath.length === 0) {
1119
1119
  fieldErrors._errors.push(mapper(issue2));
1120
1120
  } else {
@@ -1153,17 +1153,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
1153
1153
  }
1154
1154
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
1155
1155
  const result = { errors: [] };
1156
- const processError = (error63, path46 = []) => {
1156
+ const processError = (error63, path47 = []) => {
1157
1157
  var _a4;
1158
1158
  for (const issue2 of error63.issues) {
1159
1159
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1160
- issue2.errors.map((issues) => processError({ issues }, [...path46, ...issue2.path]));
1160
+ issue2.errors.map((issues) => processError({ issues }, [...path47, ...issue2.path]));
1161
1161
  } else if (issue2.code === "invalid_key") {
1162
- processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
1162
+ processError({ issues: issue2.issues }, [...path47, ...issue2.path]);
1163
1163
  } else if (issue2.code === "invalid_element") {
1164
- processError({ issues: issue2.issues }, [...path46, ...issue2.path]);
1164
+ processError({ issues: issue2.issues }, [...path47, ...issue2.path]);
1165
1165
  } else {
1166
- const fullpath = [...path46, ...issue2.path];
1166
+ const fullpath = [...path47, ...issue2.path];
1167
1167
  if (fullpath.length === 0) {
1168
1168
  result.errors.push(mapper(issue2));
1169
1169
  continue;
@@ -1202,8 +1202,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
1202
1202
  }
1203
1203
  function toDotPath(_path) {
1204
1204
  const segs = [];
1205
- const path46 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
- for (const seg of path46) {
1205
+ const path47 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
+ for (const seg of path47) {
1207
1207
  if (typeof seg === "number")
1208
1208
  segs.push(`[${seg}]`);
1209
1209
  else if (typeof seg === "symbol")
@@ -19199,13 +19199,13 @@ function resolveRef(ref, ctx) {
19199
19199
  if (!ref.startsWith("#")) {
19200
19200
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19201
19201
  }
19202
- const path46 = ref.slice(1).split("/").filter(Boolean);
19203
- if (path46.length === 0) {
19202
+ const path47 = ref.slice(1).split("/").filter(Boolean);
19203
+ if (path47.length === 0) {
19204
19204
  return ctx.rootSchema;
19205
19205
  }
19206
19206
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19207
- if (path46[0] === defsKey) {
19208
- const key = path46[1] === void 0 ? void 0 : decodeJSONPointerSegment(path46[1]);
19207
+ if (path47[0] === defsKey) {
19208
+ const key = path47[1] === void 0 ? void 0 : decodeJSONPointerSegment(path47[1]);
19209
19209
  if (!key || !ctx.defs[key]) {
19210
19210
  throw new Error(`Reference not found: ${ref}`);
19211
19211
  }
@@ -23712,42 +23712,42 @@ var require_defaults = __commonJS({
23712
23712
  var require_env_paths = __commonJS({
23713
23713
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
23714
23714
  "use strict";
23715
- var path46 = require("path");
23715
+ var path47 = require("path");
23716
23716
  var os12 = require("os");
23717
23717
  var homedir = os12.homedir();
23718
23718
  var tmpdir = os12.tmpdir();
23719
23719
  var { env } = process;
23720
23720
  var macos = (name) => {
23721
- const library = path46.join(homedir, "Library");
23721
+ const library = path47.join(homedir, "Library");
23722
23722
  return {
23723
- data: path46.join(library, "Application Support", name),
23724
- config: path46.join(library, "Preferences", name),
23725
- cache: path46.join(library, "Caches", name),
23726
- log: path46.join(library, "Logs", name),
23727
- temp: path46.join(tmpdir, name)
23723
+ data: path47.join(library, "Application Support", name),
23724
+ config: path47.join(library, "Preferences", name),
23725
+ cache: path47.join(library, "Caches", name),
23726
+ log: path47.join(library, "Logs", name),
23727
+ temp: path47.join(tmpdir, name)
23728
23728
  };
23729
23729
  };
23730
23730
  var windows = (name) => {
23731
- const appData = env.APPDATA || path46.join(homedir, "AppData", "Roaming");
23732
- const localAppData = env.LOCALAPPDATA || path46.join(homedir, "AppData", "Local");
23731
+ const appData = env.APPDATA || path47.join(homedir, "AppData", "Roaming");
23732
+ const localAppData = env.LOCALAPPDATA || path47.join(homedir, "AppData", "Local");
23733
23733
  return {
23734
23734
  // Data/config/cache/log are invented by me as Windows isn't opinionated about this
23735
- data: path46.join(localAppData, name, "Data"),
23736
- config: path46.join(appData, name, "Config"),
23737
- cache: path46.join(localAppData, name, "Cache"),
23738
- log: path46.join(localAppData, name, "Log"),
23739
- temp: path46.join(tmpdir, name)
23735
+ data: path47.join(localAppData, name, "Data"),
23736
+ config: path47.join(appData, name, "Config"),
23737
+ cache: path47.join(localAppData, name, "Cache"),
23738
+ log: path47.join(localAppData, name, "Log"),
23739
+ temp: path47.join(tmpdir, name)
23740
23740
  };
23741
23741
  };
23742
23742
  var linux = (name) => {
23743
- const username = path46.basename(homedir);
23743
+ const username = path47.basename(homedir);
23744
23744
  return {
23745
- data: path46.join(env.XDG_DATA_HOME || path46.join(homedir, ".local", "share"), name),
23746
- config: path46.join(env.XDG_CONFIG_HOME || path46.join(homedir, ".config"), name),
23747
- cache: path46.join(env.XDG_CACHE_HOME || path46.join(homedir, ".cache"), name),
23745
+ data: path47.join(env.XDG_DATA_HOME || path47.join(homedir, ".local", "share"), name),
23746
+ config: path47.join(env.XDG_CONFIG_HOME || path47.join(homedir, ".config"), name),
23747
+ cache: path47.join(env.XDG_CACHE_HOME || path47.join(homedir, ".cache"), name),
23748
23748
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
23749
- log: path46.join(env.XDG_STATE_HOME || path46.join(homedir, ".local", "state"), name),
23750
- temp: path46.join(tmpdir, username, name)
23749
+ log: path47.join(env.XDG_STATE_HOME || path47.join(homedir, ".local", "state"), name),
23750
+ temp: path47.join(tmpdir, username, name)
23751
23751
  };
23752
23752
  };
23753
23753
  var envPaths = (name, options) => {
@@ -23815,11 +23815,11 @@ var require_util = __commonJS({
23815
23815
  return result;
23816
23816
  }
23817
23817
  exports2.emplace = emplace;
23818
- function getPropertyByPath(source, path46) {
23819
- if (typeof path46 === "string" && Object.prototype.hasOwnProperty.call(source, path46)) {
23820
- return source[path46];
23818
+ function getPropertyByPath(source, path47) {
23819
+ if (typeof path47 === "string" && Object.prototype.hasOwnProperty.call(source, path47)) {
23820
+ return source[path47];
23821
23821
  }
23822
- const parsedPath = typeof path46 === "string" ? path46.split(".") : path46;
23822
+ const parsedPath = typeof path47 === "string" ? path47.split(".") : path47;
23823
23823
  return parsedPath.reduce((previous, key) => {
23824
23824
  if (previous === void 0) {
23825
23825
  return previous;
@@ -23842,9 +23842,9 @@ var require_util = __commonJS({
23842
23842
  return Object.fromEntries(Object.entries(options).filter(([, value2]) => value2 !== void 0));
23843
23843
  }
23844
23844
  exports2.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
23845
- async function isDirectory(path46) {
23845
+ async function isDirectory(path47) {
23846
23846
  try {
23847
- const stat = await fs_1.promises.stat(path46);
23847
+ const stat = await fs_1.promises.stat(path47);
23848
23848
  return stat.isDirectory();
23849
23849
  } catch (e14) {
23850
23850
  if (e14.code === "ENOENT") {
@@ -23854,9 +23854,9 @@ var require_util = __commonJS({
23854
23854
  }
23855
23855
  }
23856
23856
  exports2.isDirectory = isDirectory;
23857
- function isDirectorySync(path46) {
23857
+ function isDirectorySync(path47) {
23858
23858
  try {
23859
- const stat = fs_1.default.statSync(path46);
23859
+ const stat = fs_1.default.statSync(path47);
23860
23860
  return stat.isDirectory();
23861
23861
  } catch (e14) {
23862
23862
  if (e14.code === "ENOENT") {
@@ -23954,7 +23954,7 @@ var require_ExplorerBase = __commonJS({
23954
23954
  const idx = importStack.indexOf(fullPath);
23955
23955
  if (idx !== -1) {
23956
23956
  throw new Error(`Circular import detected:
23957
- ${[...importStack, fullPath].map((path46, i10) => `${i10 + 1}. ${path46}`).join("\n")} (same as ${idx + 1}.)`);
23957
+ ${[...importStack, fullPath].map((path47, i10) => `${i10 + 1}. ${path47}`).join("\n")} (same as ${idx + 1}.)`);
23958
23958
  }
23959
23959
  }
23960
23960
  }
@@ -24142,9 +24142,9 @@ var require_Explorer = __commonJS({
24142
24142
  throw error62;
24143
24143
  }
24144
24144
  }
24145
- async #fileExists(path46) {
24145
+ async #fileExists(path47) {
24146
24146
  try {
24147
- await promises_1.default.stat(path46);
24147
+ await promises_1.default.stat(path47);
24148
24148
  return true;
24149
24149
  } catch (e14) {
24150
24150
  return false;
@@ -24304,9 +24304,9 @@ var require_ExplorerSync = __commonJS({
24304
24304
  throw error62;
24305
24305
  }
24306
24306
  }
24307
- #fileExists(path46) {
24307
+ #fileExists(path47) {
24308
24308
  try {
24309
- fs_1.default.statSync(path46);
24309
+ fs_1.default.statSync(path47);
24310
24310
  return true;
24311
24311
  } catch (e14) {
24312
24312
  return false;
@@ -24430,7 +24430,7 @@ var require_dist = __commonJS({
24430
24430
  };
24431
24431
  }
24432
24432
  function getResolvedSearchPlaces(moduleName, toolDefinedSearchPlaces, userConfiguredOptions) {
24433
- const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path46) => path46.replace("{name}", moduleName));
24433
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path47) => path47.replace("{name}", moduleName));
24434
24434
  if (userConfiguredOptions.mergeSearchPlaces) {
24435
24435
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
24436
24436
  }
@@ -27054,6 +27054,32 @@ function writeHeadroomState(fs21, stateFile, state) {
27054
27054
  fs21.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
27055
27055
  `);
27056
27056
  }
27057
+ function resolveServingHeadroomState(fs21, files, isRunning) {
27058
+ const current = readHeadroomState(fs21, files.stateFile);
27059
+ if (current !== void 0) {
27060
+ return { path: files.stateFile, state: current };
27061
+ }
27062
+ const legacy = readHeadroomState(fs21, files.legacyStateFile);
27063
+ if (legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid)) {
27064
+ return { path: files.legacyStateFile, state: legacy };
27065
+ }
27066
+ return void 0;
27067
+ }
27068
+ function migrateHeadroomState(fs21, files, isRunning) {
27069
+ const legacy = readHeadroomState(fs21, files.legacyStateFile);
27070
+ const legacyLive = legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid);
27071
+ const current = readHeadroomState(fs21, files.stateFile);
27072
+ if (current !== void 0 || legacyLive) {
27073
+ if (!legacyLive && fs21.readFileUtf8(files.legacyStateFile) !== void 0) {
27074
+ fs21.removeRecursive(files.legacyStateFile);
27075
+ }
27076
+ return;
27077
+ }
27078
+ if (legacy !== void 0) {
27079
+ writeHeadroomState(fs21, files.stateFile, legacy);
27080
+ }
27081
+ fs21.removeRecursive(files.legacyStateFile);
27082
+ }
27057
27083
  function headroomAllowlist(providers) {
27058
27084
  const urls = /* @__PURE__ */ new Set([HEADROOM_ANTHROPIC_UPSTREAM]);
27059
27085
  for (const provider of providers) {
@@ -27133,7 +27159,7 @@ function readStartLock(fs21, lockFile) {
27133
27159
  return void 0;
27134
27160
  }
27135
27161
  }
27136
- var import_node_crypto2, import_node_path5, HEADROOM_ANTHROPIC_UPSTREAM, HEADROOM_STATE_SCHEMA_VERSION, HeadroomStateSchema, HeadroomSessionSchema, HeadroomLockSchema;
27162
+ var import_node_crypto2, import_node_path5, HEADROOM_ANTHROPIC_UPSTREAM, HeadroomStateSchema, HeadroomSessionSchema, HeadroomLockSchema;
27137
27163
  var init_state = __esm({
27138
27164
  "src/headroom/state.ts"() {
27139
27165
  "use strict";
@@ -27142,7 +27168,6 @@ var init_state = __esm({
27142
27168
  init_zod();
27143
27169
  init_schema();
27144
27170
  HEADROOM_ANTHROPIC_UPSTREAM = "https://api.anthropic.com";
27145
- HEADROOM_STATE_SCHEMA_VERSION = 2;
27146
27171
  HeadroomStateSchema = external_exports.strictObject({
27147
27172
  /** The supervisor process owning the daemon. Alive means someone is keeping headroom running. */
27148
27173
  supervisorPid: external_exports.number().int().positive().optional(),
@@ -27174,8 +27199,9 @@ function ensureHeadroom(params) {
27174
27199
  const deadline = ports.now() + HEADROOM_START_TIMEOUT_MS;
27175
27200
  let spawnedSupervisor = false;
27176
27201
  let awaitingAllowlist = false;
27202
+ migrateHeadroomState(ports.fs, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
27177
27203
  for (; ; ) {
27178
- const state = readHeadroomState(ports.fs, paths.headroomStateFile);
27204
+ const state = resolveServingHeadroomState(ports.fs, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
27179
27205
  if (state?.supervisorPid !== void 0 && ports.isRunning(state.supervisorPid)) {
27180
27206
  const daemonUp = state.socketPath !== void 0 && state.headroomPid !== void 0 && ports.isRunning(state.headroomPid);
27181
27207
  if (daemonUp && state.socketPath !== void 0) {
@@ -27600,7 +27626,8 @@ function compareVersions2(a10, b) {
27600
27626
  async function runSupervisor(initialConfig, ports, options = {}) {
27601
27627
  const { fs: fs21, paths } = ports;
27602
27628
  let config2 = initialConfig;
27603
- const previousState = readHeadroomState(fs21, paths.headroomStateFile);
27629
+ migrateHeadroomState(fs21, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
27630
+ const previousState = resolveServingHeadroomState(fs21, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
27604
27631
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
27605
27632
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
27606
27633
  return 0;
@@ -28825,8 +28852,8 @@ var require_utils = __commonJS({
28825
28852
  }
28826
28853
  return output2;
28827
28854
  };
28828
- exports2.basename = (path46, { windows } = {}) => {
28829
- const segs = path46.split(windows ? /[\\/]/ : "/");
28855
+ exports2.basename = (path47, { windows } = {}) => {
28856
+ const segs = path47.split(windows ? /[\\/]/ : "/");
28830
28857
  const last = segs[segs.length - 1];
28831
28858
  if (last === "") {
28832
28859
  return segs[segs.length - 2];
@@ -32463,7 +32490,8 @@ function buildLayoutPaths(root) {
32463
32490
  categoriesLocalFile: import_node_path19.default.join(root, "categories.local.json"),
32464
32491
  claudeShimFile: import_node_path19.default.join(root, "claude-shim.json"),
32465
32492
  headroomDir: import_node_path19.default.join(root, "headroom"),
32466
- headroomStateFile: import_node_path19.default.join(root, "headroom", `state.v${String(HEADROOM_STATE_SCHEMA_VERSION)}.json`),
32493
+ headroomStateFile: import_node_path19.default.join(root, "headroom", "state.json"),
32494
+ headroomLegacyStateFile: import_node_path19.default.join(root, "headroom", "state.v2.json"),
32467
32495
  headroomSocketDir: import_node_path19.default.join(root, "headroom", "run"),
32468
32496
  headroomLockFile: import_node_path19.default.join(root, "headroom", "start.lock"),
32469
32497
  headroomSessionsDir: import_node_path19.default.join(root, "headroom", "sessions"),
@@ -32497,7 +32525,6 @@ var init_paths = __esm({
32497
32525
  import_node_fs7 = __toESM(require("node:fs"), 1);
32498
32526
  import_node_os3 = __toESM(require("node:os"), 1);
32499
32527
  import_node_path19 = __toESM(require("node:path"), 1);
32500
- init_state();
32501
32528
  init_legacy();
32502
32529
  }
32503
32530
  });
@@ -32852,7 +32879,7 @@ var init_package = __esm({
32852
32879
  "package.json"() {
32853
32880
  package_default = {
32854
32881
  name: "agent-shim",
32855
- version: "8.43.0",
32882
+ version: "9.0.0",
32856
32883
  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.",
32857
32884
  license: "MIT",
32858
32885
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -33276,11 +33303,11 @@ function identifyRequest(headers) {
33276
33303
  function directOrigin(port) {
33277
33304
  return `http://127.0.0.1:${String(port)}`;
33278
33305
  }
33279
- function parseProviderPath(path46) {
33280
- if (!path46.startsWith(PROVIDER_PATH_PREFIX)) {
33306
+ function parseProviderPath(path47) {
33307
+ if (!path47.startsWith(PROVIDER_PATH_PREFIX)) {
33281
33308
  return void 0;
33282
33309
  }
33283
- const tail = path46.slice(PROVIDER_PATH_PREFIX.length);
33310
+ const tail = path47.slice(PROVIDER_PATH_PREFIX.length);
33284
33311
  const slash = tail.indexOf("/");
33285
33312
  if (slash <= 0) {
33286
33313
  return void 0;
@@ -33721,9 +33748,9 @@ function decoderFor(encoding) {
33721
33748
  return void 0;
33722
33749
  }
33723
33750
  }
33724
- function destinationOf(path46) {
33725
- const scoped = parseProviderPath(path46);
33726
- return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path46 } : { provider: scoped.provider, endpoint: scoped.rest };
33751
+ function destinationOf(path47) {
33752
+ const scoped = parseProviderPath(path47);
33753
+ return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path47 } : { provider: scoped.provider, endpoint: scoped.rest };
33727
33754
  }
33728
33755
  function buildRecord(event, context) {
33729
33756
  const { scan } = context;
@@ -36107,14 +36134,14 @@ var require_util2 = __commonJS({
36107
36134
  }
36108
36135
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
36109
36136
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
36110
- let path46 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36137
+ let path47 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36111
36138
  if (origin[origin.length - 1] === "/") {
36112
36139
  origin = origin.slice(0, origin.length - 1);
36113
36140
  }
36114
- if (path46 && path46[0] !== "/") {
36115
- path46 = `/${path46}`;
36141
+ if (path47 && path47[0] !== "/") {
36142
+ path47 = `/${path47}`;
36116
36143
  }
36117
- return new URL(`${origin}${path46}`);
36144
+ return new URL(`${origin}${path47}`);
36118
36145
  }
36119
36146
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
36120
36147
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -36935,9 +36962,9 @@ var require_diagnostics = __commonJS({
36935
36962
  "undici:client:sendHeaders",
36936
36963
  (evt) => {
36937
36964
  const {
36938
- request: { method, path: path46, origin }
36965
+ request: { method, path: path47, origin }
36939
36966
  } = evt;
36940
- debugLog("sending request to %s %s%s", method, origin, path46);
36967
+ debugLog("sending request to %s %s%s", method, origin, path47);
36941
36968
  }
36942
36969
  );
36943
36970
  }
@@ -36955,14 +36982,14 @@ var require_diagnostics = __commonJS({
36955
36982
  "undici:request:headers",
36956
36983
  (evt) => {
36957
36984
  const {
36958
- request: { method, path: path46, origin },
36985
+ request: { method, path: path47, origin },
36959
36986
  response: { statusCode }
36960
36987
  } = evt;
36961
36988
  debugLog(
36962
36989
  "received response to %s %s%s - HTTP %d",
36963
36990
  method,
36964
36991
  origin,
36965
- path46,
36992
+ path47,
36966
36993
  statusCode
36967
36994
  );
36968
36995
  }
@@ -36971,23 +36998,23 @@ var require_diagnostics = __commonJS({
36971
36998
  "undici:request:trailers",
36972
36999
  (evt) => {
36973
37000
  const {
36974
- request: { method, path: path46, origin }
37001
+ request: { method, path: path47, origin }
36975
37002
  } = evt;
36976
- debugLog("trailers received from %s %s%s", method, origin, path46);
37003
+ debugLog("trailers received from %s %s%s", method, origin, path47);
36977
37004
  }
36978
37005
  );
36979
37006
  diagnosticsChannel.subscribe(
36980
37007
  "undici:request:error",
36981
37008
  (evt) => {
36982
37009
  const {
36983
- request: { method, path: path46, origin },
37010
+ request: { method, path: path47, origin },
36984
37011
  error: error62
36985
37012
  } = evt;
36986
37013
  debugLog(
36987
37014
  "request to %s %s%s errored - %s",
36988
37015
  method,
36989
37016
  origin,
36990
- path46,
37017
+ path47,
36991
37018
  error62.message
36992
37019
  );
36993
37020
  }
@@ -37102,7 +37129,7 @@ var require_request = __commonJS({
37102
37129
  var kHandler = /* @__PURE__ */ Symbol("handler");
37103
37130
  var Request2 = class {
37104
37131
  constructor(origin, {
37105
- path: path46,
37132
+ path: path47,
37106
37133
  method,
37107
37134
  body,
37108
37135
  headers,
@@ -37119,11 +37146,11 @@ var require_request = __commonJS({
37119
37146
  maxRedirections,
37120
37147
  typeOfService
37121
37148
  }, handler) {
37122
- if (typeof path46 !== "string") {
37149
+ if (typeof path47 !== "string") {
37123
37150
  throw new InvalidArgumentError2("path must be a string");
37124
- } else if (path46[0] !== "/" && !(path46.startsWith("http://") || path46.startsWith("https://")) && method !== "CONNECT") {
37151
+ } else if (path47[0] !== "/" && !(path47.startsWith("http://") || path47.startsWith("https://")) && method !== "CONNECT") {
37125
37152
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
37126
- } else if (invalidPathRegex.test(path46)) {
37153
+ } else if (invalidPathRegex.test(path47)) {
37127
37154
  throw new InvalidArgumentError2("invalid request path");
37128
37155
  }
37129
37156
  if (typeof method !== "string") {
@@ -37198,7 +37225,7 @@ var require_request = __commonJS({
37198
37225
  this.completed = false;
37199
37226
  this.aborted = false;
37200
37227
  this.upgrade = upgrade || null;
37201
- this.path = query ? serializePathWithQuery(path46, query) : path46;
37228
+ this.path = query ? serializePathWithQuery(path47, query) : path47;
37202
37229
  this.origin = origin;
37203
37230
  this.protocol = getProtocolFromUrlString(origin);
37204
37231
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -42380,7 +42407,7 @@ var require_client_h1 = __commonJS({
42380
42407
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
42381
42408
  }
42382
42409
  function writeH1(client, request7) {
42383
- const { method, path: path46, host, upgrade, blocking, reset } = request7;
42410
+ const { method, path: path47, host, upgrade, blocking, reset } = request7;
42384
42411
  let { body, headers, contentLength } = request7;
42385
42412
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
42386
42413
  if (util.isFormDataLike(body)) {
@@ -42458,7 +42485,7 @@ var require_client_h1 = __commonJS({
42458
42485
  if (socket.setTypeOfService) {
42459
42486
  socket.setTypeOfService(request7.typeOfService);
42460
42487
  }
42461
- let header = `${method} ${path46} HTTP/1.1\r
42488
+ let header = `${method} ${path47} HTTP/1.1\r
42462
42489
  `;
42463
42490
  if (typeof host === "string") {
42464
42491
  header += `host: ${host}\r
@@ -43137,7 +43164,7 @@ var require_client_h2 = __commonJS({
43137
43164
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
43138
43165
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
43139
43166
  const session = client[kHTTP2Session];
43140
- const { method, path: path46, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43167
+ const { method, path: path47, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43141
43168
  let { body } = request7;
43142
43169
  if (upgrade != null && upgrade !== "websocket") {
43143
43170
  util.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -43206,7 +43233,7 @@ var require_client_h2 = __commonJS({
43206
43233
  }
43207
43234
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
43208
43235
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
43209
- headers[HTTP2_HEADER_PATH] = path46;
43236
+ headers[HTTP2_HEADER_PATH] = path47;
43210
43237
  if (protocol === "ws:" || protocol === "wss:") {
43211
43238
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
43212
43239
  } else {
@@ -43248,7 +43275,7 @@ var require_client_h2 = __commonJS({
43248
43275
  stream.setTimeout(headersTimeout);
43249
43276
  return true;
43250
43277
  }
43251
- headers[HTTP2_HEADER_PATH] = path46;
43278
+ headers[HTTP2_HEADER_PATH] = path47;
43252
43279
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
43253
43280
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
43254
43281
  if (body && typeof body.read === "function") {
@@ -45600,10 +45627,10 @@ var require_proxy_agent = __commonJS({
45600
45627
  };
45601
45628
  const {
45602
45629
  origin,
45603
- path: path46 = "/",
45630
+ path: path47 = "/",
45604
45631
  headers = {}
45605
45632
  } = opts;
45606
- opts.path = origin + path46;
45633
+ opts.path = origin + path47;
45607
45634
  if (!("host" in headers) && !("Host" in headers)) {
45608
45635
  const { host } = new URL(origin);
45609
45636
  headers.host = host;
@@ -47712,20 +47739,20 @@ var require_mock_utils = __commonJS({
47712
47739
  }
47713
47740
  return normalizedQp;
47714
47741
  }
47715
- function safeUrl(path46) {
47716
- if (typeof path46 !== "string") {
47717
- return path46;
47742
+ function safeUrl(path47) {
47743
+ if (typeof path47 !== "string") {
47744
+ return path47;
47718
47745
  }
47719
- const pathSegments = path46.split("?", 3);
47746
+ const pathSegments = path47.split("?", 3);
47720
47747
  if (pathSegments.length !== 2) {
47721
- return path46;
47748
+ return path47;
47722
47749
  }
47723
47750
  const qp2 = new URLSearchParams(pathSegments.pop());
47724
47751
  qp2.sort();
47725
47752
  return [...pathSegments, qp2.toString()].join("?");
47726
47753
  }
47727
- function matchKey(mockDispatch2, { path: path46, method, body, headers }) {
47728
- const pathMatch = matchValue(mockDispatch2.path, path46);
47754
+ function matchKey(mockDispatch2, { path: path47, method, body, headers }) {
47755
+ const pathMatch = matchValue(mockDispatch2.path, path47);
47729
47756
  const methodMatch = matchValue(mockDispatch2.method, method);
47730
47757
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
47731
47758
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -47750,8 +47777,8 @@ var require_mock_utils = __commonJS({
47750
47777
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
47751
47778
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
47752
47779
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
47753
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path46, ignoreTrailingSlash }) => {
47754
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path46)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path46), resolvedPath);
47780
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path47, ignoreTrailingSlash }) => {
47781
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path47)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path47), resolvedPath);
47755
47782
  });
47756
47783
  if (matchedMockDispatches.length === 0) {
47757
47784
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -47790,19 +47817,19 @@ var require_mock_utils = __commonJS({
47790
47817
  mockDispatches.splice(index, 1);
47791
47818
  }
47792
47819
  }
47793
- function removeTrailingSlash(path46) {
47794
- while (path46.endsWith("/")) {
47795
- path46 = path46.slice(0, -1);
47820
+ function removeTrailingSlash(path47) {
47821
+ while (path47.endsWith("/")) {
47822
+ path47 = path47.slice(0, -1);
47796
47823
  }
47797
- if (path46.length === 0) {
47798
- path46 = "/";
47824
+ if (path47.length === 0) {
47825
+ path47 = "/";
47799
47826
  }
47800
- return path46;
47827
+ return path47;
47801
47828
  }
47802
47829
  function buildKey(opts) {
47803
- const { path: path46, method, body, headers, query } = opts;
47830
+ const { path: path47, method, body, headers, query } = opts;
47804
47831
  return {
47805
- path: path46,
47832
+ path: path47,
47806
47833
  method,
47807
47834
  body,
47808
47835
  headers,
@@ -48492,10 +48519,10 @@ var require_pending_interceptors_formatter = __commonJS({
48492
48519
  }
48493
48520
  format(pendingInterceptors) {
48494
48521
  const withPrettyHeaders = pendingInterceptors.map(
48495
- ({ method, path: path46, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48522
+ ({ method, path: path47, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48496
48523
  Method: method,
48497
48524
  Origin: origin,
48498
- Path: path46,
48525
+ Path: path47,
48499
48526
  "Status code": statusCode,
48500
48527
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
48501
48528
  Invocations: timesInvoked,
@@ -48577,9 +48604,9 @@ var require_mock_agent = __commonJS({
48577
48604
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
48578
48605
  const dispatchOpts = { ...opts };
48579
48606
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
48580
- const [path46, searchParams] = dispatchOpts.path.split("?");
48607
+ const [path47, searchParams] = dispatchOpts.path.split("?");
48581
48608
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
48582
- dispatchOpts.path = `${path46}?${normalizedSearchParams}`;
48609
+ dispatchOpts.path = `${path47}?${normalizedSearchParams}`;
48583
48610
  }
48584
48611
  return this[kAgent].dispatch(dispatchOpts, handler);
48585
48612
  }
@@ -48980,12 +49007,12 @@ var require_snapshot_recorder = __commonJS({
48980
49007
  * @return {Promise<void>} - Resolves when snapshots are loaded
48981
49008
  */
48982
49009
  async loadSnapshots(filePath) {
48983
- const path46 = filePath || this.#snapshotPath;
48984
- if (!path46) {
49010
+ const path47 = filePath || this.#snapshotPath;
49011
+ if (!path47) {
48985
49012
  throw new InvalidArgumentError2("Snapshot path is required");
48986
49013
  }
48987
49014
  try {
48988
- const data = await readFile(resolve2(path46), "utf8");
49015
+ const data = await readFile(resolve2(path47), "utf8");
48989
49016
  const parsed = JSON.parse(data);
48990
49017
  if (Array.isArray(parsed)) {
48991
49018
  this.#snapshots.clear();
@@ -48999,7 +49026,7 @@ var require_snapshot_recorder = __commonJS({
48999
49026
  if (error62.code === "ENOENT") {
49000
49027
  this.#snapshots.clear();
49001
49028
  } else {
49002
- throw new UndiciError(`Failed to load snapshots from ${path46}`, { cause: error62 });
49029
+ throw new UndiciError(`Failed to load snapshots from ${path47}`, { cause: error62 });
49003
49030
  }
49004
49031
  }
49005
49032
  }
@@ -49010,11 +49037,11 @@ var require_snapshot_recorder = __commonJS({
49010
49037
  * @returns {Promise<void>} - Resolves when snapshots are saved
49011
49038
  */
49012
49039
  async saveSnapshots(filePath) {
49013
- const path46 = filePath || this.#snapshotPath;
49014
- if (!path46) {
49040
+ const path47 = filePath || this.#snapshotPath;
49041
+ if (!path47) {
49015
49042
  throw new InvalidArgumentError2("Snapshot path is required");
49016
49043
  }
49017
- const resolvedPath = resolve2(path46);
49044
+ const resolvedPath = resolve2(path47);
49018
49045
  await mkdir(dirname3(resolvedPath), { recursive: true });
49019
49046
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
49020
49047
  hash: hash2,
@@ -49646,15 +49673,15 @@ var require_redirect_handler = __commonJS({
49646
49673
  return;
49647
49674
  }
49648
49675
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
49649
- const path46 = search ? `${pathname}${search}` : pathname;
49650
- const redirectUrlString = `${origin}${path46}`;
49676
+ const path47 = search ? `${pathname}${search}` : pathname;
49677
+ const redirectUrlString = `${origin}${path47}`;
49651
49678
  for (const historyUrl of this.history) {
49652
49679
  if (historyUrl.toString() === redirectUrlString) {
49653
49680
  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.`);
49654
49681
  }
49655
49682
  }
49656
49683
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
49657
- this.opts.path = path46;
49684
+ this.opts.path = path47;
49658
49685
  this.opts.origin = origin;
49659
49686
  this.opts.query = null;
49660
49687
  }
@@ -51414,10 +51441,10 @@ var require_cache_handler = __commonJS({
51414
51441
  }
51415
51442
  return locationUrl.pathname + locationUrl.search;
51416
51443
  }
51417
- function deleteCachedUri(store, cacheKey, path46) {
51444
+ function deleteCachedUri(store, cacheKey, path47) {
51418
51445
  deleteCachedValue(store, {
51419
51446
  ...cacheKey,
51420
- path: path46
51447
+ path: path47
51421
51448
  });
51422
51449
  for (let i10 = 0; i10 < util.safeHTTPMethods.length; i10++) {
51423
51450
  const method = util.safeHTTPMethods[i10];
@@ -51425,7 +51452,7 @@ var require_cache_handler = __commonJS({
51425
51452
  deleteCachedValue(store, {
51426
51453
  ...cacheKey,
51427
51454
  method,
51428
- path: path46
51455
+ path: path47
51429
51456
  });
51430
51457
  }
51431
51458
  }
@@ -51436,9 +51463,9 @@ var require_cache_handler = __commonJS({
51436
51463
  }
51437
51464
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
51438
51465
  for (let i10 = 0; i10 < values.length; i10++) {
51439
- const path46 = getSameOriginPath(cacheKey, values[i10]);
51440
- if (path46 !== void 0) {
51441
- deleteCachedUri(store, cacheKey, path46);
51466
+ const path47 = getSameOriginPath(cacheKey, values[i10]);
51467
+ if (path47 !== void 0) {
51468
+ deleteCachedUri(store, cacheKey, path47);
51442
51469
  }
51443
51470
  }
51444
51471
  }
@@ -56438,11 +56465,11 @@ var require_fetch = __commonJS({
56438
56465
  function dispatch({ body }) {
56439
56466
  const url2 = requestCurrentURL(request7);
56440
56467
  const agent = fetchParams.controller.dispatcher;
56441
- const path46 = url2.pathname + url2.search;
56468
+ const path47 = url2.pathname + url2.search;
56442
56469
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
56443
56470
  return new Promise((resolve2, reject) => agent.dispatch(
56444
56471
  {
56445
- path: hasTrailingQuestionMark ? `${path46}?` : path46,
56472
+ path: hasTrailingQuestionMark ? `${path47}?` : path47,
56446
56473
  origin: url2.origin,
56447
56474
  method: request7.method,
56448
56475
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -57389,9 +57416,9 @@ var require_util5 = __commonJS({
57389
57416
  }
57390
57417
  }
57391
57418
  }
57392
- function validateCookiePath(path46) {
57393
- for (let i10 = 0; i10 < path46.length; ++i10) {
57394
- const code = path46.charCodeAt(i10);
57419
+ function validateCookiePath(path47) {
57420
+ for (let i10 = 0; i10 < path47.length; ++i10) {
57421
+ const code = path47.charCodeAt(i10);
57395
57422
  if (code < 32 || // exclude CTLs (0-31)
57396
57423
  code > 126 || // exclude DEL and non-ascii
57397
57424
  code === 59) {
@@ -60739,11 +60766,11 @@ var require_undici = __commonJS({
60739
60766
  if (typeof opts.path !== "string") {
60740
60767
  throw new InvalidArgumentError2("invalid opts.path");
60741
60768
  }
60742
- let path46 = opts.path;
60769
+ let path47 = opts.path;
60743
60770
  if (!opts.path.startsWith("/")) {
60744
- path46 = `/${path46}`;
60771
+ path47 = `/${path47}`;
60745
60772
  }
60746
- url2 = new URL(util.parseOrigin(url2).origin + path46);
60773
+ url2 = new URL(util.parseOrigin(url2).origin + path47);
60747
60774
  } else {
60748
60775
  if (!opts) {
60749
60776
  opts = typeof url2 === "object" ? url2 : {};
@@ -96322,7 +96349,7 @@ var init_realAnthropicUsageProbe = __esm({
96322
96349
  });
96323
96350
 
96324
96351
  // src/cli.ts
96325
- var import_node_path45 = __toESM(require("node:path"), 1);
96352
+ var import_node_path46 = __toESM(require("node:path"), 1);
96326
96353
 
96327
96354
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
96328
96355
  var CommanderError = class extends Error {
@@ -99435,9 +99462,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
99435
99462
  * @param {string} [path]
99436
99463
  * @return {(string|null|Command)}
99437
99464
  */
99438
- executableDir(path46) {
99439
- if (path46 === void 0) return this._executableDir;
99440
- this._executableDir = path46;
99465
+ executableDir(path47) {
99466
+ if (path47 === void 0) return this._executableDir;
99467
+ this._executableDir = path47;
99441
99468
  return this;
99442
99469
  }
99443
99470
  /**
@@ -101044,19 +101071,19 @@ function writePools(paths, pools) {
101044
101071
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
101045
101072
  }
101046
101073
  function poolCycleOf(pools, name) {
101047
- const walk = (current, path46) => {
101074
+ const walk = (current, path47) => {
101048
101075
  for (const entry of pools[current]?.identities ?? []) {
101049
101076
  const nested = poolNameOf(poolMemberIdentity(entry));
101050
101077
  if (nested === void 0) {
101051
101078
  continue;
101052
101079
  }
101053
101080
  if (nested === name) {
101054
- return [...path46, nested];
101081
+ return [...path47, nested];
101055
101082
  }
101056
- if (path46.includes(nested)) {
101083
+ if (path47.includes(nested)) {
101057
101084
  continue;
101058
101085
  }
101059
- const found = walk(nested, [...path46, nested]);
101086
+ const found = walk(nested, [...path47, nested]);
101060
101087
  if (found !== void 0) {
101061
101088
  return found;
101062
101089
  }
@@ -103871,7 +103898,7 @@ function registerCodexCommand(program2, deps) {
103871
103898
 
103872
103899
  // src/frontdoor/commands.ts
103873
103900
  var import_node_crypto20 = require("node:crypto");
103874
- var import_node_path41 = __toESM(require("node:path"), 1);
103901
+ var import_node_path42 = __toESM(require("node:path"), 1);
103875
103902
  var import_node_fs15 = __toESM(require("node:fs"), 1);
103876
103903
  init_commandDeps();
103877
103904
  init_schema();
@@ -104465,12 +104492,22 @@ init_capability();
104465
104492
  init_route();
104466
104493
 
104467
104494
  // src/frontdoor/supervisor.ts
104495
+ var import_node_path37 = __toESM(require("node:path"), 1);
104468
104496
  init_state2();
104497
+ function watchedInstallEntry(resolvedOwnExecutablePath, siblingExists) {
104498
+ const parsed = import_node_path37.default.parse(resolvedOwnExecutablePath);
104499
+ if (parsed.name === "agent-shim") {
104500
+ return resolvedOwnExecutablePath;
104501
+ }
104502
+ const sibling = import_node_path37.default.join(parsed.dir, `agent-shim${parsed.ext}`);
104503
+ return siblingExists(sibling) ? sibling : resolvedOwnExecutablePath;
104504
+ }
104469
104505
  var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
104470
104506
  var FRONTDOOR_POLL_MS = 1e3;
104471
104507
  var MS_PER_MINUTE2 = 6e4;
104472
104508
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
104473
104509
  const { fs: fs21, paths } = ports;
104510
+ const servingBinary = ports.statOwnExecutable();
104474
104511
  const previous = readFrontDoorState(fs21, paths.frontdoorStateFile);
104475
104512
  let lastPort = previous?.lastPort;
104476
104513
  let lastConnectPort = previous?.lastConnectPort;
@@ -104533,6 +104570,18 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
104533
104570
  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)}`);
104534
104571
  let idleSince;
104535
104572
  let ticks = 0;
104573
+ const binaryReplaced = () => {
104574
+ const current = ports.statOwnExecutable();
104575
+ return current !== void 0 && servingBinary !== void 0 && (current.dev !== servingBinary.dev || current.ino !== servingBinary.ino || current.size !== servingBinary.size || current.mtimeMs !== servingBinary.mtimeMs);
104576
+ };
104577
+ const shutdown = async () => {
104578
+ await direct.close();
104579
+ await connect3.close();
104580
+ await http8.close();
104581
+ ports.closeRcStreamHub();
104582
+ writeFrontDoorState(fs21, paths.frontdoorStateFile, sticky());
104583
+ return 0;
104584
+ };
104536
104585
  for (; ; ) {
104537
104586
  if (options.tickLimit !== void 0 && ticks >= options.tickLimit) {
104538
104587
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
@@ -104544,16 +104593,16 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
104544
104593
  ports.checkQuotaExpiry();
104545
104594
  const prunedPids = new Set(pruned);
104546
104595
  if (listed.filter((session) => !prunedPids.has(session.pid)).length === 0) {
104596
+ if (ticks > 1 && binaryReplaced()) {
104597
+ ports.log("agent-shim frontdoor supervisor: the installed binary changed and no sessions are live; turning the door over for the next launch");
104598
+ ports.doorHealth.binaryTurnover();
104599
+ return await shutdown();
104600
+ }
104547
104601
  idleSince ??= ports.now();
104548
104602
  if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE2) {
104549
104603
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
104550
104604
  ports.doorHealth.idleShutdown();
104551
- await direct.close();
104552
- await connect3.close();
104553
- await http8.close();
104554
- ports.closeRcStreamHub();
104555
- writeFrontDoorState(fs21, paths.frontdoorStateFile, sticky());
104556
- return 0;
104605
+ return await shutdown();
104557
104606
  }
104558
104607
  } else {
104559
104608
  idleSince = void 0;
@@ -104605,8 +104654,8 @@ function parseConnectTarget(authority) {
104605
104654
  }
104606
104655
  return { host, port };
104607
104656
  }
104608
- function servedByPipeline(path46) {
104609
- return path46?.startsWith(ROUTED_PATH_PREFIX) === true;
104657
+ function servedByPipeline(path47) {
104658
+ return path47?.startsWith(ROUTED_PATH_PREFIX) === true;
104610
104659
  }
104611
104660
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
104612
104661
  "connection",
@@ -105125,11 +105174,11 @@ function createRcSessionTracker(deps) {
105125
105174
  };
105126
105175
  const observeExchange = (request7) => {
105127
105176
  const method = (request7.method ?? "").toUpperCase();
105128
- const path46 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
105129
- if (!path46.startsWith(RC_SESSIONS_PATH_PREFIX)) {
105177
+ const path47 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
105178
+ if (!path47.startsWith(RC_SESSIONS_PATH_PREFIX)) {
105130
105179
  return void 0;
105131
105180
  }
105132
- const tail = path46.slice(RC_SESSIONS_PATH_PREFIX.length);
105181
+ const tail = path47.slice(RC_SESSIONS_PATH_PREFIX.length);
105133
105182
  const facts = {
105134
105183
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
105135
105184
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -105490,8 +105539,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
105490
105539
  function isRcReadFileEncoding(value2) {
105491
105540
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value2);
105492
105541
  }
105493
- function buildRcReadFilePayload(requestId, path46, options) {
105494
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path46, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
105542
+ function buildRcReadFilePayload(requestId, path47, options) {
105543
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path47, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
105495
105544
  }
105496
105545
  function buildRcFileSuggestionsPayload(requestId, query) {
105497
105546
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -105593,15 +105642,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
105593
105642
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
105594
105643
  return result.ok ? { ...result, requestId } : result;
105595
105644
  }
105596
- async function readRcSessionFile(deps, sessionId, path46, options) {
105597
- if (path46 === "") {
105645
+ async function readRcSessionFile(deps, sessionId, path47, options) {
105646
+ if (path47 === "") {
105598
105647
  return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none" };
105599
105648
  }
105600
105649
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
105601
105650
  return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing" };
105602
105651
  }
105603
105652
  const requestId = deps.newUuid();
105604
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path46, options), `read ${path46} from session ${sessionId}`);
105653
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path47, options), `read ${path47} from session ${sessionId}`);
105605
105654
  return result.ok ? { ...result, requestId } : result;
105606
105655
  }
105607
105656
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -105772,11 +105821,11 @@ function createRcControlHandler(deps) {
105772
105821
  path: "read-file",
105773
105822
  read: (body) => {
105774
105823
  const session = bodyString(body, "session");
105775
- const path46 = bodyString(body, "path");
105824
+ const path47 = bodyString(body, "path");
105776
105825
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
105777
105826
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
105778
- const refused2 = session === void 0 || path46 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
105779
- return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path46, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
105827
+ const refused2 = session === void 0 || path47 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
105828
+ return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path47, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
105780
105829
  }
105781
105830
  },
105782
105831
  {
@@ -106086,9 +106135,9 @@ function requestIdOfBody(body) {
106086
106135
  }
106087
106136
  function frontDoorRcControl(transport, token) {
106088
106137
  const headers = { authorization: `Bearer ${token}` };
106089
- const listAnswerOf = async (path46, what) => {
106138
+ const listAnswerOf = async (path47, what) => {
106090
106139
  try {
106091
- return await transport.request({ method: "GET", path: path46, headers });
106140
+ return await transport.request({ method: "GET", path: path47, headers });
106092
106141
  } catch (error62) {
106093
106142
  throw new Error(`${what}: could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}`, { cause: error62 });
106094
106143
  }
@@ -106160,10 +106209,10 @@ function frontDoorRcControl(transport, token) {
106160
106209
  }
106161
106210
  return pending;
106162
106211
  };
106163
- const writeOf = async (path46, body, describeFailure) => {
106212
+ const writeOf = async (path47, body, describeFailure) => {
106164
106213
  let answer;
106165
106214
  try {
106166
- answer = await transport.request({ method: "POST", path: path46, headers: { ...headers, "content-type": "application/json" }, body });
106215
+ answer = await transport.request({ method: "POST", path: path47, headers: { ...headers, "content-type": "application/json" }, body });
106167
106216
  } catch (error62) {
106168
106217
  return { ok: false, message: `could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}` };
106169
106218
  }
@@ -106194,10 +106243,10 @@ function frontDoorRcControl(transport, token) {
106194
106243
  endSession: async (sessionId, reason) => await writeOf(`${CONTROL_PATH_PREFIX}/end-session`, JSON.stringify({ session: sessionId, ...reason === void 0 ? {} : { reason } }), (status, message) => `ending ${sessionId} failed (HTTP ${String(status)}): ${message}`),
106195
106244
  getUsage: async (sessionId, skipBehaviors) => await writeOf(`${CONTROL_PATH_PREFIX}/get-usage`, JSON.stringify({ session: sessionId, ...skipBehaviors === void 0 ? {} : { skipBehaviors } }), (status, message) => `requesting the usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
106196
106245
  getContextUsage: async (sessionId, detail) => await writeOf(`${CONTROL_PATH_PREFIX}/get-context-usage`, JSON.stringify({ session: sessionId, ...detail === void 0 ? {} : { detail } }), (status, message) => `requesting the context usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
106197
- readFile: async (sessionId, path46, options) => await writeOf(
106246
+ readFile: async (sessionId, path47, options) => await writeOf(
106198
106247
  `${CONTROL_PATH_PREFIX}/read-file`,
106199
- JSON.stringify({ session: sessionId, path: path46, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
106200
- (status, message) => `reading ${path46} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
106248
+ JSON.stringify({ session: sessionId, path: path47, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
106249
+ (status, message) => `reading ${path47} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
106201
106250
  ),
106202
106251
  fileSuggestions: async (sessionId, query) => await writeOf(`${CONTROL_PATH_PREFIX}/file-suggestions`, JSON.stringify({ session: sessionId, query }), (status, message) => `requesting file suggestions from ${sessionId} failed (HTTP ${String(status)}): ${message}`),
106203
106252
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -106487,12 +106536,12 @@ function tlsFacts(options) {
106487
106536
  }
106488
106537
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
106489
106538
  const agent = new ExemptTlsAgent();
106490
- const post = async (path46, headers, body) => await new Promise((resolve2, reject) => {
106539
+ const post = async (path47, headers, body) => await new Promise((resolve2, reject) => {
106491
106540
  const options = {
106492
106541
  host: target.host,
106493
106542
  port: target.port,
106494
106543
  method: "POST",
106495
- path: path46,
106544
+ path: path47,
106496
106545
  // 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.
106497
106546
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
106498
106547
  agent
@@ -106557,12 +106606,12 @@ function lateRcStreamDial(resolve2) {
106557
106606
  }
106558
106607
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
106559
106608
  const agent = new ExemptTlsAgent();
106560
- const request7 = async (method, path46, headers, body, signal) => await new Promise((resolve2, reject) => {
106609
+ const request7 = async (method, path47, headers, body, signal) => await new Promise((resolve2, reject) => {
106561
106610
  const options = {
106562
106611
  host: target.host,
106563
106612
  port: target.port,
106564
106613
  method,
106565
- path: path46,
106614
+ path: path47,
106566
106615
  // 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.
106567
106616
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
106568
106617
  agent,
@@ -106604,9 +106653,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
106604
106653
  return { status, body: await readAll(response) };
106605
106654
  },
106606
106655
  openStream: async (sessionId, headers, resume, signal) => {
106607
- 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)}`;
106656
+ const path47 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
106608
106657
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
106609
- const { status, response } = await request7("GET", path46, streamHeaders, void 0, signal);
106658
+ const { status, response } = await request7("GET", path47, streamHeaders, void 0, signal);
106610
106659
  if (!isSuccessful2(status)) {
106611
106660
  await readAll(response);
106612
106661
  return { status, chunks: NO_CHUNKS };
@@ -106822,7 +106871,7 @@ init_claudeShim();
106822
106871
  init_store();
106823
106872
  init_realPorts();
106824
106873
  var import_node_fs14 = __toESM(require("node:fs"), 1);
106825
- var import_node_path37 = __toESM(require("node:path"), 1);
106874
+ var import_node_path38 = __toESM(require("node:path"), 1);
106826
106875
  init_load();
106827
106876
  init_schema();
106828
106877
  init_credential();
@@ -106875,8 +106924,18 @@ function validateJson(schema, input2) {
106875
106924
  }
106876
106925
  return { ok: true, data: result.data };
106877
106926
  }
106927
+ function tcpPortEraRecord(raw) {
106928
+ let parsed;
106929
+ try {
106930
+ parsed = JSON.parse(raw);
106931
+ } catch {
106932
+ return false;
106933
+ }
106934
+ const has = (key) => typeof parsed === "object" && parsed !== null && key in parsed;
106935
+ return (has("port") || has("lastPort")) && !has("socketPath");
106936
+ }
106878
106937
  function pushPathResolution(push, resolution) {
106879
- const ownDir = import_node_path37.default.dirname(resolution.ownExecutablePath);
106938
+ const ownDir = import_node_path38.default.dirname(resolution.ownExecutablePath);
106880
106939
  switch (resolution.agentShim.status) {
106881
106940
  case "ok":
106882
106941
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -106975,14 +107034,14 @@ function pushProvider(push, entry, cacheEnv, signIn) {
106975
107034
  }
106976
107035
  function pushLegacyName(push, params) {
106977
107036
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
106978
- if (legacyVariables.length === 0 && import_node_path37.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
107037
+ if (legacyVariables.length === 0 && import_node_path38.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
106979
107038
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
106980
107039
  return;
106981
107040
  }
106982
107041
  for (const name of legacyVariables) {
106983
107042
  push("legacy-name", "warn", `${name} is the former name of ${name.replace(LEGACY_ENV_PREFIX, ENV_PREFIX)}. Rename it; the old name still works but is only a fallback.`, name);
106984
107043
  }
106985
- if (import_node_path37.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
107044
+ if (import_node_path38.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
106986
107045
  push(
106987
107046
  "legacy-name",
106988
107047
  "warn",
@@ -107184,6 +107243,8 @@ function runDoctor(params) {
107184
107243
  }
107185
107244
  if (params.headroom.state.raw === void 0) {
107186
107245
  push("headroom", "pass", "No headroom daemon has ever run; nothing to check.");
107246
+ } else if (tcpPortEraRecord(params.headroom.state.raw)) {
107247
+ push("headroom", "pass", `${params.headroom.state.path} holds a previous release's TCP-port state record; the next launch through headroom claims over it.`);
107187
107248
  } else {
107188
107249
  const validated2 = validateJson(HeadroomStateSchema, params.headroom.state);
107189
107250
  if (!validated2.ok) {
@@ -107322,18 +107383,18 @@ function collectDoctorReport(params) {
107322
107383
  const { paths } = params;
107323
107384
  const identityNames = import_node_fs14.default.existsSync(paths.identitiesDir) ? import_node_fs14.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
107324
107385
  const identities = identityNames.map((name) => {
107325
- const farmRoot = import_node_path37.default.join(paths.identitiesDir, name);
107326
- const identityPath = import_node_path37.default.join(farmRoot, "identity.json");
107386
+ const farmRoot = import_node_path38.default.join(paths.identitiesDir, name);
107387
+ const identityPath = import_node_path38.default.join(farmRoot, "identity.json");
107327
107388
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
107328
107389
  });
107329
107390
  const profileNames = import_node_fs14.default.existsSync(paths.configProfilesDir) ? import_node_fs14.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
107330
107391
  const configProfiles = profileNames.map((name) => {
107331
- const profilePath = import_node_path37.default.join(paths.configProfilesDir, `${name}.json`);
107392
+ const profilePath = import_node_path38.default.join(paths.configProfilesDir, `${name}.json`);
107332
107393
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
107333
107394
  });
107334
107395
  const providerNames = import_node_fs14.default.existsSync(paths.providersDir) ? import_node_fs14.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
107335
107396
  const providers = providerNames.map((name) => {
107336
- const providerPath = import_node_path37.default.join(paths.providersDir, `${name}.json`);
107397
+ const providerPath = import_node_path38.default.join(paths.providersDir, `${name}.json`);
107337
107398
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
107338
107399
  });
107339
107400
  const ownExecutablePath = realOwnExecutablePath();
@@ -107345,12 +107406,12 @@ function collectDoctorReport(params) {
107345
107406
  binaryDiscovery = { ok: false, message: error62 instanceof Error ? error62.message : String(error62) };
107346
107407
  }
107347
107408
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
107348
- const pathDirs = (params.env.PATH ?? "").split(import_node_path37.default.delimiter).filter((dir) => dir !== "");
107409
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path38.default.delimiter).filter((dir) => dir !== "");
107349
107410
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
107350
107411
  findPathShadow({
107351
107412
  pathDirs,
107352
- targetDir: import_node_path37.default.dirname(shimState.targetPath),
107353
- targetFilename: import_node_path37.default.basename(shimState.targetPath),
107413
+ targetDir: import_node_path38.default.dirname(shimState.targetPath),
107414
+ targetFilename: import_node_path38.default.basename(shimState.targetPath),
107354
107415
  findExecutableInDir
107355
107416
  }),
107356
107417
  shimState.targetPath,
@@ -107376,7 +107437,7 @@ function collectDoctorReport(params) {
107376
107437
  agentShim: refinePathShadow(
107377
107438
  findPathShadow({
107378
107439
  pathDirs,
107379
- targetDir: import_node_path37.default.dirname(ownExecutablePath),
107440
+ targetDir: import_node_path38.default.dirname(ownExecutablePath),
107380
107441
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
107381
107442
  findExecutableInDir
107382
107443
  }),
@@ -107388,7 +107449,12 @@ function collectDoctorReport(params) {
107388
107449
  run: realRunPort,
107389
107450
  platform: process.platform,
107390
107451
  headroom: {
107391
- state: { path: paths.headroomStateFile, raw: realFsPort.readFileUtf8(paths.headroomStateFile) },
107452
+ // Read-only resolution like `headroom status`: the doctor reports whichever record a launch would join, migrating nothing.
107453
+ state: (() => {
107454
+ const resolved = resolveServingHeadroomState(realFarmFs, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, realIsProcessRunning);
107455
+ const statePath = resolved?.path ?? paths.headroomStateFile;
107456
+ return { path: statePath, raw: realFarmFs.readFileUtf8(statePath) };
107457
+ })(),
107392
107458
  isRunning: realIsProcessRunning
107393
107459
  }
107394
107460
  });
@@ -108341,9 +108407,9 @@ function resolveFriendlyClientOptions(options) {
108341
108407
  };
108342
108408
  }
108343
108409
  function createORPCClient(link, options = {}) {
108344
- const path46 = options.path ?? [];
108410
+ const path47 = options.path ?? [];
108345
108411
  const procedureClient = async (...[input2, options2 = {}]) => {
108346
- return await link.call(path46, input2, resolveFriendlyClientOptions(options2));
108412
+ return await link.call(path47, input2, resolveFriendlyClientOptions(options2));
108347
108413
  };
108348
108414
  const recursive2 = new Proxy(procedureClient, {
108349
108415
  get(target, key) {
@@ -108352,7 +108418,7 @@ function createORPCClient(link, options = {}) {
108352
108418
  }
108353
108419
  return createORPCClient(link, {
108354
108420
  ...options,
108355
- path: [...path46, key]
108421
+ path: [...path47, key]
108356
108422
  });
108357
108423
  }
108358
108424
  });
@@ -108549,7 +108615,7 @@ init_middleware();
108549
108615
  init_preflight();
108550
108616
 
108551
108617
  // src/frontdoor/controlSchemas.ts
108552
- var import_node_path38 = __toESM(require("node:path"), 1);
108618
+ var import_node_path39 = __toESM(require("node:path"), 1);
108553
108619
  init_zod();
108554
108620
  init_schema2();
108555
108621
 
@@ -108761,11 +108827,11 @@ var FrontDoorSessionsOutputSchema = external_exports.strictObject({ sessions: ex
108761
108827
  var CheckRunInputSchema = external_exports.strictObject({
108762
108828
  path: external_exports.string().min(1),
108763
108829
  identity: external_exports.string().min(1).optional()
108764
- }).refine((input2) => import_node_path38.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
108830
+ }).refine((input2) => import_node_path39.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
108765
108831
  var PoolPickInputSchema = external_exports.strictObject({
108766
108832
  pool: external_exports.string().min(1),
108767
108833
  path: external_exports.string().min(1)
108768
- }).refine((input2) => import_node_path38.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
108834
+ }).refine((input2) => import_node_path39.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
108769
108835
  var DoctorFindingSchema = external_exports.strictObject({
108770
108836
  section: external_exports.enum(DOCTOR_SECTIONS),
108771
108837
  subject: external_exports.string().optional(),
@@ -109123,19 +109189,19 @@ var StandardLink = class {
109123
109189
  }
109124
109190
  interceptors;
109125
109191
  clientInterceptors;
109126
- call(path46, input2, options) {
109192
+ call(path47, input2, options) {
109127
109193
  return runWithSpan(
109128
- { name: `${ORPC_NAME}.${path46.join("/")}`, signal: options.signal },
109194
+ { name: `${ORPC_NAME}.${path47.join("/")}`, signal: options.signal },
109129
109195
  (span) => {
109130
109196
  span?.setAttribute("rpc.system", ORPC_NAME);
109131
- span?.setAttribute("rpc.method", path46.join("."));
109197
+ span?.setAttribute("rpc.method", path47.join("."));
109132
109198
  if (isAsyncIteratorObject(input2)) {
109133
109199
  input2 = asyncIteratorWithSpan(
109134
109200
  { name: "consume_event_iterator_input", signal: options.signal },
109135
109201
  input2
109136
109202
  );
109137
109203
  }
109138
- return intercept(this.interceptors, { ...options, path: path46, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
109204
+ return intercept(this.interceptors, { ...options, path: path47, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
109139
109205
  const otelConfig = getGlobalOtelConfig();
109140
109206
  let otelContext;
109141
109207
  const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
@@ -109370,8 +109436,8 @@ var StandardRPCJsonSerializer = class {
109370
109436
  return ref.data;
109371
109437
  }
109372
109438
  };
109373
- function toHttpPath(path46) {
109374
- return `/${path46.map(encodeURIComponent).join("/")}`;
109439
+ function toHttpPath(path47) {
109440
+ return `/${path47.map(encodeURIComponent).join("/")}`;
109375
109441
  }
109376
109442
  function toStandardHeaders2(headers) {
109377
109443
  if (typeof headers.forEach === "function") {
@@ -109396,18 +109462,18 @@ var StandardRPCLinkCodec = class {
109396
109462
  fallbackMethod;
109397
109463
  expectedMethod;
109398
109464
  headers;
109399
- async encode(path46, input2, options) {
109400
- let headers = toStandardHeaders2(await value(this.headers, options, path46, input2));
109465
+ async encode(path47, input2, options) {
109466
+ let headers = toStandardHeaders2(await value(this.headers, options, path47, input2));
109401
109467
  if (options.lastEventId !== void 0) {
109402
109468
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
109403
109469
  }
109404
- const expectedMethod = await value(this.expectedMethod, options, path46, input2);
109405
- const baseUrl = await value(this.baseUrl, options, path46, input2);
109470
+ const expectedMethod = await value(this.expectedMethod, options, path47, input2);
109471
+ const baseUrl = await value(this.baseUrl, options, path47, input2);
109406
109472
  const url2 = new URL(baseUrl);
109407
- url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path46)}`;
109473
+ url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path47)}`;
109408
109474
  const serialized = this.serializer.serialize(input2);
109409
109475
  if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
109410
- const maxUrlLength = await value(this.maxUrlLength, options, path46, input2);
109476
+ const maxUrlLength = await value(this.maxUrlLength, options, path47, input2);
109411
109477
  const getUrl = new URL(url2);
109412
109478
  getUrl.searchParams.append("data", stringifyJSON(serialized));
109413
109479
  if (getUrl.toString().length <= maxUrlLength) {
@@ -109881,7 +109947,7 @@ function middlewareOutputFn(output2) {
109881
109947
  function createProcedureClient(lazyableProcedure, ...rest) {
109882
109948
  const options = resolveMaybeOptionalOptions(rest);
109883
109949
  return async (...[input2, callerOptions]) => {
109884
- const path46 = toArray(options.path);
109950
+ const path47 = toArray(options.path);
109885
109951
  const { default: procedure } = await unlazy(lazyableProcedure);
109886
109952
  const clientContext = callerOptions?.context ?? {};
109887
109953
  const context = await value(options.context ?? {}, clientContext);
@@ -109896,7 +109962,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
109896
109962
  const output2 = await runWithSpan(
109897
109963
  { name: "call_procedure", signal: callerOptions?.signal },
109898
109964
  (span) => {
109899
- span?.setAttribute("procedure.path", [...path46]);
109965
+ span?.setAttribute("procedure.path", [...path47]);
109900
109966
  return intercept(
109901
109967
  toArray(options.interceptors),
109902
109968
  {
@@ -109904,7 +109970,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
109904
109970
  input: input2,
109905
109971
  // input only optional when it undefinable so we can safely cast it
109906
109972
  errors,
109907
- path: path46,
109973
+ path: path47,
109908
109974
  procedure,
109909
109975
  signal: callerOptions?.signal,
109910
109976
  lastEventId: callerOptions?.lastEventId
@@ -110026,10 +110092,10 @@ var HIDDEN_ROUTER_CONTRACT_SYMBOL = /* @__PURE__ */ Symbol("ORPC_HIDDEN_ROUTER_C
110026
110092
  function getHiddenRouterContract(router) {
110027
110093
  return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
110028
110094
  }
110029
- function getRouter(router, path46) {
110095
+ function getRouter(router, path47) {
110030
110096
  let current = router;
110031
- for (let i10 = 0; i10 < path46.length; i10++) {
110032
- const segment = path46[i10];
110097
+ for (let i10 = 0; i10 < path47.length; i10++) {
110098
+ const segment = path47[i10];
110033
110099
  if (!current) {
110034
110100
  return void 0;
110035
110101
  }
@@ -110044,7 +110110,7 @@ function getRouter(router, path46) {
110044
110110
  continue;
110045
110111
  }
110046
110112
  const lazied = current;
110047
- const rest = path46.slice(i10);
110113
+ const rest = path47.slice(i10);
110048
110114
  return lazy2(async () => {
110049
110115
  const unwrapped = await unlazy(lazied);
110050
110116
  const next = getRouter(unwrapped.default, rest);
@@ -110521,11 +110587,11 @@ var LinkFetchClient = class {
110521
110587
  this.toFetchRequestOptions = options;
110522
110588
  this.adapterInterceptors = toArray(options.adapterInterceptors);
110523
110589
  }
110524
- async call(standardRequest, options, path46, input2) {
110590
+ async call(standardRequest, options, path47, input2) {
110525
110591
  const request7 = toFetchRequest(standardRequest, this.toFetchRequestOptions);
110526
110592
  const fetchResponse = await intercept(
110527
110593
  this.adapterInterceptors,
110528
- { ...options, request: request7, path: path46, input: input2, init: { redirect: "manual" } },
110594
+ { ...options, request: request7, path: path47, input: input2, init: { redirect: "manual" } },
110529
110595
  ({ request: request22, path: path210, input: input22, init, ...options2 }) => this.fetch(request22, init, options2, path210, input22)
110530
110596
  );
110531
110597
  const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request7.signal });
@@ -110565,8 +110631,8 @@ var StandardBracketNotationSerializer = class {
110565
110631
  }
110566
110632
  const arrayPushStyles = /* @__PURE__ */ new WeakSet();
110567
110633
  const ref = { value: [] };
110568
- for (const [path46, value2] of serialized) {
110569
- const segments = this.parsePath(path46);
110634
+ for (const [path47, value2] of serialized) {
110635
+ const segments = this.parsePath(path47);
110570
110636
  let currentRef = ref;
110571
110637
  let nextSegment = "value";
110572
110638
  segments.forEach((segment, i10) => {
@@ -110638,14 +110704,14 @@ var StandardBracketNotationSerializer = class {
110638
110704
  return `${result}[${segment}]`;
110639
110705
  }, "");
110640
110706
  }
110641
- parsePath(path46) {
110707
+ parsePath(path47) {
110642
110708
  const segments = [];
110643
110709
  let inBrackets = false;
110644
110710
  let currentSegment = "";
110645
110711
  let backslashCount = 0;
110646
- for (let i10 = 0; i10 < path46.length; i10++) {
110647
- const char = path46[i10];
110648
- const nextChar = path46[i10 + 1];
110712
+ for (let i10 = 0; i10 < path47.length; i10++) {
110713
+ const char = path47[i10];
110714
+ const nextChar = path47[i10 + 1];
110649
110715
  if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[") && backslashCount % 2 === 0) {
110650
110716
  if (nextChar === void 0) {
110651
110717
  inBrackets = false;
@@ -110664,7 +110730,7 @@ var StandardBracketNotationSerializer = class {
110664
110730
  backslashCount = 0;
110665
110731
  }
110666
110732
  }
110667
- return inBrackets || segments.length === 0 ? [path46] : segments;
110733
+ return inBrackets || segments.length === 0 ? [path47] : segments;
110668
110734
  }
110669
110735
  };
110670
110736
  function isValidArrayIndex(value2, maxIndex) {
@@ -110732,11 +110798,11 @@ var StandardOpenAPIJsonSerializer = class {
110732
110798
  return [data, hasBlobRef.value];
110733
110799
  }
110734
110800
  };
110735
- function standardizeHTTPPath(path46) {
110736
- return `/${path46.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
110801
+ function standardizeHTTPPath(path47) {
110802
+ return `/${path47.replace(/\/{2,}/g, "/").replace(/^\/|\/$/g, "")}`;
110737
110803
  }
110738
- function getDynamicParams(path46) {
110739
- return path46 ? standardizeHTTPPath(path46).match(/\/\{[^}]+\}/g)?.map((v) => ({
110804
+ function getDynamicParams(path47) {
110805
+ return path47 ? standardizeHTTPPath(path47).match(/\/\{[^}]+\}/g)?.map((v) => ({
110740
110806
  raw: v,
110741
110807
  name: v.match(/\{\+?([^}]+)\}/)[1]
110742
110808
  })) : void 0;
@@ -110767,9 +110833,9 @@ var StandardOpenAPISerializer = class {
110767
110833
  }
110768
110834
  if (options.outputFormat === "URLSearchParams") {
110769
110835
  const params = new URLSearchParams();
110770
- for (const [path46, value2] of this.bracketNotation.serialize(json2)) {
110836
+ for (const [path47, value2] of this.bracketNotation.serialize(json2)) {
110771
110837
  if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") {
110772
- params.append(path46, value2.toString());
110838
+ params.append(path47, value2.toString());
110773
110839
  }
110774
110840
  }
110775
110841
  return params;
@@ -110778,11 +110844,11 @@ var StandardOpenAPISerializer = class {
110778
110844
  return json2;
110779
110845
  }
110780
110846
  const form = new FormData();
110781
- for (const [path46, value2] of this.bracketNotation.serialize(json2)) {
110847
+ for (const [path47, value2] of this.bracketNotation.serialize(json2)) {
110782
110848
  if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean") {
110783
- form.append(path46, value2.toString());
110849
+ form.append(path47, value2.toString());
110784
110850
  } else if (value2 instanceof Blob) {
110785
- form.append(path46, value2);
110851
+ form.append(path47, value2);
110786
110852
  }
110787
110853
  }
110788
110854
  return form;
@@ -111097,8 +111163,8 @@ function isPrimitiveSchema(schema) {
111097
111163
  return false;
111098
111164
  });
111099
111165
  }
111100
- function toOpenAPIPath(path46) {
111101
- return standardizeHTTPPath(path46).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
111166
+ function toOpenAPIPath(path47) {
111167
+ return standardizeHTTPPath(path47).replace(/\/\{\+([^}]+)\}/g, "/{$1}");
111102
111168
  }
111103
111169
  function toOpenAPIMethod(method) {
111104
111170
  return method.toLocaleLowerCase();
@@ -111345,8 +111411,8 @@ var OpenAPIGenerator = class {
111345
111411
  * @see {@link https://orpc.dev/docs/openapi/openapi-specification OpenAPI Specification Docs}
111346
111412
  */
111347
111413
  async generate(router, { customErrorResponseBodySchema, commonSchemas, filter: baseFilter, exclude, ...baseDoc } = {}) {
111348
- const filter = baseFilter ?? (({ contract, path: path46 }) => {
111349
- return !(exclude?.(contract, path46) ?? false);
111414
+ const filter = baseFilter ?? (({ contract, path: path47 }) => {
111415
+ return !(exclude?.(contract, path47) ?? false);
111350
111416
  });
111351
111417
  const doc = {
111352
111418
  ...clone2(baseDoc),
@@ -111362,12 +111428,12 @@ var OpenAPIGenerator = class {
111362
111428
  contracts.push(traverseOptions);
111363
111429
  });
111364
111430
  const errors = [];
111365
- for (const { contract, path: path46 } of contracts) {
111366
- const stringPath = path46.join(".");
111431
+ for (const { contract, path: path47 } of contracts) {
111432
+ const stringPath = path47.join(".");
111367
111433
  try {
111368
111434
  const def = contract["~orpc"];
111369
111435
  const method = toOpenAPIMethod(fallbackContractConfig("defaultMethod", def.route.method));
111370
- const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path46));
111436
+ const httpPath = toOpenAPIPath(def.route.path ?? toHttpPath(path47));
111371
111437
  let operationObjectRef;
111372
111438
  if (def.route.spec !== void 0 && typeof def.route.spec !== "function") {
111373
111439
  operationObjectRef = def.route.spec;
@@ -111839,8 +111905,8 @@ function toAbortSignal(stream) {
111839
111905
  function toStandardUrl(req) {
111840
111906
  const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
111841
111907
  const origin = guard(() => new URL(`${protocol}//${req.headers.host ?? "localhost"}`).origin) ?? `${protocol}//localhost`;
111842
- const path46 = req.originalUrl ?? req.url ?? "/";
111843
- return new URL(`${origin}${path46.startsWith("/") ? "" : "/"}${path46}`);
111908
+ const path47 = req.originalUrl ?? req.url ?? "/";
111909
+ return new URL(`${origin}${path47.startsWith("/") ? "" : "/"}${path47}`);
111844
111910
  }
111845
111911
  function toStandardLazyRequest(req, res) {
111846
111912
  const signal = toAbortSignal(res);
@@ -112039,8 +112105,8 @@ var StandardRPCMatcher = class {
112039
112105
  constructor(options = {}) {
112040
112106
  this.filter = options.filter ?? true;
112041
112107
  }
112042
- init(router, path46 = []) {
112043
- const laziedOptions = traverseContractProcedures({ router, path: path46 }, (traverseOptions) => {
112108
+ init(router, path47 = []) {
112109
+ const laziedOptions = traverseContractProcedures({ router, path: path47 }, (traverseOptions) => {
112044
112110
  if (!value(this.filter, traverseOptions)) {
112045
112111
  return;
112046
112112
  }
@@ -112246,8 +112312,8 @@ function createRouter() {
112246
112312
  static: new NullProtoObj2()
112247
112313
  };
112248
112314
  }
112249
- function splitPath(path46) {
112250
- const [_, ...s] = path46.split("/");
112315
+ function splitPath(path47) {
112316
+ const [_, ...s] = path47.split("/");
112251
112317
  return s[s.length - 1] === "" ? s.slice(0, -1) : s;
112252
112318
  }
112253
112319
  function getMatchParams(segments, paramsMap) {
@@ -112262,11 +112328,11 @@ function getMatchParams(segments, paramsMap) {
112262
112328
  }
112263
112329
  return params;
112264
112330
  }
112265
- function addRoute(ctx, method = "", path46, data) {
112331
+ function addRoute(ctx, method = "", path47, data) {
112266
112332
  method = method.toUpperCase();
112267
- if (path46.charCodeAt(0) !== 47) path46 = `/${path46}`;
112268
- path46 = path46.replace(/\\:/g, "%3A");
112269
- const segments = splitPath(path46);
112333
+ if (path47.charCodeAt(0) !== 47) path47 = `/${path47}`;
112334
+ path47 = path47.replace(/\\:/g, "%3A");
112335
+ const segments = splitPath(path47);
112270
112336
  let node2 = ctx.root;
112271
112337
  let _unnamedParamIndex = 0;
112272
112338
  const paramsMap = [];
@@ -112332,14 +112398,14 @@ function getParamRegexp(segment) {
112332
112398
  const regex = segment.replace(/:(\w+)/g, (_, id2) => `(?<${id2}>[^/]+)`).replace(/\./g, "\\.");
112333
112399
  return /* @__PURE__ */ new RegExp(`^${regex}$`);
112334
112400
  }
112335
- function findRoute(ctx, method = "", path46, opts) {
112336
- if (path46.charCodeAt(path46.length - 1) === 47) path46 = path46.slice(0, -1);
112337
- const staticNode = ctx.static[path46];
112401
+ function findRoute(ctx, method = "", path47, opts) {
112402
+ if (path47.charCodeAt(path47.length - 1) === 47) path47 = path47.slice(0, -1);
112403
+ const staticNode = ctx.static[path47];
112338
112404
  if (staticNode && staticNode.methods) {
112339
112405
  const staticMatch = staticNode.methods[method] || staticNode.methods[""];
112340
112406
  if (staticMatch !== void 0) return staticMatch[0];
112341
112407
  }
112342
- const segments = splitPath(path46);
112408
+ const segments = splitPath(path47);
112343
112409
  const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];
112344
112410
  if (match === void 0) return;
112345
112411
  if (opts?.params === false) return match;
@@ -112494,8 +112560,8 @@ var StandardOpenAPICodec = class {
112494
112560
  return true;
112495
112561
  }
112496
112562
  };
112497
- function toRou3Pattern(path46) {
112498
- return standardizeHTTPPath(path46).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
112563
+ function toRou3Pattern(path47) {
112564
+ return standardizeHTTPPath(path47).replace(/\/\{\+([^}]+)\}/g, "/**:$1").replace(/\/\{([^}]+)\}/g, "/:$1");
112499
112565
  }
112500
112566
  function decodeParams(params) {
112501
112567
  return Object.fromEntries(Object.entries(params).map(([key, value2]) => [key, tryDecodeURIComponent(value2)]));
@@ -112507,8 +112573,8 @@ var StandardOpenAPIMatcher = class {
112507
112573
  constructor(options = {}) {
112508
112574
  this.filter = options.filter ?? true;
112509
112575
  }
112510
- init(router, path46 = []) {
112511
- const laziedOptions = traverseContractProcedures({ router, path: path46 }, (traverseOptions) => {
112576
+ init(router, path47 = []) {
112577
+ const laziedOptions = traverseContractProcedures({ router, path: path47 }, (traverseOptions) => {
112512
112578
  if (!value(this.filter, traverseOptions)) {
112513
112579
  return;
112514
112580
  }
@@ -112790,6 +112856,7 @@ var LaunchLifecycleEventSchema = external_exports.strictObject({
112790
112856
  var DoorHealthEventSchema = external_exports.discriminatedUnion("kind", [
112791
112857
  external_exports.strictObject({ kind: external_exports.literal("generation"), pid: external_exports.number().int().positive(), providerPort: external_exports.number().int().positive(), connectPort: external_exports.number().int().positive(), directPort: external_exports.number().int().positive(), observedAt: external_exports.number() }),
112792
112858
  external_exports.strictObject({ kind: external_exports.literal("listenerFailed"), pid: external_exports.number().int().positive(), listener: external_exports.enum(["provider", "connect", "direct"]), message: external_exports.string(), observedAt: external_exports.number() }),
112859
+ external_exports.strictObject({ kind: external_exports.literal("binaryTurnover"), pid: external_exports.number().int().positive(), observedAt: external_exports.number() }),
112793
112860
  external_exports.strictObject({ kind: external_exports.literal("idleShutdown"), pid: external_exports.number().int().positive(), observedAt: external_exports.number() })
112794
112861
  ]);
112795
112862
  var QuotaExpiringEventSchema = external_exports.strictObject({
@@ -112923,6 +112990,9 @@ function createDoorHealthPublisher(hub, now, pid) {
112923
112990
  },
112924
112991
  idleShutdown: () => {
112925
112992
  publisher.publish({ kind: "idleShutdown", pid, observedAt: now() });
112993
+ },
112994
+ binaryTurnover: () => {
112995
+ publisher.publish({ kind: "binaryTurnover", pid, observedAt: now() });
112926
112996
  }
112927
112997
  };
112928
112998
  }
@@ -114231,8 +114301,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
114231
114301
  request7.body.resume();
114232
114302
  return;
114233
114303
  }
114234
- const path46 = new URL(request7.url, "http://127.0.0.1").pathname;
114235
- const translated = { method: request7.method, path: path46, body, signal: request7.signal };
114304
+ const path47 = new URL(request7.url, "http://127.0.0.1").pathname;
114305
+ const translated = { method: request7.method, path: path47, body, signal: request7.signal };
114236
114306
  const routed = await route(translated);
114237
114307
  if (request7.signal.aborted) {
114238
114308
  return;
@@ -114266,7 +114336,7 @@ function createPassthroughRoute(name, target) {
114266
114336
  headroomUpstream: target.headroomUpstream,
114267
114337
  serve: async (request7, response) => {
114268
114338
  const incoming = new URL(request7.url, "http://127.0.0.1");
114269
- const path46 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
114339
+ const path47 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
114270
114340
  const headers = forwardableHeaders(request7.headers);
114271
114341
  delete headers.host;
114272
114342
  await new Promise((resolve2) => {
@@ -114274,7 +114344,7 @@ function createPassthroughRoute(name, target) {
114274
114344
  host: base.hostname,
114275
114345
  port: base.port === "" ? void 0 : Number(base.port),
114276
114346
  method: request7.method,
114277
- path: `${basePath}${path46}${incoming.search}`,
114347
+ path: `${basePath}${path47}${incoming.search}`,
114278
114348
  headers,
114279
114349
  agent
114280
114350
  };
@@ -114407,7 +114477,7 @@ async function scanRequestHead(request7, wholeBody = false) {
114407
114477
  // src/frontdoor/providerRoute.ts
114408
114478
  var MS_PER_HOUR3 = 36e5;
114409
114479
  function createProviderRouteResolver(deps) {
114410
- const isRcSelfHostPath = (path46) => path46 === "/v1/code/sessions" || path46.startsWith("/v1/code/sessions/") || path46 === "/v1/sessions" || path46.startsWith("/v1/sessions/");
114480
+ const isRcSelfHostPath = (path47) => path47 === "/v1/code/sessions" || path47.startsWith("/v1/code/sessions/") || path47 === "/v1/sessions" || path47.startsWith("/v1/sessions/");
114411
114481
  const oauthRoute = createPassthroughRoute("anthropic", { baseUrl: `https://${CONNECT_INTERCEPT_HOST}:${String(HTTPS_PORT)}`, stripPrefix: void 0, headroomUpstream: void 0 });
114412
114482
  const passthroughByTarget = /* @__PURE__ */ new Map();
114413
114483
  const passthroughFor = (name, target) => {
@@ -114421,16 +114491,16 @@ function createProviderRouteResolver(deps) {
114421
114491
  return route;
114422
114492
  };
114423
114493
  const resolve2 = (request7) => {
114424
- const path46 = new URL(request7.url, "http://127.0.0.1").pathname;
114425
- const scoped = parseProviderPath(path46);
114494
+ const path47 = new URL(request7.url, "http://127.0.0.1").pathname;
114495
+ const scoped = parseProviderPath(path47);
114426
114496
  if (scoped === void 0) {
114427
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path46)) {
114497
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path47)) {
114428
114498
  return { ok: true, route: deps.rcSelfHostRoute };
114429
114499
  }
114430
- if (request7.session.provider !== void 0 && path46.startsWith("/v1/") && !isRcSelfHostPath(path46)) {
114500
+ if (request7.session.provider !== void 0 && path47.startsWith("/v1/") && !isRcSelfHostPath(path47)) {
114431
114501
  return resolve2({ ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` });
114432
114502
  }
114433
- return path46.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path46}` };
114503
+ return path47.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path47}` };
114434
114504
  }
114435
114505
  const { provider } = scoped;
114436
114506
  let definition;
@@ -114483,8 +114553,8 @@ function createProviderRouteResolver(deps) {
114483
114553
  let replay;
114484
114554
  const visited = /* @__PURE__ */ new Set();
114485
114555
  for (; ; ) {
114486
- const path46 = new URL(current.url, "http://127.0.0.1").pathname;
114487
- const scoped = parseProviderPath(path46);
114556
+ const path47 = new URL(current.url, "http://127.0.0.1").pathname;
114557
+ const scoped = parseProviderPath(path47);
114488
114558
  const providerName = scoped?.provider ?? current.session.provider;
114489
114559
  if (providerName !== void 0 && visited.has(providerName)) {
114490
114560
  return { ok: false, status: HTTP_STATUS.internalServerError, message: `provider routing cycle: ${[...visited, providerName].join(" -> ")}` };
@@ -114549,7 +114619,7 @@ function createProviderRouteResolver(deps) {
114549
114619
  const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
114550
114620
  replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
114551
114621
  }
114552
- const rest = scoped === void 0 ? path46 : path46.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
114622
+ const rest = scoped === void 0 ? path47 : path47.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
114553
114623
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
114554
114624
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
114555
114625
  }
@@ -114653,7 +114723,7 @@ function createRcLiveUsage(deps) {
114653
114723
  }
114654
114724
 
114655
114725
  // src/frontdoor/rcSelfHostMint.ts
114656
- var import_node_path39 = __toESM(require("node:path"), 1);
114726
+ var import_node_path40 = __toESM(require("node:path"), 1);
114657
114727
  init_account();
114658
114728
 
114659
114729
  // src/frontdoor/rcSelfHostLocal.ts
@@ -114783,7 +114853,7 @@ function readJsonObject(fs21, file2) {
114783
114853
  return isRecord6(parsed) ? parsed : void 0;
114784
114854
  }
114785
114855
  function readRcSelfHostRecord(fs21, frontdoorDir) {
114786
- const parsed = readJsonObject(fs21, import_node_path39.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
114856
+ const parsed = readJsonObject(fs21, import_node_path40.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
114787
114857
  if (parsed === void 0) {
114788
114858
  return void 0;
114789
114859
  }
@@ -114797,11 +114867,11 @@ function mintRcSelfHostCredential(deps) {
114797
114867
  if (!isIdentityName(deps.identity)) {
114798
114868
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
114799
114869
  }
114800
- const identityDir = import_node_path39.default.join(deps.identitiesDir, deps.identity);
114801
- const credentialsFile = import_node_path39.default.join(identityDir, CREDENTIALS_FILE);
114802
- const claudeJsonFile = import_node_path39.default.join(identityDir, CLAUDE_JSON2);
114803
- const recordDir = import_node_path39.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
114804
- const recordFile = import_node_path39.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
114870
+ const identityDir = import_node_path40.default.join(deps.identitiesDir, deps.identity);
114871
+ const credentialsFile = import_node_path40.default.join(identityDir, CREDENTIALS_FILE);
114872
+ const claudeJsonFile = import_node_path40.default.join(identityDir, CLAUDE_JSON2);
114873
+ const recordDir = import_node_path40.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
114874
+ const recordFile = import_node_path40.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
114805
114875
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
114806
114876
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
114807
114877
  const existingOauth = isRecord6(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -114817,7 +114887,7 @@ function mintRcSelfHostCredential(deps) {
114817
114887
  const organizationUuid = deps.newUuid();
114818
114888
  const accountUuid = deps.newUuid();
114819
114889
  const mintedAt = new Date(deps.now()).toISOString();
114820
- deps.fs.mkdirPrivate(import_node_path39.default.dirname(credentialsFile));
114890
+ deps.fs.mkdirPrivate(import_node_path40.default.dirname(credentialsFile));
114821
114891
  deps.fs.writeFilePrivate(credentialsFile, `${JSON.stringify({ ...existingCredentials, claudeAiOauth: { accessToken, refreshToken, expiresAt: null, scopes: [...RC_SELF_HOST_SCOPE_LIST], subscriptionType: SELF_HOST_SUBSCRIPTION_TYPE, rateLimitTier: null } }, null, 2)}
114822
114892
  `);
114823
114893
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -115204,7 +115274,7 @@ function registerRcCommand(frontdoor, paths) {
115204
115274
  }
115205
115275
 
115206
115276
  // src/frontdoor/rcCredentialStore.ts
115207
- var import_node_path40 = __toESM(require("node:path"), 1);
115277
+ var import_node_path41 = __toESM(require("node:path"), 1);
115208
115278
  function isSafeSessionId(sessionId) {
115209
115279
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
115210
115280
  }
@@ -115230,7 +115300,7 @@ function sequenceNumOfJson(value2) {
115230
115300
  }
115231
115301
  function createRcCredentialStore(fs21, dir) {
115232
115302
  fs21.mkdirPrivate(dir);
115233
- const fileFor = (sessionId) => import_node_path40.default.join(dir, `${sessionId}.json`);
115303
+ const fileFor = (sessionId) => import_node_path41.default.join(dir, `${sessionId}.json`);
115234
115304
  const readParsed = (sessionId) => {
115235
115305
  const raw = fs21.readFileUtf8(fileFor(sessionId));
115236
115306
  if (raw === void 0) {
@@ -117299,7 +117369,7 @@ init_socket();
117299
117369
  init_state();
117300
117370
  init_state2();
117301
117371
  function headroomSocketTarget(fsPort, trust, paths) {
117302
- const socketPath = readHeadroomState(fsPort, paths.headroomStateFile)?.socketPath;
117372
+ const socketPath = readHeadroomState(fsPort, paths.headroomStateFile)?.socketPath ?? readHeadroomState(fsPort, paths.headroomLegacyStateFile)?.socketPath;
117303
117373
  return socketPath === void 0 ? void 0 : verifyHeadroomSocket(socketPath, trust);
117304
117374
  }
117305
117375
  function collectFrontDoorStatus(fsPort, socketTrust, paths, isRunning) {
@@ -117404,6 +117474,12 @@ function rcObservingResolver(resolve2, tracker, hub) {
117404
117474
  } }) } : resolution;
117405
117475
  };
117406
117476
  }
117477
+ function realStatOwnExecutable(watchPath) {
117478
+ return () => {
117479
+ const st2 = import_node_fs15.default.statSync(watchPath, { throwIfNoEntry: false });
117480
+ return st2?.isFile() !== true ? void 0 : { dev: st2.dev, ino: st2.ino, size: st2.size, mtimeMs: st2.mtimeMs };
117481
+ };
117482
+ }
117407
117483
  function realFrontDoorSupervisorPorts(paths) {
117408
117484
  const log = (line) => {
117409
117485
  appendLog(paths, `frontdoor ${String(process.pid)}: ${line}`);
@@ -117532,6 +117608,8 @@ function realFrontDoorSupervisorPorts(paths) {
117532
117608
  });
117533
117609
  },
117534
117610
  isRunning: realIsProcessRunning,
117611
+ // The turnover check's file identity, over the installed entry resolved once at door start: re-resolving per tick would re-run the PATH scan every second and could theoretically flip between two files, while the entry itself is fixed for as long as this door lives. The existence check prefers the agent-shim sibling only when it is really there (see watchedInstallEntry).
117612
+ statOwnExecutable: realStatOwnExecutable(watchedInstallEntry(realOwnExecutablePath(), (candidate) => import_node_fs15.default.existsSync(candidate))),
117535
117613
  startProviderListener: async (preferredPort) => {
117536
117614
  const authority = loadCa();
117537
117615
  const rcDial = rcSelfHost ? lateRcEventDial(rcSelfHostDialTarget) : realRcEventDial();
@@ -117626,7 +117704,7 @@ function realFrontDoorSupervisorPorts(paths) {
117626
117704
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
117627
117705
  const capture = captureFromEnv(process.env, paths.logsDir);
117628
117706
  if (capture !== void 0) {
117629
- log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path41.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
117707
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path42.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
117630
117708
  }
117631
117709
  if (rcSelfHostSurface !== void 0) {
117632
117710
  log("self-hosted Remote Control surface on: the door serves the CCR session family itself, and its own client-half dials its own transparent surface");
@@ -117885,16 +117963,16 @@ init_credentialCache();
117885
117963
 
117886
117964
  // src/identityToken.ts
117887
117965
  var import_node_fs16 = __toESM(require("node:fs"), 1);
117888
- var import_node_path42 = __toESM(require("node:path"), 1);
117966
+ var import_node_path43 = __toESM(require("node:path"), 1);
117889
117967
  init_cliError();
117890
117968
  var TOKEN_FILE_MODE = 384;
117891
117969
  var TOKEN_DIR_MODE = 448;
117892
117970
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
117893
117971
  function identityTokenDir(paths) {
117894
- return import_node_path42.default.join(paths.root, "credentials");
117972
+ return import_node_path43.default.join(paths.root, "credentials");
117895
117973
  }
117896
117974
  function identityTokenPath(paths, identityName) {
117897
- return import_node_path42.default.join(identityTokenDir(paths), `${identityName}.token`);
117975
+ return import_node_path43.default.join(identityTokenDir(paths), `${identityName}.token`);
117898
117976
  }
117899
117977
  function storeIdentityToken(paths, identityName, raw) {
117900
117978
  const token = raw.trim();
@@ -117905,7 +117983,7 @@ function storeIdentityToken(paths, identityName, raw) {
117905
117983
  import_node_fs16.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
117906
117984
  import_node_fs16.default.chmodSync(dir, TOKEN_DIR_MODE);
117907
117985
  const target = identityTokenPath(paths, identityName);
117908
- const temp = import_node_path42.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
117986
+ const temp = import_node_path43.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
117909
117987
  import_node_fs16.default.writeFileSync(temp, `${token}
117910
117988
  `, { mode: TOKEN_FILE_MODE });
117911
117989
  import_node_fs16.default.renameSync(temp, target);
@@ -118073,7 +118151,7 @@ function registerDoctorCommand(program2, deps) {
118073
118151
  // src/headroom/commands.ts
118074
118152
  var import_node_fs17 = __toESM(require("node:fs"), 1);
118075
118153
  var import_node_http3 = __toESM(require("node:http"), 1);
118076
- var import_node_path43 = __toESM(require("node:path"), 1);
118154
+ var import_node_path44 = __toESM(require("node:path"), 1);
118077
118155
  var import_node_child_process6 = require("node:child_process");
118078
118156
  init_commandDeps();
118079
118157
  init_realFrontDoorPort();
@@ -118084,7 +118162,7 @@ init_realPorts();
118084
118162
  init_state();
118085
118163
  init_supervisor();
118086
118164
  function collectHeadroomStatus(fsPort, paths, isRunning) {
118087
- const state = readHeadroomState(fsPort, paths.headroomStateFile) ?? {};
118165
+ const state = resolveServingHeadroomState(fsPort, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, isRunning)?.state ?? {};
118088
118166
  const allowlist = currentHeadroomAllowlist(fsPort, paths);
118089
118167
  const settings2 = settingsOf(readGlobalConfig(paths)?.headroom ?? {});
118090
118168
  return {
@@ -118187,12 +118265,12 @@ function readInstalledHeadroomCommit() {
118187
118265
  if (toolDir.status !== 0) {
118188
118266
  return void 0;
118189
118267
  }
118190
- const libDir = import_node_path43.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
118268
+ const libDir = import_node_path44.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
118191
118269
  for (const python of realFarmFs.readdir(libDir)) {
118192
- const sitePackages = import_node_path43.default.join(libDir, python, "site-packages");
118270
+ const sitePackages = import_node_path44.default.join(libDir, python, "site-packages");
118193
118271
  for (const entry of realFarmFs.readdir(sitePackages)) {
118194
118272
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
118195
- const directUrl = realFarmFs.readFileUtf8(import_node_path43.default.join(sitePackages, entry, "direct_url.json"));
118273
+ const directUrl = realFarmFs.readFileUtf8(import_node_path44.default.join(sitePackages, entry, "direct_url.json"));
118196
118274
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
118197
118275
  }
118198
118276
  }
@@ -118752,7 +118830,7 @@ function registerRunCommand(program2, handler) {
118752
118830
  var import_node_child_process7 = require("node:child_process");
118753
118831
  var import_node_fs18 = __toESM(require("node:fs"), 1);
118754
118832
  var import_node_os11 = __toESM(require("node:os"), 1);
118755
- var import_node_path44 = __toESM(require("node:path"), 1);
118833
+ var import_node_path45 = __toESM(require("node:path"), 1);
118756
118834
  init_package();
118757
118835
  init_commandDeps();
118758
118836
  init_store();
@@ -118854,7 +118932,7 @@ var realUpdatePorts = {
118854
118932
  chmod: (filePath, mode) => {
118855
118933
  import_node_fs18.default.chmodSync(filePath, mode);
118856
118934
  },
118857
- mkdtemp: () => import_node_fs18.default.mkdtempSync(import_node_path44.default.join(import_node_os11.default.tmpdir(), "agent-shim-update-")),
118935
+ mkdtemp: () => import_node_fs18.default.mkdtempSync(import_node_path45.default.join(import_node_os11.default.tmpdir(), "agent-shim-update-")),
118858
118936
  rmRecursive: (targetPath) => {
118859
118937
  import_node_fs18.default.rmSync(targetPath, { recursive: true, force: true });
118860
118938
  }
@@ -118921,7 +118999,7 @@ function registerUpdateCommand(program2, deps, ports = realUpdatePorts) {
118921
118999
  platform: process.platform,
118922
119000
  arch: process.arch,
118923
119001
  executablePath: realOwnExecutablePath(),
118924
- lockPath: import_node_path44.default.join(deps.paths.root, "update.lock"),
119002
+ lockPath: import_node_path45.default.join(deps.paths.root, "update.lock"),
118925
119003
  checkOnly: options.check === true,
118926
119004
  pid: process.pid
118927
119005
  });
@@ -119391,7 +119469,7 @@ async function runClaude(argvOverride) {
119391
119469
  // src/cli.ts
119392
119470
  async function main() {
119393
119471
  aliasLegacyEnv(process.env);
119394
- const invokedName = import_node_path45.default.basename(process.argv[1] ?? "agent-shim");
119472
+ const invokedName = import_node_path46.default.basename(process.argv[1] ?? "agent-shim");
119395
119473
  if (isInvokedAsClaude(invokedName)) {
119396
119474
  await runClaude();
119397
119475
  return;