agent-shim 8.14.1 → 8.16.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
@@ -3248,42 +3248,42 @@ var require_defaults = __commonJS({
3248
3248
  var require_env_paths = __commonJS({
3249
3249
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
3250
3250
  "use strict";
3251
- var path43 = require("path");
3251
+ var path44 = require("path");
3252
3252
  var os10 = require("os");
3253
3253
  var homedir = os10.homedir();
3254
3254
  var tmpdir = os10.tmpdir();
3255
3255
  var { env } = process;
3256
3256
  var macos = (name) => {
3257
- const library = path43.join(homedir, "Library");
3257
+ const library = path44.join(homedir, "Library");
3258
3258
  return {
3259
- data: path43.join(library, "Application Support", name),
3260
- config: path43.join(library, "Preferences", name),
3261
- cache: path43.join(library, "Caches", name),
3262
- log: path43.join(library, "Logs", name),
3263
- temp: path43.join(tmpdir, name)
3259
+ data: path44.join(library, "Application Support", name),
3260
+ config: path44.join(library, "Preferences", name),
3261
+ cache: path44.join(library, "Caches", name),
3262
+ log: path44.join(library, "Logs", name),
3263
+ temp: path44.join(tmpdir, name)
3264
3264
  };
3265
3265
  };
3266
3266
  var windows = (name) => {
3267
- const appData = env.APPDATA || path43.join(homedir, "AppData", "Roaming");
3268
- const localAppData = env.LOCALAPPDATA || path43.join(homedir, "AppData", "Local");
3267
+ const appData = env.APPDATA || path44.join(homedir, "AppData", "Roaming");
3268
+ const localAppData = env.LOCALAPPDATA || path44.join(homedir, "AppData", "Local");
3269
3269
  return {
3270
3270
  // Data/config/cache/log are invented by me as Windows isn't opinionated about this
3271
- data: path43.join(localAppData, name, "Data"),
3272
- config: path43.join(appData, name, "Config"),
3273
- cache: path43.join(localAppData, name, "Cache"),
3274
- log: path43.join(localAppData, name, "Log"),
3275
- temp: path43.join(tmpdir, name)
3271
+ data: path44.join(localAppData, name, "Data"),
3272
+ config: path44.join(appData, name, "Config"),
3273
+ cache: path44.join(localAppData, name, "Cache"),
3274
+ log: path44.join(localAppData, name, "Log"),
3275
+ temp: path44.join(tmpdir, name)
3276
3276
  };
3277
3277
  };
3278
3278
  var linux = (name) => {
3279
- const username = path43.basename(homedir);
3279
+ const username = path44.basename(homedir);
3280
3280
  return {
3281
- data: path43.join(env.XDG_DATA_HOME || path43.join(homedir, ".local", "share"), name),
3282
- config: path43.join(env.XDG_CONFIG_HOME || path43.join(homedir, ".config"), name),
3283
- cache: path43.join(env.XDG_CACHE_HOME || path43.join(homedir, ".cache"), name),
3281
+ data: path44.join(env.XDG_DATA_HOME || path44.join(homedir, ".local", "share"), name),
3282
+ config: path44.join(env.XDG_CONFIG_HOME || path44.join(homedir, ".config"), name),
3283
+ cache: path44.join(env.XDG_CACHE_HOME || path44.join(homedir, ".cache"), name),
3284
3284
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
3285
- log: path43.join(env.XDG_STATE_HOME || path43.join(homedir, ".local", "state"), name),
3286
- temp: path43.join(tmpdir, username, name)
3285
+ log: path44.join(env.XDG_STATE_HOME || path44.join(homedir, ".local", "state"), name),
3286
+ temp: path44.join(tmpdir, username, name)
3287
3287
  };
3288
3288
  };
3289
3289
  var envPaths = (name, options) => {
@@ -3351,11 +3351,11 @@ var require_util = __commonJS({
3351
3351
  return result;
3352
3352
  }
3353
3353
  exports2.emplace = emplace;
3354
- function getPropertyByPath(source, path43) {
3355
- if (typeof path43 === "string" && Object.prototype.hasOwnProperty.call(source, path43)) {
3356
- return source[path43];
3354
+ function getPropertyByPath(source, path44) {
3355
+ if (typeof path44 === "string" && Object.prototype.hasOwnProperty.call(source, path44)) {
3356
+ return source[path44];
3357
3357
  }
3358
- const parsedPath = typeof path43 === "string" ? path43.split(".") : path43;
3358
+ const parsedPath = typeof path44 === "string" ? path44.split(".") : path44;
3359
3359
  return parsedPath.reduce((previous, key) => {
3360
3360
  if (previous === void 0) {
3361
3361
  return previous;
@@ -3378,9 +3378,9 @@ var require_util = __commonJS({
3378
3378
  return Object.fromEntries(Object.entries(options).filter(([, value2]) => value2 !== void 0));
3379
3379
  }
3380
3380
  exports2.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
3381
- async function isDirectory(path43) {
3381
+ async function isDirectory(path44) {
3382
3382
  try {
3383
- const stat = await fs_1.promises.stat(path43);
3383
+ const stat = await fs_1.promises.stat(path44);
3384
3384
  return stat.isDirectory();
3385
3385
  } catch (e) {
3386
3386
  if (e.code === "ENOENT") {
@@ -3390,9 +3390,9 @@ var require_util = __commonJS({
3390
3390
  }
3391
3391
  }
3392
3392
  exports2.isDirectory = isDirectory;
3393
- function isDirectorySync(path43) {
3393
+ function isDirectorySync(path44) {
3394
3394
  try {
3395
- const stat = fs_1.default.statSync(path43);
3395
+ const stat = fs_1.default.statSync(path44);
3396
3396
  return stat.isDirectory();
3397
3397
  } catch (e) {
3398
3398
  if (e.code === "ENOENT") {
@@ -3490,7 +3490,7 @@ var require_ExplorerBase = __commonJS({
3490
3490
  const idx = importStack.indexOf(fullPath);
3491
3491
  if (idx !== -1) {
3492
3492
  throw new Error(`Circular import detected:
3493
- ${[...importStack, fullPath].map((path43, i2) => `${i2 + 1}. ${path43}`).join("\n")} (same as ${idx + 1}.)`);
3493
+ ${[...importStack, fullPath].map((path44, i2) => `${i2 + 1}. ${path44}`).join("\n")} (same as ${idx + 1}.)`);
3494
3494
  }
3495
3495
  }
3496
3496
  }
@@ -3678,9 +3678,9 @@ var require_Explorer = __commonJS({
3678
3678
  throw error62;
3679
3679
  }
3680
3680
  }
3681
- async #fileExists(path43) {
3681
+ async #fileExists(path44) {
3682
3682
  try {
3683
- await promises_1.default.stat(path43);
3683
+ await promises_1.default.stat(path44);
3684
3684
  return true;
3685
3685
  } catch (e) {
3686
3686
  return false;
@@ -3840,9 +3840,9 @@ var require_ExplorerSync = __commonJS({
3840
3840
  throw error62;
3841
3841
  }
3842
3842
  }
3843
- #fileExists(path43) {
3843
+ #fileExists(path44) {
3844
3844
  try {
3845
- fs_1.default.statSync(path43);
3845
+ fs_1.default.statSync(path44);
3846
3846
  return true;
3847
3847
  } catch (e) {
3848
3848
  return false;
@@ -3966,7 +3966,7 @@ var require_dist = __commonJS({
3966
3966
  };
3967
3967
  }
3968
3968
  function getResolvedSearchPlaces(moduleName, toolDefinedSearchPlaces, userConfiguredOptions) {
3969
- const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path43) => path43.replace("{name}", moduleName));
3969
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path44) => path44.replace("{name}", moduleName));
3970
3970
  if (userConfiguredOptions.mergeSearchPlaces) {
3971
3971
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
3972
3972
  }
@@ -4374,8 +4374,8 @@ var require_utils = __commonJS({
4374
4374
  }
4375
4375
  return output2;
4376
4376
  };
4377
- exports2.basename = (path43, { windows } = {}) => {
4378
- const segs = path43.split(windows ? /[\\/]/ : "/");
4377
+ exports2.basename = (path44, { windows } = {}) => {
4378
+ const segs = path44.split(windows ? /[\\/]/ : "/");
4379
4379
  const last = segs[segs.length - 1];
4380
4380
  if (last === "") {
4381
4381
  return segs[segs.length - 2];
@@ -7003,14 +7003,14 @@ var require_util2 = __commonJS({
7003
7003
  }
7004
7004
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
7005
7005
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
7006
- let path43 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
7006
+ let path44 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
7007
7007
  if (origin[origin.length - 1] === "/") {
7008
7008
  origin = origin.slice(0, origin.length - 1);
7009
7009
  }
7010
- if (path43 && path43[0] !== "/") {
7011
- path43 = `/${path43}`;
7010
+ if (path44 && path44[0] !== "/") {
7011
+ path44 = `/${path44}`;
7012
7012
  }
7013
- return new URL(`${origin}${path43}`);
7013
+ return new URL(`${origin}${path44}`);
7014
7014
  }
7015
7015
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
7016
7016
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -7831,9 +7831,9 @@ var require_diagnostics = __commonJS({
7831
7831
  "undici:client:sendHeaders",
7832
7832
  (evt) => {
7833
7833
  const {
7834
- request: { method, path: path43, origin }
7834
+ request: { method, path: path44, origin }
7835
7835
  } = evt;
7836
- debugLog("sending request to %s %s%s", method, origin, path43);
7836
+ debugLog("sending request to %s %s%s", method, origin, path44);
7837
7837
  }
7838
7838
  );
7839
7839
  }
@@ -7851,14 +7851,14 @@ var require_diagnostics = __commonJS({
7851
7851
  "undici:request:headers",
7852
7852
  (evt) => {
7853
7853
  const {
7854
- request: { method, path: path43, origin },
7854
+ request: { method, path: path44, origin },
7855
7855
  response: { statusCode }
7856
7856
  } = evt;
7857
7857
  debugLog(
7858
7858
  "received response to %s %s%s - HTTP %d",
7859
7859
  method,
7860
7860
  origin,
7861
- path43,
7861
+ path44,
7862
7862
  statusCode
7863
7863
  );
7864
7864
  }
@@ -7867,23 +7867,23 @@ var require_diagnostics = __commonJS({
7867
7867
  "undici:request:trailers",
7868
7868
  (evt) => {
7869
7869
  const {
7870
- request: { method, path: path43, origin }
7870
+ request: { method, path: path44, origin }
7871
7871
  } = evt;
7872
- debugLog("trailers received from %s %s%s", method, origin, path43);
7872
+ debugLog("trailers received from %s %s%s", method, origin, path44);
7873
7873
  }
7874
7874
  );
7875
7875
  diagnosticsChannel.subscribe(
7876
7876
  "undici:request:error",
7877
7877
  (evt) => {
7878
7878
  const {
7879
- request: { method, path: path43, origin },
7879
+ request: { method, path: path44, origin },
7880
7880
  error: error62
7881
7881
  } = evt;
7882
7882
  debugLog(
7883
7883
  "request to %s %s%s errored - %s",
7884
7884
  method,
7885
7885
  origin,
7886
- path43,
7886
+ path44,
7887
7887
  error62.message
7888
7888
  );
7889
7889
  }
@@ -7998,7 +7998,7 @@ var require_request = __commonJS({
7998
7998
  var kHandler = /* @__PURE__ */ Symbol("handler");
7999
7999
  var Request2 = class {
8000
8000
  constructor(origin, {
8001
- path: path43,
8001
+ path: path44,
8002
8002
  method,
8003
8003
  body,
8004
8004
  headers,
@@ -8015,11 +8015,11 @@ var require_request = __commonJS({
8015
8015
  maxRedirections,
8016
8016
  typeOfService
8017
8017
  }, handler) {
8018
- if (typeof path43 !== "string") {
8018
+ if (typeof path44 !== "string") {
8019
8019
  throw new InvalidArgumentError2("path must be a string");
8020
- } else if (path43[0] !== "/" && !(path43.startsWith("http://") || path43.startsWith("https://")) && method !== "CONNECT") {
8020
+ } else if (path44[0] !== "/" && !(path44.startsWith("http://") || path44.startsWith("https://")) && method !== "CONNECT") {
8021
8021
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
8022
- } else if (invalidPathRegex.test(path43)) {
8022
+ } else if (invalidPathRegex.test(path44)) {
8023
8023
  throw new InvalidArgumentError2("invalid request path");
8024
8024
  }
8025
8025
  if (typeof method !== "string") {
@@ -8094,7 +8094,7 @@ var require_request = __commonJS({
8094
8094
  this.completed = false;
8095
8095
  this.aborted = false;
8096
8096
  this.upgrade = upgrade || null;
8097
- this.path = query ? serializePathWithQuery(path43, query) : path43;
8097
+ this.path = query ? serializePathWithQuery(path44, query) : path44;
8098
8098
  this.origin = origin;
8099
8099
  this.protocol = getProtocolFromUrlString(origin);
8100
8100
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -13276,7 +13276,7 @@ var require_client_h1 = __commonJS({
13276
13276
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
13277
13277
  }
13278
13278
  function writeH1(client, request7) {
13279
- const { method, path: path43, host, upgrade, blocking, reset } = request7;
13279
+ const { method, path: path44, host, upgrade, blocking, reset } = request7;
13280
13280
  let { body, headers, contentLength } = request7;
13281
13281
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
13282
13282
  if (util.isFormDataLike(body)) {
@@ -13354,7 +13354,7 @@ var require_client_h1 = __commonJS({
13354
13354
  if (socket.setTypeOfService) {
13355
13355
  socket.setTypeOfService(request7.typeOfService);
13356
13356
  }
13357
- let header = `${method} ${path43} HTTP/1.1\r
13357
+ let header = `${method} ${path44} HTTP/1.1\r
13358
13358
  `;
13359
13359
  if (typeof host === "string") {
13360
13360
  header += `host: ${host}\r
@@ -14033,7 +14033,7 @@ var require_client_h2 = __commonJS({
14033
14033
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
14034
14034
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
14035
14035
  const session = client[kHTTP2Session];
14036
- const { method, path: path43, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
14036
+ const { method, path: path44, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
14037
14037
  let { body } = request7;
14038
14038
  if (upgrade != null && upgrade !== "websocket") {
14039
14039
  util.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -14102,7 +14102,7 @@ var require_client_h2 = __commonJS({
14102
14102
  }
14103
14103
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
14104
14104
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
14105
- headers[HTTP2_HEADER_PATH] = path43;
14105
+ headers[HTTP2_HEADER_PATH] = path44;
14106
14106
  if (protocol === "ws:" || protocol === "wss:") {
14107
14107
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
14108
14108
  } else {
@@ -14144,7 +14144,7 @@ var require_client_h2 = __commonJS({
14144
14144
  stream.setTimeout(headersTimeout);
14145
14145
  return true;
14146
14146
  }
14147
- headers[HTTP2_HEADER_PATH] = path43;
14147
+ headers[HTTP2_HEADER_PATH] = path44;
14148
14148
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
14149
14149
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
14150
14150
  if (body && typeof body.read === "function") {
@@ -14464,7 +14464,7 @@ var require_client = __commonJS({
14464
14464
  "use strict";
14465
14465
  var assert2 = require("node:assert");
14466
14466
  var net3 = require("node:net");
14467
- var http6 = require("node:http");
14467
+ var http7 = require("node:http");
14468
14468
  var util = require_util2();
14469
14469
  var { ClientStats } = require_stats();
14470
14470
  var { channels } = require_diagnostics();
@@ -14522,7 +14522,7 @@ var require_client = __commonJS({
14522
14522
  var connectH1 = require_client_h1();
14523
14523
  var connectH2 = require_client_h2();
14524
14524
  var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve");
14525
- var getDefaultNodeMaxHeaderSize = http6 && http6.maxHeaderSize && Number.isInteger(http6.maxHeaderSize) && http6.maxHeaderSize > 0 ? () => http6.maxHeaderSize : () => {
14525
+ var getDefaultNodeMaxHeaderSize = http7 && http7.maxHeaderSize && Number.isInteger(http7.maxHeaderSize) && http7.maxHeaderSize > 0 ? () => http7.maxHeaderSize : () => {
14526
14526
  throw new InvalidArgumentError2("http module not available or http.maxHeaderSize invalid");
14527
14527
  };
14528
14528
  var noop = () => {
@@ -16496,10 +16496,10 @@ var require_proxy_agent = __commonJS({
16496
16496
  };
16497
16497
  const {
16498
16498
  origin,
16499
- path: path43 = "/",
16499
+ path: path44 = "/",
16500
16500
  headers = {}
16501
16501
  } = opts;
16502
- opts.path = origin + path43;
16502
+ opts.path = origin + path44;
16503
16503
  if (!("host" in headers) && !("Host" in headers)) {
16504
16504
  const { host } = new URL(origin);
16505
16505
  headers.host = host;
@@ -18608,20 +18608,20 @@ var require_mock_utils = __commonJS({
18608
18608
  }
18609
18609
  return normalizedQp;
18610
18610
  }
18611
- function safeUrl(path43) {
18612
- if (typeof path43 !== "string") {
18613
- return path43;
18611
+ function safeUrl(path44) {
18612
+ if (typeof path44 !== "string") {
18613
+ return path44;
18614
18614
  }
18615
- const pathSegments = path43.split("?", 3);
18615
+ const pathSegments = path44.split("?", 3);
18616
18616
  if (pathSegments.length !== 2) {
18617
- return path43;
18617
+ return path44;
18618
18618
  }
18619
18619
  const qp = new URLSearchParams(pathSegments.pop());
18620
18620
  qp.sort();
18621
18621
  return [...pathSegments, qp.toString()].join("?");
18622
18622
  }
18623
- function matchKey(mockDispatch2, { path: path43, method, body, headers }) {
18624
- const pathMatch = matchValue(mockDispatch2.path, path43);
18623
+ function matchKey(mockDispatch2, { path: path44, method, body, headers }) {
18624
+ const pathMatch = matchValue(mockDispatch2.path, path44);
18625
18625
  const methodMatch = matchValue(mockDispatch2.method, method);
18626
18626
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
18627
18627
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -18646,8 +18646,8 @@ var require_mock_utils = __commonJS({
18646
18646
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
18647
18647
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
18648
18648
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
18649
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path43, ignoreTrailingSlash }) => {
18650
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path43)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path43), resolvedPath);
18649
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path44, ignoreTrailingSlash }) => {
18650
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path44)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path44), resolvedPath);
18651
18651
  });
18652
18652
  if (matchedMockDispatches.length === 0) {
18653
18653
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -18686,19 +18686,19 @@ var require_mock_utils = __commonJS({
18686
18686
  mockDispatches.splice(index, 1);
18687
18687
  }
18688
18688
  }
18689
- function removeTrailingSlash(path43) {
18690
- while (path43.endsWith("/")) {
18691
- path43 = path43.slice(0, -1);
18689
+ function removeTrailingSlash(path44) {
18690
+ while (path44.endsWith("/")) {
18691
+ path44 = path44.slice(0, -1);
18692
18692
  }
18693
- if (path43.length === 0) {
18694
- path43 = "/";
18693
+ if (path44.length === 0) {
18694
+ path44 = "/";
18695
18695
  }
18696
- return path43;
18696
+ return path44;
18697
18697
  }
18698
18698
  function buildKey(opts) {
18699
- const { path: path43, method, body, headers, query } = opts;
18699
+ const { path: path44, method, body, headers, query } = opts;
18700
18700
  return {
18701
- path: path43,
18701
+ path: path44,
18702
18702
  method,
18703
18703
  body,
18704
18704
  headers,
@@ -19388,10 +19388,10 @@ var require_pending_interceptors_formatter = __commonJS({
19388
19388
  }
19389
19389
  format(pendingInterceptors) {
19390
19390
  const withPrettyHeaders = pendingInterceptors.map(
19391
- ({ method, path: path43, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
19391
+ ({ method, path: path44, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
19392
19392
  Method: method,
19393
19393
  Origin: origin,
19394
- Path: path43,
19394
+ Path: path44,
19395
19395
  "Status code": statusCode,
19396
19396
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
19397
19397
  Invocations: timesInvoked,
@@ -19473,9 +19473,9 @@ var require_mock_agent = __commonJS({
19473
19473
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
19474
19474
  const dispatchOpts = { ...opts };
19475
19475
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
19476
- const [path43, searchParams] = dispatchOpts.path.split("?");
19476
+ const [path44, searchParams] = dispatchOpts.path.split("?");
19477
19477
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
19478
- dispatchOpts.path = `${path43}?${normalizedSearchParams}`;
19478
+ dispatchOpts.path = `${path44}?${normalizedSearchParams}`;
19479
19479
  }
19480
19480
  return this[kAgent].dispatch(dispatchOpts, handler);
19481
19481
  }
@@ -19876,12 +19876,12 @@ var require_snapshot_recorder = __commonJS({
19876
19876
  * @return {Promise<void>} - Resolves when snapshots are loaded
19877
19877
  */
19878
19878
  async loadSnapshots(filePath) {
19879
- const path43 = filePath || this.#snapshotPath;
19880
- if (!path43) {
19879
+ const path44 = filePath || this.#snapshotPath;
19880
+ if (!path44) {
19881
19881
  throw new InvalidArgumentError2("Snapshot path is required");
19882
19882
  }
19883
19883
  try {
19884
- const data = await readFile(resolve(path43), "utf8");
19884
+ const data = await readFile(resolve(path44), "utf8");
19885
19885
  const parsed = JSON.parse(data);
19886
19886
  if (Array.isArray(parsed)) {
19887
19887
  this.#snapshots.clear();
@@ -19895,7 +19895,7 @@ var require_snapshot_recorder = __commonJS({
19895
19895
  if (error62.code === "ENOENT") {
19896
19896
  this.#snapshots.clear();
19897
19897
  } else {
19898
- throw new UndiciError(`Failed to load snapshots from ${path43}`, { cause: error62 });
19898
+ throw new UndiciError(`Failed to load snapshots from ${path44}`, { cause: error62 });
19899
19899
  }
19900
19900
  }
19901
19901
  }
@@ -19906,11 +19906,11 @@ var require_snapshot_recorder = __commonJS({
19906
19906
  * @returns {Promise<void>} - Resolves when snapshots are saved
19907
19907
  */
19908
19908
  async saveSnapshots(filePath) {
19909
- const path43 = filePath || this.#snapshotPath;
19910
- if (!path43) {
19909
+ const path44 = filePath || this.#snapshotPath;
19910
+ if (!path44) {
19911
19911
  throw new InvalidArgumentError2("Snapshot path is required");
19912
19912
  }
19913
- const resolvedPath = resolve(path43);
19913
+ const resolvedPath = resolve(path44);
19914
19914
  await mkdir(dirname2(resolvedPath), { recursive: true });
19915
19915
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
19916
19916
  hash: hash2,
@@ -20542,15 +20542,15 @@ var require_redirect_handler = __commonJS({
20542
20542
  return;
20543
20543
  }
20544
20544
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
20545
- const path43 = search ? `${pathname}${search}` : pathname;
20546
- const redirectUrlString = `${origin}${path43}`;
20545
+ const path44 = search ? `${pathname}${search}` : pathname;
20546
+ const redirectUrlString = `${origin}${path44}`;
20547
20547
  for (const historyUrl of this.history) {
20548
20548
  if (historyUrl.toString() === redirectUrlString) {
20549
20549
  throw new InvalidArgumentError2(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
20550
20550
  }
20551
20551
  }
20552
20552
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
20553
- this.opts.path = path43;
20553
+ this.opts.path = path44;
20554
20554
  this.opts.origin = origin;
20555
20555
  this.opts.query = null;
20556
20556
  }
@@ -22310,10 +22310,10 @@ var require_cache_handler = __commonJS({
22310
22310
  }
22311
22311
  return locationUrl.pathname + locationUrl.search;
22312
22312
  }
22313
- function deleteCachedUri(store, cacheKey, path43) {
22313
+ function deleteCachedUri(store, cacheKey, path44) {
22314
22314
  deleteCachedValue(store, {
22315
22315
  ...cacheKey,
22316
- path: path43
22316
+ path: path44
22317
22317
  });
22318
22318
  for (let i2 = 0; i2 < util.safeHTTPMethods.length; i2++) {
22319
22319
  const method = util.safeHTTPMethods[i2];
@@ -22321,7 +22321,7 @@ var require_cache_handler = __commonJS({
22321
22321
  deleteCachedValue(store, {
22322
22322
  ...cacheKey,
22323
22323
  method,
22324
- path: path43
22324
+ path: path44
22325
22325
  });
22326
22326
  }
22327
22327
  }
@@ -22332,9 +22332,9 @@ var require_cache_handler = __commonJS({
22332
22332
  }
22333
22333
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
22334
22334
  for (let i2 = 0; i2 < values.length; i2++) {
22335
- const path43 = getSameOriginPath(cacheKey, values[i2]);
22336
- if (path43 !== void 0) {
22337
- deleteCachedUri(store, cacheKey, path43);
22335
+ const path44 = getSameOriginPath(cacheKey, values[i2]);
22336
+ if (path44 !== void 0) {
22337
+ deleteCachedUri(store, cacheKey, path44);
22338
22338
  }
22339
22339
  }
22340
22340
  }
@@ -27334,11 +27334,11 @@ var require_fetch = __commonJS({
27334
27334
  function dispatch({ body }) {
27335
27335
  const url2 = requestCurrentURL(request7);
27336
27336
  const agent = fetchParams.controller.dispatcher;
27337
- const path43 = url2.pathname + url2.search;
27337
+ const path44 = url2.pathname + url2.search;
27338
27338
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
27339
27339
  return new Promise((resolve, reject) => agent.dispatch(
27340
27340
  {
27341
- path: hasTrailingQuestionMark ? `${path43}?` : path43,
27341
+ path: hasTrailingQuestionMark ? `${path44}?` : path44,
27342
27342
  origin: url2.origin,
27343
27343
  method: request7.method,
27344
27344
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -28285,9 +28285,9 @@ var require_util5 = __commonJS({
28285
28285
  }
28286
28286
  }
28287
28287
  }
28288
- function validateCookiePath(path43) {
28289
- for (let i2 = 0; i2 < path43.length; ++i2) {
28290
- const code = path43.charCodeAt(i2);
28288
+ function validateCookiePath(path44) {
28289
+ for (let i2 = 0; i2 < path44.length; ++i2) {
28290
+ const code = path44.charCodeAt(i2);
28291
28291
  if (code < 32 || // exclude CTLs (0-31)
28292
28292
  code > 126 || // exclude DEL and non-ascii
28293
28293
  code === 59) {
@@ -31635,11 +31635,11 @@ var require_undici = __commonJS({
31635
31635
  if (typeof opts.path !== "string") {
31636
31636
  throw new InvalidArgumentError2("invalid opts.path");
31637
31637
  }
31638
- let path43 = opts.path;
31638
+ let path44 = opts.path;
31639
31639
  if (!opts.path.startsWith("/")) {
31640
- path43 = `/${path43}`;
31640
+ path44 = `/${path44}`;
31641
31641
  }
31642
- url2 = new URL(util.parseOrigin(url2).origin + path43);
31642
+ url2 = new URL(util.parseOrigin(url2).origin + path44);
31643
31643
  } else {
31644
31644
  if (!opts) {
31645
31645
  opts = typeof url2 === "object" ? url2 : {};
@@ -31749,7 +31749,7 @@ ${captureLines}` : capture.stack;
31749
31749
  });
31750
31750
 
31751
31751
  // src/cli.ts
31752
- var import_node_path41 = __toESM(require("node:path"), 1);
31752
+ var import_node_path42 = __toESM(require("node:path"), 1);
31753
31753
 
31754
31754
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
31755
31755
  var CommanderError = class extends Error {
@@ -34862,9 +34862,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
34862
34862
  * @param {string} [path]
34863
34863
  * @return {(string|null|Command)}
34864
34864
  */
34865
- executableDir(path43) {
34866
- if (path43 === void 0) return this._executableDir;
34867
- this._executableDir = path43;
34865
+ executableDir(path44) {
34866
+ if (path44 === void 0) return this._executableDir;
34867
+ this._executableDir = path44;
34868
34868
  return this;
34869
34869
  }
34870
34870
  /**
@@ -36002,10 +36002,10 @@ function mergeDefs(...defs) {
36002
36002
  function cloneDef(schema) {
36003
36003
  return mergeDefs(schema._zod.def);
36004
36004
  }
36005
- function getElementAtPath(obj, path43) {
36006
- if (!path43)
36005
+ function getElementAtPath(obj, path44) {
36006
+ if (!path44)
36007
36007
  return obj;
36008
- return path43.reduce((acc, key) => acc?.[key], obj);
36008
+ return path44.reduce((acc, key) => acc?.[key], obj);
36009
36009
  }
36010
36010
  function promiseAllObject(promisesObj) {
36011
36011
  const keys = Object.keys(promisesObj);
@@ -36345,11 +36345,11 @@ function explicitlyAborted(x, startIndex = 0) {
36345
36345
  }
36346
36346
  return false;
36347
36347
  }
36348
- function prefixIssues(path43, issues) {
36348
+ function prefixIssues(path44, issues) {
36349
36349
  return issues.map((iss) => {
36350
36350
  var _a3;
36351
36351
  (_a3 = iss).path ?? (_a3.path = []);
36352
- iss.path.unshift(path43);
36352
+ iss.path.unshift(path44);
36353
36353
  return iss;
36354
36354
  });
36355
36355
  }
@@ -36799,16 +36799,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
36799
36799
  }
36800
36800
  function formatError(error62, mapper = (issue2) => issue2.message) {
36801
36801
  const fieldErrors = { _errors: [] };
36802
- const processError = (error63, path43 = []) => {
36802
+ const processError = (error63, path44 = []) => {
36803
36803
  for (const issue2 of error63.issues) {
36804
36804
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36805
- issue2.errors.map((issues) => processError({ issues }, [...path43, ...issue2.path]));
36805
+ issue2.errors.map((issues) => processError({ issues }, [...path44, ...issue2.path]));
36806
36806
  } else if (issue2.code === "invalid_key") {
36807
- processError({ issues: issue2.issues }, [...path43, ...issue2.path]);
36807
+ processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36808
36808
  } else if (issue2.code === "invalid_element") {
36809
- processError({ issues: issue2.issues }, [...path43, ...issue2.path]);
36809
+ processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36810
36810
  } else {
36811
- const fullpath = [...path43, ...issue2.path];
36811
+ const fullpath = [...path44, ...issue2.path];
36812
36812
  if (fullpath.length === 0) {
36813
36813
  fieldErrors._errors.push(mapper(issue2));
36814
36814
  } else {
@@ -36847,17 +36847,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
36847
36847
  }
36848
36848
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
36849
36849
  const result = { errors: [] };
36850
- const processError = (error63, path43 = []) => {
36850
+ const processError = (error63, path44 = []) => {
36851
36851
  var _a3;
36852
36852
  for (const issue2 of error63.issues) {
36853
36853
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36854
- issue2.errors.map((issues) => processError({ issues }, [...path43, ...issue2.path]));
36854
+ issue2.errors.map((issues) => processError({ issues }, [...path44, ...issue2.path]));
36855
36855
  } else if (issue2.code === "invalid_key") {
36856
- processError({ issues: issue2.issues }, [...path43, ...issue2.path]);
36856
+ processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36857
36857
  } else if (issue2.code === "invalid_element") {
36858
- processError({ issues: issue2.issues }, [...path43, ...issue2.path]);
36858
+ processError({ issues: issue2.issues }, [...path44, ...issue2.path]);
36859
36859
  } else {
36860
- const fullpath = [...path43, ...issue2.path];
36860
+ const fullpath = [...path44, ...issue2.path];
36861
36861
  if (fullpath.length === 0) {
36862
36862
  result.errors.push(mapper(issue2));
36863
36863
  continue;
@@ -36896,8 +36896,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
36896
36896
  }
36897
36897
  function toDotPath(_path) {
36898
36898
  const segs = [];
36899
- const path43 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36900
- for (const seg of path43) {
36899
+ const path44 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36900
+ for (const seg of path44) {
36901
36901
  if (typeof seg === "number")
36902
36902
  segs.push(`[${seg}]`);
36903
36903
  else if (typeof seg === "symbol")
@@ -53999,13 +53999,13 @@ function resolveRef(ref, ctx) {
53999
53999
  if (!ref.startsWith("#")) {
54000
54000
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
54001
54001
  }
54002
- const path43 = ref.slice(1).split("/").filter(Boolean);
54003
- if (path43.length === 0) {
54002
+ const path44 = ref.slice(1).split("/").filter(Boolean);
54003
+ if (path44.length === 0) {
54004
54004
  return ctx.rootSchema;
54005
54005
  }
54006
54006
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
54007
- if (path43[0] === defsKey) {
54008
- const key = path43[1] === void 0 ? void 0 : decodeJSONPointerSegment(path43[1]);
54007
+ if (path44[0] === defsKey) {
54008
+ const key = path44[1] === void 0 ? void 0 : decodeJSONPointerSegment(path44[1]);
54009
54009
  if (!key || !ctx.defs[key]) {
54010
54010
  throw new Error(`Reference not found: ${ref}`);
54011
54011
  }
@@ -55242,6 +55242,8 @@ var ProviderEnvSchema = external_exports.record(external_exports.string().min(1)
55242
55242
  var PROVIDER_KINDS = ["http", "codex"];
55243
55243
  var CODEX_TIERS = ["fable", "opus", "sonnet", "haiku"];
55244
55244
  var CODEX_EFFORTS = ["none", "low", "medium", "high"];
55245
+ var CODEX_LOGINS = ["codex-cli", "chatgpt-sign-in"];
55246
+ var CODEX_DEFAULT_LOGIN = "codex-cli";
55245
55247
  var CODEX_DEFAULT_MODEL = "gpt-5.6-sol";
55246
55248
  var CODEX_DEFAULT_TIER_MODELS = Object.freeze({
55247
55249
  fable: "gpt-5.6-sol",
@@ -55261,7 +55263,9 @@ var CodexProviderConfigSchema = external_exports.strictObject({
55261
55263
  haiku: external_exports.string().min(1).optional()
55262
55264
  }).optional(),
55263
55265
  /** The reasoning effort used when the request's own `output_config.effort` is not one the backend accepts. */
55264
- effort: external_exports.enum(CODEX_EFFORTS).optional()
55266
+ effort: external_exports.enum(CODEX_EFFORTS).optional(),
55267
+ /** Which login the upstream call is made with; see `CODEX_LOGINS`. */
55268
+ login: external_exports.enum(CODEX_LOGINS).optional()
55265
55269
  });
55266
55270
  var HttpProviderSchema = external_exports.strictObject({
55267
55271
  $schema: external_exports.string().optional(),
@@ -58058,6 +58062,20 @@ var import_node_path13 = __toESM(require("node:path"), 1);
58058
58062
 
58059
58063
  // src/launcher/identity.ts
58060
58064
  var import_node_path10 = __toESM(require("node:path"), 1);
58065
+ var IDENTITY_DECISION_SOURCES = [
58066
+ /** `CLAUDE_CONFIG_DIR` was already set: identity resolution is skipped entirely and the real binary uses whatever it already points to. */
58067
+ "config-dir-escape-hatch",
58068
+ /** A leading `@name` argv[0] positional, or its explicit form `--identity <name>`. */
58069
+ "argv",
58070
+ /** The `AGENT_SHIM_IDENTITY` environment variable. */
58071
+ "env",
58072
+ /** A directory rule pinning an identity to the current path. */
58073
+ "directory-pin",
58074
+ /** The persisted `~/.agent-shim/active-identity` file. */
58075
+ "active-identity-file",
58076
+ /** Nothing resolved an identity at all — a bare launch with no active identity. */
58077
+ "none"
58078
+ ];
58061
58079
  function poolNameOf(selector) {
58062
58080
  return selector.startsWith(POOL_SELECTOR_PREFIX) ? selector.slice(POOL_SELECTOR_PREFIX.length) : void 0;
58063
58081
  }
@@ -58087,6 +58105,20 @@ function decideIdentity(params) {
58087
58105
  }
58088
58106
  return { source: "none", configDirEscapeHatch: false };
58089
58107
  }
58108
+ var CONFIG_PROFILE_DECISION_SOURCES = [
58109
+ /** An explicit `--config-profile` CLI flag. */
58110
+ "cli-flag",
58111
+ /** The `AGENT_SHIM_CONFIG_PROFILE` environment variable. */
58112
+ "env",
58113
+ /** A directory rule's `configProfile` selection for `$PWD`. */
58114
+ "directory-rule",
58115
+ /** The active identity's own declared `defaultConfigProfile`. */
58116
+ "identity-default",
58117
+ /** The user-global `~/.agent-shim/config.json` default. */
58118
+ "global-default",
58119
+ /** Nothing resolved a configuration profile at all. */
58120
+ "none"
58121
+ ];
58090
58122
  function decideConfigProfile(params) {
58091
58123
  if (isNonEmpty(params.cliFlagConfigProfile)) {
58092
58124
  return { name: params.cliFlagConfigProfile, source: "cli-flag" };
@@ -59114,6 +59146,12 @@ function encodeProjectPattern(fragment, options) {
59114
59146
  }
59115
59147
  return splitOnWildcards(expanded).map((piece) => piece.kind === "literal" ? encodeProjectPath(piece.text) : piece.text).join("");
59116
59148
  }
59149
+ var ENCODING_AMBIGUITY_REASONS = [
59150
+ /** The literal portion contains a character other than `/` that encodes to `-`, so a sibling path differing only in that character encodes identically. */
59151
+ "lossy-characters",
59152
+ /** Two different patterns in the same configuration encode to the identical form. */
59153
+ "collides-with-sibling-pattern"
59154
+ ];
59117
59155
  function lossyCharacters(literal2) {
59118
59156
  const found = /* @__PURE__ */ new Set();
59119
59157
  for (const character of literal2) {
@@ -60244,6 +60282,7 @@ function buildLayoutPaths(root) {
60244
60282
  frontdoorCaCertFile: import_node_path19.default.join(root, "frontdoor", "ca", "ca.pem"),
60245
60283
  frontdoorCaKeyFile: import_node_path19.default.join(root, "frontdoor", "ca", "ca.key"),
60246
60284
  frontdoorCaBundlesDir: import_node_path19.default.join(root, "frontdoor", "ca", "bundles"),
60285
+ chatgptSignInFile: import_node_path19.default.join(root, "codex", "chatgpt-sign-in.json"),
60247
60286
  frontdoorStateFile: import_node_path19.default.join(root, "frontdoor", "state.json"),
60248
60287
  frontdoorLockFile: import_node_path19.default.join(root, "frontdoor", "start.lock"),
60249
60288
  frontdoorControlTokenFile: import_node_path19.default.join(root, "frontdoor", "control-token"),
@@ -61710,7 +61749,7 @@ function registerIdentityCommand(program2, deps) {
61710
61749
  // package.json
61711
61750
  var package_default = {
61712
61751
  name: "agent-shim",
61713
- version: "8.14.1",
61752
+ version: "8.16.0",
61714
61753
  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.",
61715
61754
  license: "MIT",
61716
61755
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -62140,11 +62179,11 @@ function providerBaseUrl(port, provider) {
62140
62179
  function directOrigin(port) {
62141
62180
  return `http://127.0.0.1:${String(port)}`;
62142
62181
  }
62143
- function parseProviderPath(path43) {
62144
- if (!path43.startsWith(PROVIDER_PATH_PREFIX)) {
62182
+ function parseProviderPath(path44) {
62183
+ if (!path44.startsWith(PROVIDER_PATH_PREFIX)) {
62145
62184
  return void 0;
62146
62185
  }
62147
- const tail = path43.slice(PROVIDER_PATH_PREFIX.length);
62186
+ const tail = path44.slice(PROVIDER_PATH_PREFIX.length);
62148
62187
  const slash = tail.indexOf("/");
62149
62188
  if (slash <= 0) {
62150
62189
  return void 0;
@@ -62544,9 +62583,9 @@ function decoderFor(encoding) {
62544
62583
  return void 0;
62545
62584
  }
62546
62585
  }
62547
- function destinationOf(path43) {
62548
- const scoped = parseProviderPath(path43);
62549
- return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path43 } : { provider: scoped.provider, endpoint: scoped.rest };
62586
+ function destinationOf(path44) {
62587
+ const scoped = parseProviderPath(path44);
62588
+ return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path44 } : { provider: scoped.provider, endpoint: scoped.rest };
62550
62589
  }
62551
62590
  function buildRecord(event, context) {
62552
62591
  const { scan } = context;
@@ -63450,7 +63489,7 @@ var ProviderKindMismatchError = class extends UsageError {
63450
63489
  }
63451
63490
  };
63452
63491
  function isEmptyCodexConfig(config2) {
63453
- return config2 === void 0 || config2.defaultModel === void 0 && config2.effort === void 0 && (config2.models === void 0 || Object.keys(config2.models).length === 0);
63492
+ return config2 === void 0 || config2.defaultModel === void 0 && config2.effort === void 0 && config2.login === void 0 && (config2.models === void 0 || Object.keys(config2.models).length === 0);
63454
63493
  }
63455
63494
  function addProvider(paths, name, input2) {
63456
63495
  if (providerExists(paths, name)) {
@@ -63591,6 +63630,7 @@ function parseEnvBool(variable, value2) {
63591
63630
  }
63592
63631
 
63593
63632
  // src/launcher/claudeVersion.ts
63633
+ var CLAUDE_VERSION_SOURCES = ["flag", "environment", "cascade"];
63594
63634
  var InvalidClaudeVersionError = class extends UsageError {
63595
63635
  constructor(value2, origin) {
63596
63636
  super(`${origin} names Claude Code version "${value2}", which is not an exact dotted-numeric version such as 2.1.220.`);
@@ -63904,7 +63944,7 @@ function formatCheckReport(report) {
63904
63944
  const { credential } = report;
63905
63945
  if (credential.provider !== void 0) {
63906
63946
  lines.push(
63907
- ` Provider ${credential.provider.name}: ${credential.provider.credential === void 0 ? `unusable: ${credential.provider.problem ?? ""}` : formatCredentialSummary(credential.provider.credential)}${credential.provider.cached === void 0 ? "" : `; ${formatCachedCredentialState(credential.provider.cached)}`}`
63947
+ ` Provider ${credential.provider.name}: ${credential.provider.credential === void 0 ? `unusable: ${credential.provider.problem}` : formatCredentialSummary(credential.provider.credential)}${credential.provider.cached === void 0 ? "" : `; ${formatCachedCredentialState(credential.provider.cached)}`}`
63908
63948
  );
63909
63949
  }
63910
63950
  if (credential.identity !== void 0) {
@@ -64086,7 +64126,7 @@ function registerCheckCommand(program2, deps) {
64086
64126
  }
64087
64127
 
64088
64128
  // src/codex/commands.ts
64089
- var import_node_crypto7 = require("node:crypto");
64129
+ var import_node_crypto9 = require("node:crypto");
64090
64130
  var import_node_fs11 = __toESM(require("node:fs"), 1);
64091
64131
  var import_node_os6 = __toESM(require("node:os"), 1);
64092
64132
  var import_node_path31 = __toESM(require("node:path"), 1);
@@ -64237,8 +64277,273 @@ function createCodexAuthStore(authPath, ports) {
64237
64277
  };
64238
64278
  }
64239
64279
 
64240
- // src/codex/upstream.ts
64280
+ // src/codex/siwc.ts
64241
64281
  var import_node_crypto6 = require("node:crypto");
64282
+ var SIWC_AUTHORIZE_URL = "https://auth.openai.com/api/accounts/authorize";
64283
+ var SIWC_TOKEN_URL = "https://auth.openai.com/api/accounts/oauth/token";
64284
+ var SIWC_REVOKE_URL = "https://auth.openai.com/api/accounts/oauth/revoke";
64285
+ var SIWC_ISSUER = "https://auth.openai.com";
64286
+ var SIWC_JWKS_URL = "https://auth.openai.com/.well-known/jwks.json";
64287
+ var SIWC_DYNAMIC_CLIENT_ID = "dynamic_agent_client";
64288
+ var SIWC_RESOURCE = "https://api.openai.com/v1";
64289
+ var SIWC_RESPONSES_URL = `${SIWC_RESOURCE}/responses`;
64290
+ var SIWC_SCOPES = ["openid", "profile", "email", "offline_access", "resource.invoke", "chatgpt.tokens.use.direct"];
64291
+ var SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
64292
+ var SIWC_CALLBACK_PORT = 1455;
64293
+ var SIWC_CALLBACK_PATH = "/auth/callback";
64294
+ var SIWC_RANDOM_BYTES = 32;
64295
+ var MS_PER_SECOND4 = 1e3;
64296
+ var ID_TOKEN_ALGORITHM = "RS256";
64297
+ var SiwcError = class extends Error {
64298
+ constructor(message) {
64299
+ super(message);
64300
+ this.name = "SiwcError";
64301
+ }
64302
+ };
64303
+ var SiwcInvalidGrantError = class extends SiwcError {
64304
+ constructor(message) {
64305
+ super(message);
64306
+ this.name = "SiwcInvalidGrantError";
64307
+ }
64308
+ };
64309
+ function base64Url(bytes) {
64310
+ return Buffer.from(bytes).toString("base64url");
64311
+ }
64312
+ function newPkce(randomBytes4) {
64313
+ const verifier = base64Url(randomBytes4(SIWC_RANDOM_BYTES));
64314
+ return { verifier, challenge: (0, import_node_crypto6.createHash)("sha256").update(verifier).digest("base64url") };
64315
+ }
64316
+ function newOpaqueValue(randomBytes4) {
64317
+ return base64Url(randomBytes4(SIWC_RANDOM_BYTES));
64318
+ }
64319
+ function buildAuthorizeUrl(request7) {
64320
+ const url2 = new URL(SIWC_AUTHORIZE_URL);
64321
+ const params = url2.searchParams;
64322
+ params.set("client_id", request7.clientId ?? SIWC_DYNAMIC_CLIENT_ID);
64323
+ if (request7.clientId === void 0) {
64324
+ params.set("agent_name_hint", request7.agentName);
64325
+ }
64326
+ if (request7.returning !== void 0) {
64327
+ params.set("id_token_hint", request7.returning.idToken);
64328
+ if (request7.returning.loginHint !== void 0) {
64329
+ params.set("login_hint", request7.returning.loginHint);
64330
+ }
64331
+ }
64332
+ params.set("response_type", "code");
64333
+ params.set("redirect_uri", request7.redirectUri);
64334
+ params.set("scope", SIWC_SCOPES.join(" "));
64335
+ params.set("resource", SIWC_RESOURCE);
64336
+ params.set("state", request7.state);
64337
+ params.set("nonce", request7.nonce);
64338
+ params.set("code_challenge_method", "S256");
64339
+ params.set("code_challenge", request7.challenge);
64340
+ return url2.toString();
64341
+ }
64342
+ function parseCallback(url2, expectedState) {
64343
+ const params = url2.searchParams;
64344
+ const error62 = params.get("error");
64345
+ if (error62 !== null) {
64346
+ throw new SiwcError(`the sign-in was refused: ${error62}${params.has("error_description") ? ` (${params.get("error_description") ?? ""})` : ""}`);
64347
+ }
64348
+ if (params.get("state") !== expectedState) {
64349
+ throw new SiwcError("the sign-in callback's state did not match the request, so it was discarded");
64350
+ }
64351
+ const code = params.get("code");
64352
+ if (code === null || code === "") {
64353
+ throw new SiwcError("the sign-in callback carried no authorization code");
64354
+ }
64355
+ const scope = params.get("scope");
64356
+ return { code, clientId: params.get("client_id") ?? void 0, scopes: scope === null ? [] : scope.split(" ").filter((part) => part !== "") };
64357
+ }
64358
+ var TokenResponseSchema = external_exports.looseObject({
64359
+ access_token: external_exports.string().min(1),
64360
+ refresh_token: external_exports.string().min(1).optional(),
64361
+ id_token: external_exports.string().min(1).optional(),
64362
+ expires_in: external_exports.number().positive(),
64363
+ scope: external_exports.string().optional()
64364
+ });
64365
+ var ERROR_BODY_CHARS = 300;
64366
+ var TOKEN_CALL_TIMEOUT_MS = 3e4;
64367
+ async function postToken(ports, form, what) {
64368
+ const response = await ports.fetch(SIWC_TOKEN_URL, {
64369
+ method: "POST",
64370
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
64371
+ body: new URLSearchParams({ ...form, resource: SIWC_RESOURCE }).toString(),
64372
+ signal: AbortSignal.timeout(TOKEN_CALL_TIMEOUT_MS)
64373
+ });
64374
+ if (!response.ok) {
64375
+ const detail = (await response.text()).slice(0, ERROR_BODY_CHARS);
64376
+ const message = `the ${what} failed with HTTP ${String(response.status)}: ${detail}`;
64377
+ throw /"error"\s*:\s*"invalid_grant"/.test(detail) ? new SiwcInvalidGrantError(message) : new SiwcError(message);
64378
+ }
64379
+ const parsed = TokenResponseSchema.safeParse(await response.json());
64380
+ if (!parsed.success) {
64381
+ throw new SiwcError(`the ${what} answered without an access token and a lifetime`);
64382
+ }
64383
+ return parsed.data;
64384
+ }
64385
+ function grantTokens(ports, answer) {
64386
+ return {
64387
+ accessToken: answer.access_token,
64388
+ refreshToken: answer.refresh_token,
64389
+ idToken: answer.id_token,
64390
+ scopes: answer.scope === void 0 ? void 0 : answer.scope.split(" ").filter((part) => part !== ""),
64391
+ expiresAt: ports.now().getTime() + answer.expires_in * MS_PER_SECOND4
64392
+ };
64393
+ }
64394
+ async function exchangeCode(ports, request7) {
64395
+ return grantTokens(
64396
+ ports,
64397
+ await postToken(ports, { grant_type: "authorization_code", client_id: request7.clientId, code: request7.code, code_verifier: request7.verifier, redirect_uri: request7.redirectUri }, "authorisation code exchange")
64398
+ );
64399
+ }
64400
+ async function refreshTokens(ports, request7) {
64401
+ return grantTokens(ports, await postToken(ports, { grant_type: "refresh_token", client_id: request7.clientId, refresh_token: request7.refreshToken }, "token refresh"));
64402
+ }
64403
+ var JwtHeaderSchema = external_exports.looseObject({ alg: external_exports.string(), kid: external_exports.string().optional() });
64404
+ var IdTokenClaimsSchema = external_exports.looseObject({
64405
+ iss: external_exports.string(),
64406
+ sub: external_exports.string().min(1),
64407
+ aud: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]),
64408
+ exp: external_exports.number(),
64409
+ nonce: external_exports.string().optional(),
64410
+ email: external_exports.string().optional()
64411
+ });
64412
+ var JwksSchema = external_exports.object({ keys: external_exports.array(external_exports.looseObject({ kid: external_exports.string().optional(), kty: external_exports.string() })) });
64413
+ function decodeSegment(segment) {
64414
+ if (segment === void 0) {
64415
+ throw new SiwcError("the ID token is not a three-part JWT");
64416
+ }
64417
+ try {
64418
+ const parsed = JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
64419
+ return parsed;
64420
+ } catch {
64421
+ throw new SiwcError("the ID token has an unreadable segment");
64422
+ }
64423
+ }
64424
+ async function verifyIdToken(ports, idToken, expected) {
64425
+ const [headerSegment, payloadSegment, signatureSegment, ...rest] = idToken.split(".");
64426
+ if (rest.length > 0 || headerSegment === void 0 || payloadSegment === void 0 || signatureSegment === void 0) {
64427
+ throw new SiwcError("the ID token is not a three-part JWT");
64428
+ }
64429
+ const header = JwtHeaderSchema.parse(decodeSegment(headerSegment));
64430
+ if (header.alg !== ID_TOKEN_ALGORITHM) {
64431
+ throw new SiwcError(`the ID token is signed with ${header.alg}, and only ${ID_TOKEN_ALGORITHM} is accepted`);
64432
+ }
64433
+ const response = await ports.fetch(SIWC_JWKS_URL, { method: "GET", headers: {}, signal: AbortSignal.timeout(TOKEN_CALL_TIMEOUT_MS) });
64434
+ if (!response.ok) {
64435
+ throw new SiwcError(`the issuer's key set could not be fetched (HTTP ${String(response.status)})`);
64436
+ }
64437
+ const jwk = JwksSchema.parse(await response.json()).keys.find((key) => key.kty === "RSA" && (header.kid === void 0 || key.kid === header.kid));
64438
+ if (jwk === void 0) {
64439
+ throw new SiwcError("the issuer's key set has no key for the ID token's signature");
64440
+ }
64441
+ const signed = Buffer.from(`${headerSegment}.${payloadSegment}`);
64442
+ if (!(0, import_node_crypto6.verify)("sha256", signed, (0, import_node_crypto6.createPublicKey)({ key: jwk, format: "jwk" }), Buffer.from(signatureSegment, "base64url"))) {
64443
+ throw new SiwcError("the ID token's signature did not verify");
64444
+ }
64445
+ const claims = IdTokenClaimsSchema.parse(decodeSegment(payloadSegment));
64446
+ if (claims.iss !== SIWC_ISSUER) {
64447
+ throw new SiwcError(`the ID token was issued by ${claims.iss}, not ${SIWC_ISSUER}`);
64448
+ }
64449
+ if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expected.clientId)) {
64450
+ throw new SiwcError("the ID token was issued for a different client");
64451
+ }
64452
+ if (claims.exp * MS_PER_SECOND4 <= ports.now().getTime()) {
64453
+ throw new SiwcError("the ID token has already expired");
64454
+ }
64455
+ if (expected.nonce !== void 0 && claims.nonce !== expected.nonce) {
64456
+ throw new SiwcError("the ID token's nonce did not match the request");
64457
+ }
64458
+ return { sub: claims.sub, email: claims.email };
64459
+ }
64460
+
64461
+ // src/codex/siwcLogin.ts
64462
+ var SIWC_AGENT_NAME = "agent-shim";
64463
+ var SIWC_LOGIN_TIMEOUT_MS = 3e5;
64464
+ async function runSiwcLogin(ports, options) {
64465
+ const existing = ports.store.read();
64466
+ const returning = existing?.grant;
64467
+ for (let attempt = 0; ; attempt += 1) {
64468
+ const clientId = ports.store.read()?.registeredClientId ?? returning?.clientId;
64469
+ try {
64470
+ return await authorizeOnce(ports, options, clientId, attempt === 0 ? returning : void 0);
64471
+ } catch (error62) {
64472
+ if (!(error62 instanceof SiwcInvalidGrantError) || attempt > 0) {
64473
+ throw error62;
64474
+ }
64475
+ ports.print("OpenAI did not accept the first code, which is expected once after registering: authorising again with the registration it issued.");
64476
+ }
64477
+ }
64478
+ }
64479
+ async function authorizeOnce(ports, options, savedClientId, returning) {
64480
+ const pkce = newPkce(ports.siwc.randomBytes);
64481
+ const state = newOpaqueValue(ports.siwc.randomBytes);
64482
+ const nonce = newOpaqueValue(ports.siwc.randomBytes);
64483
+ const redirectUri = `http://127.0.0.1:${String(SIWC_CALLBACK_PORT)}${SIWC_CALLBACK_PATH}`;
64484
+ const url2 = buildAuthorizeUrl({
64485
+ clientId: savedClientId,
64486
+ agentName: SIWC_AGENT_NAME,
64487
+ redirectUri,
64488
+ state,
64489
+ nonce,
64490
+ challenge: pkce.challenge,
64491
+ ...returning === void 0 ? {} : { returning: { idToken: returning.idToken, loginHint: returning.email } }
64492
+ });
64493
+ const listener = await ports.listen(SIWC_CALLBACK_PORT, state);
64494
+ try {
64495
+ ports.print(`Sign in at: ${url2}`);
64496
+ if (options.open) {
64497
+ ports.openBrowser(url2);
64498
+ }
64499
+ const callback = parseCallback(await listener.waitForCallback(AbortSignal.timeout(SIWC_LOGIN_TIMEOUT_MS)), state);
64500
+ const clientId = callback.clientId ?? savedClientId;
64501
+ if (clientId === void 0) {
64502
+ throw new SiwcError("the sign-in callback carried no client id and none was stored from an earlier sign-in");
64503
+ }
64504
+ const grantBefore = ports.store.read()?.grant;
64505
+ ports.store.write({ registeredClientId: clientId, ...grantBefore === void 0 ? {} : { grant: grantBefore } });
64506
+ const tokens = await exchangeCode(ports.siwc, { clientId, code: callback.code, verifier: pkce.verifier, redirectUri });
64507
+ if (tokens.refreshToken === void 0 || tokens.idToken === void 0) {
64508
+ throw new SiwcError("the token endpoint did not return a refresh token and an ID token, so the sign-in cannot be kept");
64509
+ }
64510
+ const scopes = tokens.scopes ?? callback.scopes;
64511
+ if (!scopes.includes(SIWC_PLAN_SCOPE)) {
64512
+ throw new SiwcError("the sign-in was not granted permission to use your ChatGPT plan: run the login again and allow it");
64513
+ }
64514
+ const identity = await verifyIdToken(ports.siwc, tokens.idToken, { clientId, nonce });
64515
+ ports.store.write({
64516
+ registeredClientId: clientId,
64517
+ grant: { clientId, sub: identity.sub, ...identity.email === void 0 ? {} : { email: identity.email }, idToken: tokens.idToken, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken, scopes, expiresAt: tokens.expiresAt }
64518
+ });
64519
+ return { email: identity.email, sub: identity.sub };
64520
+ } finally {
64521
+ listener.close();
64522
+ }
64523
+ }
64524
+ var REVOKE_TIMEOUT_MS = 3e4;
64525
+ async function runSiwcLogout(ports) {
64526
+ const file2 = ports.store.read();
64527
+ if (file2?.grant === void 0) {
64528
+ return { hadGrant: false, revoked: false };
64529
+ }
64530
+ const revoked = await ports.siwc.fetch(SIWC_REVOKE_URL, {
64531
+ method: "POST",
64532
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
64533
+ body: new URLSearchParams({ token: file2.grant.refreshToken, token_type_hint: "refresh_token", client_id: file2.grant.clientId }).toString(),
64534
+ signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS)
64535
+ }).then(
64536
+ (response) => response.ok,
64537
+ () => false
64538
+ );
64539
+ ports.store.write({ registeredClientId: file2.grant.clientId });
64540
+ return { hadGrant: true, revoked };
64541
+ }
64542
+
64543
+ // src/codex/siwcPorts.ts
64544
+ var import_node_child_process4 = require("node:child_process");
64545
+ var import_node_crypto7 = require("node:crypto");
64546
+ var import_node_http = __toESM(require("node:http"), 1);
64242
64547
 
64243
64548
  // src/codex/http.ts
64244
64549
  var HTTP_STATUS = {
@@ -64256,7 +64561,157 @@ var HTTP_STATUS = {
64256
64561
  badGateway: 502
64257
64562
  };
64258
64563
 
64564
+ // src/codex/siwcPorts.ts
64565
+ function realSiwcPorts(fetch3) {
64566
+ return { fetch: fetch3, randomBytes: (size) => (0, import_node_crypto7.randomBytes)(size), now: () => /* @__PURE__ */ new Date() };
64567
+ }
64568
+ var CALLBACK_PAGE = "<!doctype html><meta charset=utf-8><title>Signed in</title><p>You can close this tab and return to the terminal.</p>";
64569
+ async function listenForCallback(port, state) {
64570
+ let deliver;
64571
+ const arrived = new Promise((resolve) => {
64572
+ deliver = resolve;
64573
+ });
64574
+ const server = import_node_http.default.createServer((request7, response) => {
64575
+ const url2 = new URL(request7.url ?? "/", `http://127.0.0.1:${String(port)}`);
64576
+ if (request7.method !== "GET" || url2.pathname !== SIWC_CALLBACK_PATH || url2.searchParams.getAll("state").length !== 1 || url2.searchParams.get("state") !== state) {
64577
+ response.writeHead(HTTP_STATUS.notFound).end("Not found");
64578
+ return;
64579
+ }
64580
+ response.writeHead(HTTP_STATUS.ok, { "Content-Type": "text/html; charset=utf-8" });
64581
+ response.end(CALLBACK_PAGE);
64582
+ deliver?.(url2);
64583
+ });
64584
+ await new Promise((resolve, reject) => {
64585
+ server.once("error", (error62) => {
64586
+ reject(error62.code === "EADDRINUSE" ? new Error(`port ${String(port)} is in use (another sign-in, such as \`codex login\`, may be running): finish or stop it and try again`) : error62);
64587
+ });
64588
+ server.listen(port, "127.0.0.1", () => {
64589
+ resolve();
64590
+ });
64591
+ });
64592
+ return {
64593
+ waitForCallback: async (signal) => await Promise.race([
64594
+ arrived,
64595
+ new Promise((_resolve, reject) => {
64596
+ signal.addEventListener("abort", () => {
64597
+ reject(new Error("timed out waiting for the browser sign-in to finish"));
64598
+ });
64599
+ })
64600
+ ]),
64601
+ close: () => {
64602
+ server.close();
64603
+ server.closeAllConnections();
64604
+ }
64605
+ };
64606
+ }
64607
+ function openInBrowser(url2) {
64608
+ const command = process.platform === "darwin" ? { file: "open", args: [url2] } : process.platform === "win32" ? { file: "cmd", args: ["/c", "start", "", url2] } : { file: "xdg-open", args: [url2] };
64609
+ (0, import_node_child_process4.spawn)(command.file, command.args, { detached: true, stdio: "ignore" }).unref();
64610
+ }
64611
+
64612
+ // src/codex/siwcStore.ts
64613
+ var SiwcGrantSchema = external_exports.strictObject({
64614
+ clientId: external_exports.string().min(1),
64615
+ sub: external_exports.string().min(1),
64616
+ email: external_exports.string().optional(),
64617
+ idToken: external_exports.string().min(1),
64618
+ accessToken: external_exports.string().min(1),
64619
+ refreshToken: external_exports.string().min(1),
64620
+ scopes: external_exports.array(external_exports.string()).readonly(),
64621
+ /** When the access token stops working, in milliseconds since the epoch. */
64622
+ expiresAt: external_exports.number()
64623
+ });
64624
+ var SiwcFileSchema = external_exports.strictObject({ registeredClientId: external_exports.string().min(1).optional(), grant: SiwcGrantSchema.optional() });
64625
+ var SIWC_REFRESH_MARGIN_MS = 6e4;
64626
+ function parseSiwcFile(raw, filePath) {
64627
+ let json2;
64628
+ try {
64629
+ json2 = JSON.parse(raw);
64630
+ } catch {
64631
+ throw new CodexAuthError(`${filePath} is not valid JSON: run \`agent-shim codex login\` again`);
64632
+ }
64633
+ const parsed = SiwcFileSchema.safeParse(json2);
64634
+ if (!parsed.success) {
64635
+ throw new CodexAuthError(`${filePath} is not a Sign in with ChatGPT file: run \`agent-shim codex login\` again`);
64636
+ }
64637
+ return parsed.data;
64638
+ }
64639
+ function grantFrom(previous, tokens) {
64640
+ return {
64641
+ ...previous,
64642
+ accessToken: tokens.accessToken,
64643
+ refreshToken: tokens.refreshToken ?? previous.refreshToken,
64644
+ idToken: tokens.idToken ?? previous.idToken,
64645
+ scopes: tokens.scopes ?? previous.scopes,
64646
+ expiresAt: tokens.expiresAt
64647
+ };
64648
+ }
64649
+ function createSiwcStore(filePath, ports) {
64650
+ let cached2;
64651
+ let inFlight;
64652
+ const read = () => {
64653
+ const raw = ports.fs.read(filePath);
64654
+ return raw === void 0 ? void 0 : parseSiwcFile(raw, filePath);
64655
+ };
64656
+ const write = (file2) => {
64657
+ const temp = `${filePath}.${ports.tempSuffix}.tmp`;
64658
+ ports.fs.writePrivate(temp, `${JSON.stringify(file2, null, 2)}
64659
+ `);
64660
+ ports.fs.rename(temp, filePath);
64661
+ cached2 = file2.grant;
64662
+ };
64663
+ const loadSignedIn = () => {
64664
+ const file2 = read();
64665
+ if (file2?.grant === void 0) {
64666
+ throw new CodexAuthError(`no Sign in with ChatGPT login at ${filePath}: run \`agent-shim codex login\` first`);
64667
+ }
64668
+ if (!file2.grant.scopes.includes(SIWC_PLAN_SCOPE)) {
64669
+ throw new CodexAuthError(`the Sign in with ChatGPT login at ${filePath} was not granted permission to use your ChatGPT plan: run \`agent-shim codex login\` again and allow it`);
64670
+ }
64671
+ return { file: file2, grant: file2.grant };
64672
+ };
64673
+ const credentialsOf2 = (grant) => ({ accessToken: grant.accessToken, accountId: void 0 });
64674
+ const doRefresh = async (rejected) => {
64675
+ const { file: file2, grant } = loadSignedIn();
64676
+ if (rejected !== void 0 && grant.accessToken !== rejected) {
64677
+ cached2 = grant;
64678
+ return credentialsOf2(grant);
64679
+ }
64680
+ let tokens;
64681
+ try {
64682
+ tokens = await refreshTokens(ports.siwc, { clientId: grant.clientId, refreshToken: grant.refreshToken });
64683
+ } catch (error62) {
64684
+ if (error62 instanceof SiwcError) {
64685
+ throw new CodexAuthError(`${error62.message}: run \`agent-shim codex login\` again if the login was revoked`);
64686
+ }
64687
+ throw error62;
64688
+ }
64689
+ const next = grantFrom(grant, tokens);
64690
+ write({ ...file2, grant: next });
64691
+ return credentialsOf2(next);
64692
+ };
64693
+ const refreshOnce = async (rejected) => await (inFlight ??= doRefresh(rejected).finally(() => {
64694
+ inFlight = void 0;
64695
+ }));
64696
+ return {
64697
+ read,
64698
+ write,
64699
+ auth: {
64700
+ current: async () => {
64701
+ const grant = cached2 ?? loadSignedIn().grant;
64702
+ cached2 = grant;
64703
+ if (grant.expiresAt - SIWC_REFRESH_MARGIN_MS <= ports.siwc.now().getTime()) {
64704
+ return await refreshOnce(void 0);
64705
+ }
64706
+ return credentialsOf2(grant);
64707
+ },
64708
+ refresh: async (rejected) => await refreshOnce(rejected)
64709
+ }
64710
+ };
64711
+ }
64712
+
64259
64713
  // src/codex/upstream.ts
64714
+ var import_node_crypto8 = require("node:crypto");
64260
64715
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
64261
64716
  var CODEX_UPSTREAM_TIMEOUT_MS = 3e5;
64262
64717
  var CODEX_HEADERS_TIMEOUT_MS = 15e3;
@@ -64292,12 +64747,17 @@ function sessionIdFor(userId, randomId) {
64292
64747
  if (userId === void 0 || userId === "") {
64293
64748
  return randomId();
64294
64749
  }
64295
- const hex3 = (0, import_node_crypto6.createHash)("sha256").update(`agent-shim codex session
64750
+ const hex3 = (0, import_node_crypto8.createHash)("sha256").update(`agent-shim codex session
64296
64751
  ${userId}`).digest("hex");
64297
64752
  let next = 0;
64298
64753
  return UUID_TEMPLATE.replace(/x/g, () => hex3.charAt(next++));
64299
64754
  }
64300
- function headersFor(credentials, sessionId) {
64755
+ var CODEX_BACKEND_TARGET = { url: CODEX_RESPONSES_URL, headers: codexBackendHeaders };
64756
+ var RESPONSES_API_TARGET = {
64757
+ url: SIWC_RESPONSES_URL,
64758
+ headers: (credentials) => ({ "Content-Type": "application/json", Accept: "text/event-stream", Authorization: `Bearer ${credentials.accessToken}` })
64759
+ };
64760
+ function codexBackendHeaders(credentials, sessionId) {
64301
64761
  return {
64302
64762
  "Content-Type": "application/json",
64303
64763
  Accept: "text/event-stream",
@@ -64309,11 +64769,11 @@ function headersFor(credentials, sessionId) {
64309
64769
  };
64310
64770
  }
64311
64771
  async function callCodex(ports, request7, sessionId, signal) {
64312
- const url2 = ports.url ?? CODEX_RESPONSES_URL;
64772
+ const target = ports.target ?? CODEX_BACKEND_TARGET;
64313
64773
  const body = JSON.stringify(request7);
64314
- const send = async (credentials2) => await fetchUntilHeaders(ports.fetch, ports.timers, url2, {
64774
+ const send = async (credentials2) => await fetchUntilHeaders(ports.fetch, ports.timers, target.url, {
64315
64775
  method: "POST",
64316
- headers: headersFor(credentials2, sessionId),
64776
+ headers: target.headers(credentials2, sessionId),
64317
64777
  body,
64318
64778
  signal: AbortSignal.any([signal, AbortSignal.timeout(CODEX_UPSTREAM_TIMEOUT_MS)])
64319
64779
  });
@@ -64349,6 +64809,7 @@ var realCodexAuthFs = {
64349
64809
  }
64350
64810
  },
64351
64811
  writePrivate: (filePath, contents) => {
64812
+ import_node_fs11.default.mkdirSync(import_node_path31.default.dirname(filePath), { recursive: true });
64352
64813
  import_node_fs11.default.writeFileSync(filePath, contents, { encoding: "utf8", mode: PRIVATE_FILE_MODE });
64353
64814
  import_node_fs11.default.chmodSync(filePath, PRIVATE_FILE_MODE);
64354
64815
  },
@@ -64368,17 +64829,22 @@ function writeUsageSnapshot(log, snapshot) {
64368
64829
  log(`usage snapshot write failed: ${error62 instanceof Error ? error62.message : String(error62)}`);
64369
64830
  }
64370
64831
  }
64371
- function createCodexRoutePorts(log) {
64832
+ function createCodexRoutePorts(log, signInFile) {
64372
64833
  const agent = createUpstreamAgent();
64373
64834
  const upstreamFetch = createUpstreamFetch(agent);
64835
+ const tempSuffix = `${String(process.pid)}.${(0, import_node_crypto9.randomUUID)()}`;
64374
64836
  const auth = createCodexAuthStore(import_node_path31.default.join(codexHome(process.env, import_node_os6.default.homedir()), "auth.json"), {
64375
64837
  fs: realCodexAuthFs,
64376
64838
  fetch: upstreamFetch,
64377
64839
  now: () => /* @__PURE__ */ new Date(),
64378
- tempSuffix: `${String(process.pid)}.${(0, import_node_crypto7.randomUUID)()}`
64840
+ tempSuffix
64379
64841
  });
64842
+ const signIn = createSiwcStore(signInFile, { fs: realCodexAuthFs, siwc: realSiwcPorts(upstreamFetch), tempSuffix });
64380
64843
  return {
64381
- upstream: { fetch: upstreamFetch, auth, timers: realTimers, randomId: import_node_crypto7.randomUUID },
64844
+ upstreams: {
64845
+ "codex-cli": { fetch: upstreamFetch, auth, timers: realTimers, randomId: import_node_crypto9.randomUUID },
64846
+ "chatgpt-sign-in": { fetch: upstreamFetch, auth: signIn.auth, timers: realTimers, randomId: import_node_crypto9.randomUUID, target: RESPONSES_API_TARGET }
64847
+ },
64382
64848
  writeUsageSnapshot: (snapshot) => {
64383
64849
  writeUsageSnapshot(log, snapshot);
64384
64850
  },
@@ -64386,6 +64852,18 @@ function createCodexRoutePorts(log) {
64386
64852
  log
64387
64853
  };
64388
64854
  }
64855
+ function readSignInStatus(fsPort, filePath) {
64856
+ const raw = fsPort.readFileUtf8(filePath);
64857
+ if (raw === void 0) {
64858
+ return { state: "none" };
64859
+ }
64860
+ try {
64861
+ const file2 = parseSiwcFile(raw, filePath);
64862
+ return file2.grant === void 0 ? { state: "none" } : { state: "signed-in", email: file2.grant.email, planScope: file2.grant.scopes.includes(SIWC_PLAN_SCOPE), accessTokenExpiresAt: file2.grant.expiresAt };
64863
+ } catch (error62) {
64864
+ return { state: "unreadable", message: error62 instanceof Error ? error62.message : String(error62) };
64865
+ }
64866
+ }
64389
64867
  function codexProviderNames(fsPort, providersDir) {
64390
64868
  return readAllProviders(fsPort, providersDir).filter((entry) => isCodexProvider(entry.provider)).map((entry) => entry.name).sort();
64391
64869
  }
@@ -64396,12 +64874,22 @@ function collectCodexStatus(fsPort, paths, isRunning) {
64396
64874
  supervisorAlive: state.supervisorPid !== void 0 && isRunning(state.supervisorPid),
64397
64875
  sessions: listFrontDoorSessions(fsPort, paths.frontdoorSessionsDir).map((session) => ({ ...session, alive: isRunning(session.pid) })),
64398
64876
  codexProviders: codexProviderNames(fsPort, paths.providersDir),
64877
+ signIn: readSignInStatus(fsPort, paths.chatgptSignInFile),
64399
64878
  usageSnapshotPath: codexUsageSnapshotPath(),
64400
64879
  usageSnapshotExists: fsPort.readFileUtf8(codexUsageSnapshotPath()) !== void 0,
64401
64880
  logPath: paths.frontdoorLogPath,
64402
64881
  logExists: fsPort.readFileUtf8(paths.frontdoorLogPath) !== void 0
64403
64882
  };
64404
64883
  }
64884
+ function formatSignIn(signIn) {
64885
+ if (signIn.state === "none") {
64886
+ return "chatgpt sign-in: not signed in (run `agent-shim codex login`)";
64887
+ }
64888
+ if (signIn.state === "unreadable") {
64889
+ return `chatgpt sign-in: ${signIn.message}`;
64890
+ }
64891
+ return `chatgpt sign-in: signed in${signIn.email === void 0 ? "" : ` as ${signIn.email}`}${signIn.planScope ? "" : ", WITHOUT permission to use your ChatGPT plan (run `agent-shim codex login` again and allow it)"}`;
64892
+ }
64405
64893
  function formatCodexStatus(status) {
64406
64894
  const lines = [];
64407
64895
  lines.push(
@@ -64422,10 +64910,24 @@ function formatCodexStatus(status) {
64422
64910
  if (status.frontDoor.lastError !== void 0) {
64423
64911
  lines.push(`last error: ${status.frontDoor.lastError}`);
64424
64912
  }
64913
+ lines.push(formatSignIn(status.signIn));
64425
64914
  lines.push(`usage snapshot: ${status.usageSnapshotPath}${status.usageSnapshotExists ? "" : " (not created yet)"}`);
64426
64915
  lines.push(`daemon log: ${status.logPath}${status.logExists ? "" : " (not created yet)"}`);
64427
64916
  return lines;
64428
64917
  }
64918
+ function realSiwcLoginPorts(paths) {
64919
+ const siwc = realSiwcPorts(createUpstreamFetch(createUpstreamAgent()));
64920
+ const store = createSiwcStore(paths.chatgptSignInFile, { fs: realCodexAuthFs, siwc, tempSuffix: `${String(process.pid)}.${(0, import_node_crypto9.randomUUID)()}` });
64921
+ return {
64922
+ store,
64923
+ siwc,
64924
+ listen: listenForCallback,
64925
+ openBrowser: openInBrowser,
64926
+ print: (line) => {
64927
+ console.log(line);
64928
+ }
64929
+ };
64930
+ }
64429
64931
  function registerCodexCommand(program2, deps) {
64430
64932
  const { paths } = deps;
64431
64933
  const codex = withExamples(program2.command("codex").description("Inspect the codex translation the front-door daemon serves for codex providers."), ["agent-shim codex status"]);
@@ -64442,12 +64944,40 @@ function registerCodexCommand(program2, deps) {
64442
64944
  }),
64443
64945
  ["agent-shim codex status", "agent-shim codex status --json"]
64444
64946
  );
64947
+ withExamples(
64948
+ codex.command("login").description("Sign in with ChatGPT so a codex provider with `codex.login` set to `chatgpt-sign-in` can spend your ChatGPT plan on OpenAI's public Responses API. Opens your browser.").option("--no-open", "Print the sign-in address instead of opening the browser.").option("--json", "Print the result as JSON.").action(async (options) => {
64949
+ const ports = realSiwcLoginPorts(paths);
64950
+ const result = await runSiwcLogin(options.json === true ? { ...ports, print: () => void 0 } : ports, { open: options.open });
64951
+ if (options.json === true) {
64952
+ printJson({ action: "login", email: result.email ?? null, sub: result.sub });
64953
+ return;
64954
+ }
64955
+ console.log(`Signed in${result.email === void 0 ? "" : ` as ${result.email}`}. Set "codex": { "login": "chatgpt-sign-in" } on a codex provider to use it.`);
64956
+ }),
64957
+ ["agent-shim codex login", "agent-shim codex login --no-open"]
64958
+ );
64959
+ withExamples(
64960
+ codex.command("logout").description("Revoke the Sign in with ChatGPT login and remove it from this machine.").option("--json", "Print the result as JSON.").action(async (options) => {
64961
+ const ports = realSiwcLoginPorts(paths);
64962
+ const result = await runSiwcLogout(ports);
64963
+ if (options.json === true) {
64964
+ printJson({ action: "logout", ...result });
64965
+ return;
64966
+ }
64967
+ if (!result.hadGrant) {
64968
+ console.log("Not signed in.");
64969
+ return;
64970
+ }
64971
+ console.log(result.revoked ? "Signed out and revoked the login at OpenAI." : "Signed out here, but OpenAI could not be told to revoke the login: revoke it in ChatGPT settings.");
64972
+ }),
64973
+ ["agent-shim codex logout"]
64974
+ );
64445
64975
  }
64446
64976
 
64447
64977
  // src/frontdoor/commands.ts
64448
- var import_node_crypto12 = require("node:crypto");
64449
- var import_node_path34 = __toESM(require("node:path"), 1);
64450
- var import_node_fs12 = __toESM(require("node:fs"), 1);
64978
+ var import_node_crypto14 = require("node:crypto");
64979
+ var import_node_path36 = __toESM(require("node:path"), 1);
64980
+ var import_node_fs13 = __toESM(require("node:fs"), 1);
64451
64981
 
64452
64982
  // src/frontdoor/custody.ts
64453
64983
  var CREDENTIAL_HEADERS = ["authorization", "x-api-key"];
@@ -64550,7 +65080,7 @@ function createDoorPipelines(deps) {
64550
65080
  }
64551
65081
 
64552
65082
  // src/frontdoor/capability.ts
64553
- var import_node_crypto8 = require("node:crypto");
65083
+ var import_node_crypto10 = require("node:crypto");
64554
65084
  var CONNECT_PROXY_USER = "agent-shim";
64555
65085
  var CONNECT_PROXY_REALM = "agent-shim front door";
64556
65086
  var BASIC_SCHEME = "basic";
@@ -64572,13 +65102,13 @@ function capabilityFromProxyAuthorization(value2) {
64572
65102
  return password === "" ? void 0 : password;
64573
65103
  }
64574
65104
  function digest(token) {
64575
- return (0, import_node_crypto8.createHash)("sha256").update(token, "utf8").digest();
65105
+ return (0, import_node_crypto10.createHash)("sha256").update(token, "utf8").digest();
64576
65106
  }
64577
65107
  function isLiveCapability(presented, live) {
64578
65108
  const presentedDigest = digest(presented);
64579
65109
  let matched = false;
64580
65110
  for (const token of live) {
64581
- const equal = (0, import_node_crypto8.timingSafeEqual)(presentedDigest, digest(token));
65111
+ const equal = (0, import_node_crypto10.timingSafeEqual)(presentedDigest, digest(token));
64582
65112
  matched = equal || matched;
64583
65113
  }
64584
65114
  return matched;
@@ -64722,11 +65252,11 @@ function createFileCapture(file2, now = () => /* @__PURE__ */ new Date()) {
64722
65252
  }
64723
65253
 
64724
65254
  // src/frontdoor/connect.ts
64725
- var import_node_crypto10 = require("node:crypto");
65255
+ var import_node_crypto12 = require("node:crypto");
64726
65256
  var fs13 = __toESM(require("node:fs"), 1);
64727
65257
 
64728
65258
  // src/frontdoor/x509.ts
64729
- var import_node_crypto9 = require("node:crypto");
65259
+ var import_node_crypto11 = require("node:crypto");
64730
65260
  var import_node_net = __toESM(require("node:net"), 1);
64731
65261
  var TAG_BOOLEAN = 1;
64732
65262
  var TAG_INTEGER = 2;
@@ -64762,7 +65292,7 @@ var HIGH_BIT = 128;
64762
65292
  var BASE_128_PAYLOAD_MASK = 127;
64763
65293
  var FIRST_ARC_WEIGHT = 40;
64764
65294
  var SHORT_FORM_MAX_LENGTH = 127;
64765
- var MS_PER_SECOND4 = 1e3;
65295
+ var MS_PER_SECOND5 = 1e3;
64766
65296
  var UTC_TIME_LAST_YEAR = 2049;
64767
65297
  var YEAR_DIGITS = 4;
64768
65298
  var TWO_DIGIT_YEAR_DIGITS = 2;
@@ -64821,7 +65351,7 @@ function wholeBitString(content) {
64821
65351
  return tlv(TAG_BIT_STRING, Buffer.concat([Buffer.from([0]), content]));
64822
65352
  }
64823
65353
  function time3(instant) {
64824
- const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND4) * MS_PER_SECOND4).toISOString();
65354
+ const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND5) * MS_PER_SECOND5).toISOString();
64825
65355
  const compact = `${iso.replace(/[-:T]/g, "").slice(0, COMPACT_TIME_DIGITS)}Z`;
64826
65356
  if (instant.getUTCFullYear() > UTC_TIME_LAST_YEAR) {
64827
65357
  return tlv(TAG_GENERALIZED_TIME, Buffer.from(compact, "ascii"));
@@ -64878,7 +65408,7 @@ function ipBytes(address) {
64878
65408
  return bytes;
64879
65409
  }
64880
65410
  function keyIdentifier(publicKey) {
64881
- return (0, import_node_crypto9.createHash)("sha1").update(publicKey.export({ type: "pkcs1", format: "der" })).digest();
65411
+ return (0, import_node_crypto11.createHash)("sha1").update(publicKey.export({ type: "pkcs1", format: "der" })).digest();
64882
65412
  }
64883
65413
  function readElement(buffer, offset) {
64884
65414
  const tag = buffer[offset];
@@ -64924,7 +65454,7 @@ ${body.join("\n")}
64924
65454
  `;
64925
65455
  }
64926
65456
  function randomSerial() {
64927
- const bytes = (0, import_node_crypto9.randomBytes)(SERIAL_NUMBER_BYTES);
65457
+ const bytes = (0, import_node_crypto11.randomBytes)(SERIAL_NUMBER_BYTES);
64928
65458
  bytes[0] = (bytes[0] ?? 0) & BASE_128_PAYLOAD_MASK | HIGH_BIT >> 1;
64929
65459
  return bytes;
64930
65460
  }
@@ -64939,7 +65469,7 @@ function assemble(spec) {
64939
65469
  spec.subjectPublicKey.export({ type: "spki", format: "der" }),
64940
65470
  tlv(TAG_EXTENSIONS, sequence(...spec.extensions))
64941
65471
  );
64942
- const signature = (0, import_node_crypto9.sign)("sha256", tbs, spec.signingKey);
65472
+ const signature = (0, import_node_crypto11.sign)("sha256", tbs, spec.signingKey);
64943
65473
  return sequence(tbs, SIGNATURE_ALGORITHM, wholeBitString(signature));
64944
65474
  }
64945
65475
  function subjectKeyIdentifierExtension(publicKey) {
@@ -64949,7 +65479,7 @@ function basicConstraintsExtension(isCa) {
64949
65479
  return extension(OID_BASIC_CONSTRAINTS, true, sequence(...isCa ? [boolean4(true)] : []));
64950
65480
  }
64951
65481
  function rsaKeyPair() {
64952
- return (0, import_node_crypto9.generateKeyPairSync)("rsa", { modulusLength: RSA_MODULUS_BITS });
65482
+ return (0, import_node_crypto11.generateKeyPairSync)("rsa", { modulusLength: RSA_MODULUS_BITS });
64953
65483
  }
64954
65484
  function keyPem(privateKey) {
64955
65485
  return privateKey.export({ type: "pkcs8", format: "pem" });
@@ -64973,8 +65503,8 @@ function issueLeafCertificate(ca, names, notBefore, notAfter) {
64973
65503
  if (commonName === void 0) {
64974
65504
  throw new Error("a leaf certificate needs at least one name");
64975
65505
  }
64976
- const caCertificate = new import_node_crypto9.X509Certificate(ca.certPem);
64977
- const caPrivateKey = (0, import_node_crypto9.createPrivateKey)(ca.keyPem);
65506
+ const caCertificate = new import_node_crypto11.X509Certificate(ca.certPem);
65507
+ const caPrivateKey = (0, import_node_crypto11.createPrivateKey)(ca.keyPem);
64978
65508
  const { publicKey, privateKey } = rsaKeyPair();
64979
65509
  const generalNames = names.map((name) => import_node_net.default.isIP(name) === 0 ? tlv(TAG_GENERAL_NAME_DNS, Buffer.from(name, "ascii")) : tlv(TAG_GENERAL_NAME_IP, ipBytes(name)));
64980
65510
  const der = assemble({
@@ -65071,22 +65601,22 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65071
65601
  };
65072
65602
  writeFrontDoorState(fs19, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
65073
65603
  const previousSticky = lastPort;
65074
- let http6;
65604
+ let http7;
65075
65605
  try {
65076
- http6 = await ports.startProviderListener(lastPort);
65606
+ http7 = await ports.startProviderListener(lastPort);
65077
65607
  } catch (error62) {
65078
65608
  return fail(`could not start the provider listener: ${error62 instanceof Error ? error62.message : String(error62)}`);
65079
65609
  }
65080
- if (previousSticky !== void 0 && http6.port !== previousSticky) {
65081
- ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http6.port)} (sessions launched against the old port are stale until they relaunch)`);
65610
+ if (previousSticky !== void 0 && http7.port !== previousSticky) {
65611
+ ports.log(`agent-shim frontdoor supervisor: sticky port ${String(previousSticky)} was occupied; moving to ${String(http7.port)} (sessions launched against the old port are stale until they relaunch)`);
65082
65612
  }
65083
- lastPort = http6.port;
65613
+ lastPort = http7.port;
65084
65614
  const previousStickyConnect = lastConnectPort;
65085
65615
  let connect3;
65086
65616
  try {
65087
65617
  connect3 = await ports.startConnectListener(lastConnectPort);
65088
65618
  } catch (error62) {
65089
- await http6.close();
65619
+ await http7.close();
65090
65620
  return fail(`could not start the CONNECT surface: ${error62 instanceof Error ? error62.message : String(error62)}`);
65091
65621
  }
65092
65622
  if (previousStickyConnect !== void 0 && connect3.port !== previousStickyConnect) {
@@ -65099,16 +65629,16 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65099
65629
  direct = await ports.startDirectListener(lastDirectPort);
65100
65630
  } catch (error62) {
65101
65631
  await connect3.close();
65102
- await http6.close();
65632
+ await http7.close();
65103
65633
  return fail(`could not start the direct listener: ${error62 instanceof Error ? error62.message : String(error62)}`);
65104
65634
  }
65105
65635
  if (previousStickyDirect !== void 0 && direct.port !== previousStickyDirect) {
65106
65636
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom must be restarted to admit the new address)`);
65107
65637
  }
65108
65638
  lastDirectPort = direct.port;
65109
- writeFrontDoorState(fs19, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http6.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
65639
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http7.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
65110
65640
  fs19.removeRecursive(paths.frontdoorLockFile);
65111
- ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http6.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
65641
+ ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http7.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
65112
65642
  let idleSince;
65113
65643
  let ticks = 0;
65114
65644
  for (; ; ) {
@@ -65116,14 +65646,17 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
65116
65646
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
65117
65647
  }
65118
65648
  ticks += 1;
65119
- pruneDeadFrontDoorSessions(fs19, paths.frontdoorSessionsDir, ports.isRunning);
65120
- if (listFrontDoorSessions(fs19, paths.frontdoorSessionsDir).length === 0) {
65649
+ const listed = listFrontDoorSessions(fs19, paths.frontdoorSessionsDir);
65650
+ const pruned = pruneDeadFrontDoorSessions(fs19, paths.frontdoorSessionsDir, ports.isRunning);
65651
+ ports.observeLaunchRegistry(listed, pruned);
65652
+ const prunedPids = new Set(pruned);
65653
+ if (listed.filter((session) => !prunedPids.has(session.pid)).length === 0) {
65121
65654
  idleSince ??= ports.now();
65122
65655
  if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE2) {
65123
65656
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
65124
65657
  await direct.close();
65125
65658
  await connect3.close();
65126
- await http6.close();
65659
+ await http7.close();
65127
65660
  ports.closeRcStreamHub();
65128
65661
  writeFrontDoorState(fs19, paths.frontdoorStateFile, sticky());
65129
65662
  return 0;
@@ -65178,8 +65711,8 @@ function parseConnectTarget(authority) {
65178
65711
  }
65179
65712
  return { host, port };
65180
65713
  }
65181
- function servedByPipeline(path43) {
65182
- return path43?.startsWith(ROUTED_PATH_PREFIX) === true;
65714
+ function servedByPipeline(path44) {
65715
+ return path44?.startsWith(ROUTED_PATH_PREFIX) === true;
65183
65716
  }
65184
65717
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
65185
65718
  "connection",
@@ -65239,8 +65772,8 @@ function ensureCa(store, generate) {
65239
65772
  }
65240
65773
  function caParses(ca) {
65241
65774
  try {
65242
- new import_node_crypto10.X509Certificate(ca.certPem);
65243
- (0, import_node_crypto10.createPrivateKey)(ca.keyPem);
65775
+ new import_node_crypto12.X509Certificate(ca.certPem);
65776
+ (0, import_node_crypto12.createPrivateKey)(ca.keyPem);
65244
65777
  return true;
65245
65778
  } catch {
65246
65779
  return false;
@@ -65528,13 +66061,13 @@ function realConnectCertStore(paths) {
65528
66061
 
65529
66062
  // src/frontdoor/connectEffects.ts
65530
66063
  var import_node_dns = __toESM(require("node:dns"), 1);
65531
- var http2 = __toESM(require("node:http"), 1);
66064
+ var http3 = __toESM(require("node:http"), 1);
65532
66065
  var https3 = __toESM(require("node:https"), 1);
65533
66066
  var net2 = __toESM(require("node:net"), 1);
65534
66067
  var tls = __toESM(require("node:tls"), 1);
65535
66068
 
65536
66069
  // src/frontdoor/server.ts
65537
- var import_node_http = __toESM(require("node:http"), 1);
66070
+ var import_node_http2 = __toESM(require("node:http"), 1);
65538
66071
  var import_node_https = __toESM(require("node:https"), 1);
65539
66072
 
65540
66073
  // src/frontdoor/rcControl.ts
@@ -65705,11 +66238,11 @@ function createRcSessionTracker(deps) {
65705
66238
  };
65706
66239
  const observeExchange = (request7) => {
65707
66240
  const method = (request7.method ?? "").toUpperCase();
65708
- const path43 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
65709
- if (!path43.startsWith(RC_SESSIONS_PATH_PREFIX)) {
66241
+ const path44 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
66242
+ if (!path44.startsWith(RC_SESSIONS_PATH_PREFIX)) {
65710
66243
  return void 0;
65711
66244
  }
65712
- const tail = path43.slice(RC_SESSIONS_PATH_PREFIX.length);
66245
+ const tail = path44.slice(RC_SESSIONS_PATH_PREFIX.length);
65713
66246
  const facts = {
65714
66247
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
65715
66248
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -66449,9 +66982,9 @@ function sequenceNumsOfBody(body) {
66449
66982
  }
66450
66983
  function frontDoorRcControl(transport, token) {
66451
66984
  const headers = { authorization: `Bearer ${token}` };
66452
- const listAnswerOf = async (path43, what) => {
66985
+ const listAnswerOf = async (path44, what) => {
66453
66986
  try {
66454
- return await transport.request({ method: "GET", path: path43, headers });
66987
+ return await transport.request({ method: "GET", path: path44, headers });
66455
66988
  } catch (error62) {
66456
66989
  throw new Error(`${what}: could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}`, { cause: error62 });
66457
66990
  }
@@ -66523,10 +67056,10 @@ function frontDoorRcControl(transport, token) {
66523
67056
  }
66524
67057
  return pending;
66525
67058
  };
66526
- const writeOf = async (path43, body, describeFailure) => {
67059
+ const writeOf = async (path44, body, describeFailure) => {
66527
67060
  let answer;
66528
67061
  try {
66529
- answer = await transport.request({ method: "POST", path: path43, headers: { ...headers, "content-type": "application/json" }, body });
67062
+ answer = await transport.request({ method: "POST", path: path44, headers: { ...headers, "content-type": "application/json" }, body });
66530
67063
  } catch (error62) {
66531
67064
  return { ok: false, message: `could not reach the front door's control listener: ${error62 instanceof Error ? error62.message : String(error62)}` };
66532
67065
  }
@@ -66611,7 +67144,7 @@ function createFrontDoorServer(pipeline, log, tls2, control, api) {
66611
67144
  });
66612
67145
  };
66613
67146
  if (tls2 === void 0) {
66614
- return import_node_http.default.createServer(handler);
67147
+ return import_node_http2.default.createServer(handler);
66615
67148
  }
66616
67149
  const server = import_node_https.default.createServer({ key: tls2.keyPem, cert: tls2.certPem }, handler);
66617
67150
  server.on("tlsClientError", (_error, socket) => {
@@ -66626,7 +67159,7 @@ async function frontDoorHealthy(port, ca) {
66626
67159
  resolve(response.statusCode === HTTP_STATUS.ok);
66627
67160
  };
66628
67161
  const options = { host: "127.0.0.1", port, path: "/healthz", agent: false, timeout: HEALTH_TIMEOUT_MS };
66629
- const request7 = ca === void 0 ? import_node_http.default.get(options, onResponse) : import_node_https.default.get({ ...options, ca: [ca] }, onResponse);
67162
+ const request7 = ca === void 0 ? import_node_http2.default.get(options, onResponse) : import_node_https.default.get({ ...options, ca: [ca] }, onResponse);
66630
67163
  request7.on("timeout", () => {
66631
67164
  request7.destroy();
66632
67165
  });
@@ -66781,7 +67314,7 @@ async function reservedDial(target, ports) {
66781
67314
  function requestServername(options, fallback) {
66782
67315
  return "servername" in options && typeof options.servername === "string" && options.servername !== "" ? options.servername : fallback;
66783
67316
  }
66784
- var ExemptHttpAgent = class extends http2.Agent {
67317
+ var ExemptHttpAgent = class extends http3.Agent {
66785
67318
  constructor(ports = DOOR_SOURCE_PORTS) {
66786
67319
  super();
66787
67320
  this.ports = ports;
@@ -66899,12 +67432,12 @@ function lateRcStreamDial(resolve) {
66899
67432
  }
66900
67433
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
66901
67434
  const agent = new ExemptTlsAgent();
66902
- const request7 = async (method, path43, headers, body, signal) => await new Promise((resolve, reject) => {
67435
+ const request7 = async (method, path44, headers, body, signal) => await new Promise((resolve, reject) => {
66903
67436
  const options = {
66904
67437
  host: target.host,
66905
67438
  port: target.port,
66906
67439
  method,
66907
- path: path43,
67440
+ path: path44,
66908
67441
  // 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.
66909
67442
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
66910
67443
  agent,
@@ -66941,9 +67474,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
66941
67474
  return { status, body: await readAll(response) };
66942
67475
  },
66943
67476
  openStream: async (sessionId, headers, resume, signal) => {
66944
- const path43 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
67477
+ const path44 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
66945
67478
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
66946
- const { status, response } = await request7("GET", path43, streamHeaders, void 0, signal);
67479
+ const { status, response } = await request7("GET", path44, streamHeaders, void 0, signal);
66947
67480
  if (!isSuccessful2(status)) {
66948
67481
  await readAll(response);
66949
67482
  return { status, chunks: NO_CHUNKS };
@@ -67052,7 +67585,7 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
67052
67585
  };
67053
67586
  },
67054
67587
  createHttpSession: (handler, onUpgrade) => {
67055
- const server = http2.createServer(handler);
67588
+ const server = http3.createServer(handler);
67056
67589
  server.on("clientError", (_error, socket) => {
67057
67590
  socket.destroy();
67058
67591
  });
@@ -67122,7 +67655,7 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
67122
67655
  }
67123
67656
  upstreamResponse.pipe(response);
67124
67657
  };
67125
- const upstream = target.tls ? https3.request(options, onUpstreamResponse) : http2.request(options, onUpstreamResponse);
67658
+ const upstream = target.tls ? https3.request(options, onUpstreamResponse) : http3.request(options, onUpstreamResponse);
67126
67659
  upstream.on("error", (error62) => {
67127
67660
  if (response.headersSent) {
67128
67661
  response.destroy(error62);
@@ -67154,6 +67687,548 @@ function realConnectEffects(ports = DOOR_SOURCE_PORTS) {
67154
67687
  };
67155
67688
  }
67156
67689
 
67690
+ // src/doctorReport.ts
67691
+ var import_node_fs12 = __toESM(require("node:fs"), 1);
67692
+ var import_node_path32 = __toESM(require("node:path"), 1);
67693
+ var DOCTOR_SEVERITIES = ["pass", "warn", "fail"];
67694
+ var DOCTOR_SECTIONS = [
67695
+ "ambient-credential",
67696
+ "binary-discovery",
67697
+ "claude-shim",
67698
+ "path-resolution",
67699
+ "legacy-name",
67700
+ "config-profile",
67701
+ "identity",
67702
+ "pool",
67703
+ "provider",
67704
+ "keychain",
67705
+ "directory-rules",
67706
+ "global-config",
67707
+ "categories-local",
67708
+ "active-identity",
67709
+ "headroom"
67710
+ ];
67711
+ function refinePathShadow(status, ownExecutablePath, realpath) {
67712
+ if (status.status !== "shadowed") {
67713
+ return status;
67714
+ }
67715
+ return realpath(status.by) === realpath(ownExecutablePath) ? { status: "ok" } : status;
67716
+ }
67717
+ function validateJson(schema, input2) {
67718
+ if (input2.raw === void 0) {
67719
+ return { ok: false, message: `${input2.path} is missing.` };
67720
+ }
67721
+ let parsed;
67722
+ try {
67723
+ parsed = JSON.parse(input2.raw);
67724
+ } catch (error62) {
67725
+ return { ok: false, message: `${input2.path} is not valid JSON: ${error62 instanceof Error ? error62.message : String(error62)}` };
67726
+ }
67727
+ const result = schema.safeParse(parsed);
67728
+ if (!result.success) {
67729
+ return { ok: false, message: new ConfigValidationError(input2.path, result.error.issues).message };
67730
+ }
67731
+ return { ok: true, data: result.data };
67732
+ }
67733
+ function pushPathResolution(push, resolution) {
67734
+ const ownDir = import_node_path32.default.dirname(resolution.ownExecutablePath);
67735
+ switch (resolution.agentShim.status) {
67736
+ case "ok":
67737
+ push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
67738
+ break;
67739
+ case "not-on-path":
67740
+ push(
67741
+ "path-resolution",
67742
+ "warn",
67743
+ `${ownDir} is not on PATH, so a bare \`agent-shim\` does not reach ${resolution.ownExecutablePath}. Add it to PATH, or keep invoking this executable by its full path.`,
67744
+ "agent-shim"
67745
+ );
67746
+ break;
67747
+ case "shadowed":
67748
+ push(
67749
+ "path-resolution",
67750
+ "fail",
67751
+ `\`agent-shim\` on PATH resolves to ${resolution.agentShim.by}, not this running executable, ${resolution.ownExecutablePath}. Every command you type runs that one instead, at whatever version it happens to be \u2014 including the checks in this report, which describe this executable. Remove ${resolution.agentShim.by}, repoint it at ${resolution.ownExecutablePath}, or put ${ownDir} ahead of it on PATH.`,
67752
+ "agent-shim"
67753
+ );
67754
+ break;
67755
+ }
67756
+ if (resolution.claude === void 0) {
67757
+ return;
67758
+ }
67759
+ switch (resolution.claude.status) {
67760
+ case "ok":
67761
+ push("path-resolution", "pass", "`claude` on PATH resolves to the enabled shim.", "claude");
67762
+ break;
67763
+ case "not-on-path":
67764
+ push("path-resolution", "warn", "The enabled `claude` shim's directory is not on PATH \u2014 add it, or use `agent-shim run` instead.", "claude");
67765
+ break;
67766
+ case "shadowed":
67767
+ push(
67768
+ "path-resolution",
67769
+ "warn",
67770
+ `\`claude\` on PATH resolves to ${resolution.claude.by}, not the enabled shim. Put the shim's directory ahead of it on PATH, or run \`agent-shim shim disable\` if you meant to launch that one directly.`,
67771
+ "claude"
67772
+ );
67773
+ break;
67774
+ }
67775
+ }
67776
+ function cacheClause(cacheEnv, owner, block2) {
67777
+ if (cacheEnv === void 0 || block2.cache === void 0) {
67778
+ return { text: "", unreadable: false };
67779
+ }
67780
+ const state = describeCachedCredential({ port: cacheEnv.port, platform: cacheEnv.platform, owner, cache: block2.cache, nowMs: cacheEnv.now() });
67781
+ return { text: `; ${formatCachedCredentialState(state)}`, unreadable: state.status === "unreadable" };
67782
+ }
67783
+ function signInProblem(signIn) {
67784
+ if (signIn.raw === void 0) {
67785
+ return "nobody is signed in: run `agent-shim codex login`.";
67786
+ }
67787
+ try {
67788
+ const grant = parseSiwcFile(signIn.raw, signIn.path).grant;
67789
+ if (grant === void 0) {
67790
+ return "nobody is signed in: run `agent-shim codex login`.";
67791
+ }
67792
+ return grant.scopes.includes(SIWC_PLAN_SCOPE) ? void 0 : "the login was not given permission to use your ChatGPT plan: run `agent-shim codex login` again and allow it.";
67793
+ } catch (error62) {
67794
+ return error62 instanceof Error ? error62.message : String(error62);
67795
+ }
67796
+ }
67797
+ function pushProvider(push, entry, cacheEnv, signIn) {
67798
+ if (entry.raw === void 0) {
67799
+ push("provider", "fail", `${entry.path} is missing.`, entry.name);
67800
+ return;
67801
+ }
67802
+ let parsed;
67803
+ try {
67804
+ parsed = JSON.parse(entry.raw);
67805
+ } catch (error62) {
67806
+ push("provider", "fail", `${entry.path} is not valid JSON: ${error62 instanceof Error ? error62.message : String(error62)}`, entry.name);
67807
+ return;
67808
+ }
67809
+ const conversion = legacyProviderConversion(parsed);
67810
+ if (conversion !== void 0) {
67811
+ push("provider", "fail", new LegacyProviderFileError(entry.path, conversion).message, entry.name);
67812
+ return;
67813
+ }
67814
+ const validated2 = ProviderSchema.safeParse(parsed);
67815
+ if (!validated2.success) {
67816
+ push("provider", "fail", new ConfigValidationError(entry.path, validated2.error.issues).message, entry.name);
67817
+ return;
67818
+ }
67819
+ const cache = cacheClause(cacheEnv, `provider ${entry.name}`, validated2.data.credential);
67820
+ push("provider", cache.unreadable ? "fail" : "pass", `${entry.name} is valid (${describeProviderEndpoint(validated2.data)}, credential ${describeCredential(validated2.data.credential)})${cache.text}.`, entry.name);
67821
+ if (validated2.data.env?.ENABLE_TOOL_SEARCH === void 0) {
67822
+ push("provider", "warn", `${entry.name} does not set ENABLE_TOOL_SEARCH: a session on this provider loads MCP tools upfront rather than deferring them, because its base URL is the front door, which Claude Code treats as a non-first-party host. Set ENABLE_TOOL_SEARCH in the provider's env block to restore deferred loading, when the upstream backend supports the tool_reference payloads it sends.`, entry.name);
67823
+ }
67824
+ if (signIn !== void 0 && isCodexProvider(validated2.data) && validated2.data.codex?.login === "chatgpt-sign-in") {
67825
+ const problem = signInProblem(signIn);
67826
+ if (problem !== void 0) {
67827
+ push("provider", "warn", `${entry.name} uses the Sign in with ChatGPT login, but ${problem}`, entry.name);
67828
+ }
67829
+ }
67830
+ }
67831
+ function pushLegacyName(push, params) {
67832
+ const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
67833
+ if (legacyVariables.length === 0 && import_node_path32.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
67834
+ push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
67835
+ return;
67836
+ }
67837
+ for (const name of legacyVariables) {
67838
+ 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);
67839
+ }
67840
+ if (import_node_path32.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
67841
+ push(
67842
+ "legacy-name",
67843
+ "warn",
67844
+ `The state root is the former ${params.rootPath}, used in place. Leave it where it is: macOS Claude Code keys each identity's Keychain login on its exact configuration directory path, so moving it signs every identity out.`
67845
+ );
67846
+ }
67847
+ }
67848
+ function runDoctor(params) {
67849
+ const findings = [];
67850
+ const push = (section, severity, message, subject) => {
67851
+ findings.push({ section, severity, message, ...subject === void 0 ? {} : { subject } });
67852
+ };
67853
+ const checkPin = (section, subject, where, version2) => {
67854
+ const installed = params.installedClaudeVersions;
67855
+ if (version2 === void 0 || installed === void 0 || installed.includes(version2)) {
67856
+ return;
67857
+ }
67858
+ push(section, "warn", `${where} pins Claude Code ${version2}, which is not installed (installed: ${installed.length === 0 ? "none" : installed.join(", ")}); a launch that resolves to it fails.`, subject);
67859
+ };
67860
+ const ambient = detectAmbientCredential(params.env);
67861
+ if (ambient === void 0) {
67862
+ push("ambient-credential", "pass", "No ambient-credential environment variable is set.");
67863
+ } else {
67864
+ push("ambient-credential", "warn", formatAmbientCredentialGuardMessage(ambient.variable));
67865
+ }
67866
+ if (params.binaryDiscovery.ok) {
67867
+ const { binary } = params.binaryDiscovery;
67868
+ const versionNote = binary.version === void 0 ? "" : `, version ${binary.version}`;
67869
+ push("binary-discovery", "pass", `Found ${binary.path} (${binary.source}${versionNote}).`);
67870
+ } else {
67871
+ push("binary-discovery", "fail", params.binaryDiscovery.message);
67872
+ }
67873
+ if (params.claudeShim.state === void 0) {
67874
+ push("claude-shim", "pass", "No `claude` command shim enabled (the default). Run `agent-shim shim enable` to add one.");
67875
+ } else if (!params.claudeShim.targetExists) {
67876
+ push(
67877
+ "claude-shim",
67878
+ "warn",
67879
+ `claude-shim.json records a \`claude\` shim at ${params.claudeShim.state.targetPath}, but nothing is there. Run \`agent-shim shim enable\` again, or \`agent-shim shim disable\` to clear the stale record.`
67880
+ );
67881
+ } else {
67882
+ push(
67883
+ "claude-shim",
67884
+ "pass",
67885
+ `\`claude\` is enabled at ${params.claudeShim.state.targetPath} (${params.claudeShim.state.method}). If you've upgraded agent-shim since, re-run \`agent-shim shim enable\` to refresh it.`
67886
+ );
67887
+ }
67888
+ pushPathResolution(push, params.pathResolution);
67889
+ pushLegacyName(push, params);
67890
+ const profileSources = /* @__PURE__ */ new Map();
67891
+ for (const entry of params.configProfiles) {
67892
+ const validated2 = validateJson(ConfigProfileSchema, entry);
67893
+ if (!validated2.ok) {
67894
+ push("config-profile", "fail", validated2.message, entry.name);
67895
+ continue;
67896
+ }
67897
+ profileSources.set(entry.name, { name: entry.name, profile: validated2.data });
67898
+ checkPin("config-profile", entry.name, `Configuration profile "${entry.name}"`, validated2.data.launch?.claudeVersion);
67899
+ }
67900
+ const loadProfile = (name) => profileSources.get(name);
67901
+ for (const name of profileSources.keys()) {
67902
+ const linearised = lineariseProfile(name, loadProfile);
67903
+ if (linearised.diagnostics.length === 0) {
67904
+ push("config-profile", "pass", `${name} is valid and its extends chain resolves cleanly.`, name);
67905
+ } else {
67906
+ for (const diagnostic of linearised.diagnostics) {
67907
+ push("config-profile", "fail", diagnostic.message, name);
67908
+ }
67909
+ }
67910
+ }
67911
+ const validProfileNames = new Set(profileSources.keys());
67912
+ const validIdentityNames = /* @__PURE__ */ new Set();
67913
+ for (const entry of params.identities) {
67914
+ const validated2 = validateJson(IdentitySchema, entry);
67915
+ if (!validated2.ok) {
67916
+ push("identity", "fail", validated2.message, entry.name);
67917
+ continue;
67918
+ }
67919
+ validIdentityNames.add(entry.name);
67920
+ const defaultProfile = validated2.data.defaultConfigProfile;
67921
+ if (defaultProfile !== void 0 && !validProfileNames.has(defaultProfile)) {
67922
+ push(
67923
+ "identity",
67924
+ "fail",
67925
+ `Identity "${entry.name}" names configuration profile "${defaultProfile}" as its default, but no such profile exists.`,
67926
+ entry.name
67927
+ );
67928
+ } else {
67929
+ const credential = validated2.data.credential;
67930
+ const cache = credential === void 0 ? { text: "", unreadable: false } : cacheClause(params.credentialCache, `identity ${entry.name}`, credential);
67931
+ push(
67932
+ "identity",
67933
+ cache.unreadable ? "fail" : "pass",
67934
+ `${entry.name} is valid and authenticates with ${credential === void 0 ? "its stored login" : `credential ${describeCredential(credential)}`}${cache.text}.`,
67935
+ entry.name
67936
+ );
67937
+ }
67938
+ }
67939
+ const validatedGlobalConfig = params.globalConfig.raw === void 0 ? void 0 : validateJson(GlobalConfigSchema, params.globalConfig);
67940
+ const pools = validatedGlobalConfig?.ok === true ? validatedGlobalConfig.data.pools ?? {} : {};
67941
+ for (const [poolName, pool] of Object.entries(pools)) {
67942
+ const missing = pool.identities.filter((member) => !validIdentityNames.has(member));
67943
+ if (missing.length === 0) {
67944
+ push("pool", "pass", `${poolName} is valid (${pool.identities.join(", ")}).`, poolName);
67945
+ } else {
67946
+ push("pool", "fail", `Pool "${poolName}" names ${missing.map((member) => `identity "${member}"`).join(" and ")}, which ${missing.length === 1 ? "does" : "do"} not exist.`, poolName);
67947
+ }
67948
+ }
67949
+ const selectionExists = (selector) => {
67950
+ const poolName = poolNameOf(selector);
67951
+ return poolName === void 0 ? validIdentityNames.has(selector) : poolName in pools;
67952
+ };
67953
+ for (const entry of params.providers) {
67954
+ pushProvider(push, entry, params.credentialCache, params.chatgptSignIn);
67955
+ }
67956
+ if (params.platform !== "darwin" || params.run === void 0) {
67957
+ push("keychain", "pass", "Skipped (not macOS).");
67958
+ } else {
67959
+ for (const entry of params.identities) {
67960
+ const result = lookupKeychainService(params.run, entry.farmRoot);
67961
+ push("keychain", result.found ? "pass" : "warn", result.note, entry.name);
67962
+ }
67963
+ }
67964
+ if (params.directoryRules.raw === void 0) {
67965
+ push("directory-rules", "pass", "No directory-rules.json configured.");
67966
+ } else {
67967
+ const validated2 = validateJson(DirectoryRulesSchema, params.directoryRules);
67968
+ if (!validated2.ok) {
67969
+ push("directory-rules", "fail", validated2.message);
67970
+ } else {
67971
+ push("directory-rules", "pass", `${params.directoryRules.path} is valid.`);
67972
+ for (const rule of validated2.data.rules) {
67973
+ const badRefs = [];
67974
+ if (rule.identity !== void 0 && !selectionExists(rule.identity)) {
67975
+ badRefs.push(poolNameOf(rule.identity) === void 0 ? `identity "${rule.identity}"` : `pool "${poolNameOf(rule.identity) ?? ""}"`);
67976
+ }
67977
+ if (rule.configProfile !== void 0 && !validProfileNames.has(rule.configProfile)) {
67978
+ badRefs.push(`configuration profile "${rule.configProfile}"`);
67979
+ }
67980
+ checkPin("directory-rules", rule.path, `Rule for "${rule.path}"`, rule.launch?.claudeVersion);
67981
+ if (badRefs.length > 0) {
67982
+ push("directory-rules", "fail", `Rule for "${rule.path}" names ${badRefs.join(" and ")}, which do not exist.`, rule.path);
67983
+ } else {
67984
+ push("directory-rules", "pass", `Rule for "${rule.path}" is valid.`, rule.path);
67985
+ }
67986
+ }
67987
+ }
67988
+ }
67989
+ if (params.globalConfig.raw === void 0) {
67990
+ push("global-config", "pass", "No config.json configured.");
67991
+ } else {
67992
+ const validated2 = validateJson(GlobalConfigSchema, params.globalConfig);
67993
+ if (!validated2.ok) {
67994
+ push("global-config", "fail", validated2.message);
67995
+ } else {
67996
+ const defaultProfile = validated2.data.defaultConfigProfile;
67997
+ if (defaultProfile !== void 0 && !validProfileNames.has(defaultProfile)) {
67998
+ push(
67999
+ "global-config",
68000
+ "fail",
68001
+ `config.json names configuration profile "${defaultProfile}" as its default, but no such profile exists.`
68002
+ );
68003
+ } else {
68004
+ push("global-config", "pass", `${params.globalConfig.path} is valid.`);
68005
+ checkPin("global-config", void 0, "config.json", validated2.data.launch?.claudeVersion);
68006
+ }
68007
+ }
68008
+ }
68009
+ if (params.categoriesLocal.raw === void 0) {
68010
+ push("categories-local", "pass", "No categories.local.json configured.");
68011
+ } else {
68012
+ const validated2 = validateJson(CategoryClassificationOverlaySchema, params.categoriesLocal);
68013
+ push(
68014
+ "categories-local",
68015
+ validated2.ok ? "pass" : "fail",
68016
+ validated2.ok ? `${params.categoriesLocal.path} is valid.` : validated2.message
68017
+ );
68018
+ }
68019
+ if (params.headroom.state.raw === void 0) {
68020
+ push("headroom", "pass", "No headroom daemon has ever run; nothing to check.");
68021
+ } else {
68022
+ const validated2 = validateJson(HeadroomStateSchema, params.headroom.state);
68023
+ if (!validated2.ok) {
68024
+ push("headroom", "fail", validated2.message);
68025
+ } else {
68026
+ const state = validated2.data;
68027
+ const supervisorAlive = state.supervisorPid !== void 0 && params.headroom.isRunning(state.supervisorPid);
68028
+ const headroomAlive = state.headroomPid !== void 0 && params.headroom.isRunning(state.headroomPid);
68029
+ if (state.supervisorPid === void 0) {
68030
+ if (state.lastError === void 0) {
68031
+ push("headroom", "pass", "Headroom daemon is stopped (idle shutdown) with no recorded error.");
68032
+ } else {
68033
+ push("headroom", "warn", `Headroom supervisor is not running; last error: ${state.lastError}`);
68034
+ }
68035
+ } else if (!supervisorAlive) {
68036
+ push(
68037
+ "headroom",
68038
+ "warn",
68039
+ `Headroom state names supervisor pid ${String(state.supervisorPid)}, which is not running; the next launch through headroom will start a replacement.`
68040
+ );
68041
+ } else if (state.headroomPid === void 0 || state.socketPath === void 0) {
68042
+ push(
68043
+ "headroom",
68044
+ "warn",
68045
+ state.lastError === void 0 ? "Headroom supervisor is running but the daemon has no healthy process; it should be restarting it." : `Headroom supervisor is running but the daemon is down; last error: ${state.lastError}`
68046
+ );
68047
+ } else if (!headroomAlive) {
68048
+ push(
68049
+ "headroom",
68050
+ "warn",
68051
+ `Headroom state names daemon pid ${String(state.headroomPid)}, which is not running; its supervisor should be restarting it.`
68052
+ );
68053
+ } else {
68054
+ push(
68055
+ "headroom",
68056
+ "pass",
68057
+ `Headroom daemon is up on unix socket ${state.socketPath} (supervisor ${String(state.supervisorPid)}, daemon ${String(state.headroomPid)}).`
68058
+ );
68059
+ }
68060
+ if (state.lastError !== void 0 && supervisorAlive) {
68061
+ push("headroom", "warn", `Headroom recorded a previous error: ${state.lastError}`);
68062
+ }
68063
+ if (state.installedSource !== void 0 && isMovingGitSource(state.installedSource)) {
68064
+ push(
68065
+ "headroom",
68066
+ "warn",
68067
+ `Headroom is installed from a git ref that can move (${state.installedSource}); pin headroom.source to a full commit SHA so a rebased or deleted branch cannot change or break the install.`
68068
+ );
68069
+ }
68070
+ }
68071
+ }
68072
+ if (params.activeIdentity.raw === void 0) {
68073
+ push("active-identity", "pass", "No active identity set.");
68074
+ } else {
68075
+ const trimmed = params.activeIdentity.raw.trim();
68076
+ if (trimmed === "") {
68077
+ push("active-identity", "warn", "active-identity is present but empty \u2014 treated the same as unset.");
68078
+ } else if (!selectionExists(trimmed)) {
68079
+ push("active-identity", "fail", `active-identity names "${trimmed}", which does not exist.`);
68080
+ } else {
68081
+ push("active-identity", "pass", `Active identity "${trimmed}" is valid.`);
68082
+ }
68083
+ }
68084
+ return { findings, ok: !findings.some((finding) => finding.severity === "fail") };
68085
+ }
68086
+ var SECTION_TITLES = {
68087
+ "ambient-credential": "Ambient-credential exposure",
68088
+ "binary-discovery": "Claude Code binary discovery",
68089
+ "claude-shim": "`claude` command shim",
68090
+ "path-resolution": "PATH resolution",
68091
+ "legacy-name": "Former `claude-use` name",
68092
+ "config-profile": "Configuration profiles",
68093
+ identity: "Identities",
68094
+ pool: "Pools",
68095
+ provider: "Providers",
68096
+ keychain: "macOS Keychain",
68097
+ "directory-rules": "Directory rules",
68098
+ "global-config": "Global config",
68099
+ headroom: "Headroom daemon",
68100
+ "categories-local": "categories.local.json",
68101
+ "active-identity": "Active identity"
68102
+ };
68103
+ var SECTION_ORDER = [
68104
+ "ambient-credential",
68105
+ "binary-discovery",
68106
+ "claude-shim",
68107
+ "path-resolution",
68108
+ "config-profile",
68109
+ "identity",
68110
+ "pool",
68111
+ "provider",
68112
+ "keychain",
68113
+ "directory-rules",
68114
+ "global-config",
68115
+ "headroom",
68116
+ "categories-local",
68117
+ "active-identity"
68118
+ ];
68119
+ function severityPrefix(severity) {
68120
+ switch (severity) {
68121
+ case "pass":
68122
+ return "[PASS]";
68123
+ case "warn":
68124
+ return "[WARN]";
68125
+ case "fail":
68126
+ return "[FAIL]";
68127
+ default:
68128
+ return severity;
68129
+ }
68130
+ }
68131
+ function formatDoctorReport(report) {
68132
+ const lines = [];
68133
+ for (const section of SECTION_ORDER) {
68134
+ const sectionFindings = report.findings.filter((finding) => finding.section === section);
68135
+ if (sectionFindings.length === 0) {
68136
+ continue;
68137
+ }
68138
+ lines.push("", `${SECTION_TITLES[section]}:`);
68139
+ for (const finding of sectionFindings) {
68140
+ const subject = finding.subject === void 0 ? "" : `${finding.subject}: `;
68141
+ lines.push(` ${severityPrefix(finding.severity)} ${subject}${finding.message}`);
68142
+ }
68143
+ }
68144
+ const failCount = report.findings.filter((finding) => finding.severity === "fail").length;
68145
+ lines.push("", report.ok ? "All checks passed." : `${String(failCount)} check(s) failed.`);
68146
+ return lines;
68147
+ }
68148
+ function realpathOrSelf(target) {
68149
+ try {
68150
+ return import_node_fs12.default.realpathSync(target);
68151
+ } catch {
68152
+ return target;
68153
+ }
68154
+ }
68155
+ function collectDoctorReport(params) {
68156
+ const { paths } = params;
68157
+ const identityNames = import_node_fs12.default.existsSync(paths.identitiesDir) ? import_node_fs12.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
68158
+ const identities = identityNames.map((name) => {
68159
+ const farmRoot = import_node_path32.default.join(paths.identitiesDir, name);
68160
+ const identityPath = import_node_path32.default.join(farmRoot, "identity.json");
68161
+ return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
68162
+ });
68163
+ const profileNames = import_node_fs12.default.existsSync(paths.configProfilesDir) ? import_node_fs12.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
68164
+ const configProfiles = profileNames.map((name) => {
68165
+ const profilePath = import_node_path32.default.join(paths.configProfilesDir, `${name}.json`);
68166
+ return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
68167
+ });
68168
+ const providerNames = import_node_fs12.default.existsSync(paths.providersDir) ? import_node_fs12.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
68169
+ const providers = providerNames.map((name) => {
68170
+ const providerPath = import_node_path32.default.join(paths.providersDir, `${name}.json`);
68171
+ return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
68172
+ });
68173
+ const ownExecutablePath = realOwnExecutablePath();
68174
+ let binaryDiscovery;
68175
+ try {
68176
+ const binary = realResolveClaudeBinary(resolveOwnBinaryCheck(paths, realContentSourcePath()))();
68177
+ binaryDiscovery = { ok: true, binary };
68178
+ } catch (error62) {
68179
+ binaryDiscovery = { ok: false, message: error62 instanceof Error ? error62.message : String(error62) };
68180
+ }
68181
+ const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
68182
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path32.default.delimiter).filter((dir) => dir !== "");
68183
+ const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
68184
+ findPathShadow({
68185
+ pathDirs,
68186
+ targetDir: import_node_path32.default.dirname(shimState.targetPath),
68187
+ targetFilename: import_node_path32.default.basename(shimState.targetPath),
68188
+ findExecutableInDir
68189
+ }),
68190
+ shimState.targetPath,
68191
+ realpathOrSelf
68192
+ );
68193
+ const report = runDoctor({
68194
+ env: params.env,
68195
+ credentialCache: realCredentialCacheEnv(paths),
68196
+ chatgptSignIn: { path: paths.chatgptSignInFile, raw: realFsPort.readFileUtf8(paths.chatgptSignInFile) },
68197
+ installedClaudeVersions: realInstalledClaudeVersions(),
68198
+ identities,
68199
+ configProfiles,
68200
+ providers,
68201
+ directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
68202
+ globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
68203
+ categoriesLocal: { path: paths.categoriesLocalFile, raw: realFsPort.readFileUtf8(paths.categoriesLocalFile) },
68204
+ activeIdentity: { path: paths.activeIdentityFile, raw: realFsPort.readFileUtf8(paths.activeIdentityFile) },
68205
+ binaryDiscovery,
68206
+ claudeShim: { state: shimState, targetExists: shimState !== void 0 && import_node_fs12.default.existsSync(shimState.targetPath) },
68207
+ rootPath: paths.root,
68208
+ pathResolution: {
68209
+ ownExecutablePath,
68210
+ agentShim: refinePathShadow(
68211
+ findPathShadow({
68212
+ pathDirs,
68213
+ targetDir: import_node_path32.default.dirname(ownExecutablePath),
68214
+ targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
68215
+ findExecutableInDir
68216
+ }),
68217
+ ownExecutablePath,
68218
+ realpathOrSelf
68219
+ ),
68220
+ ...claudeShimShadow === void 0 ? {} : { claude: claudeShimShadow }
68221
+ },
68222
+ run: realRunPort,
68223
+ platform: process.platform,
68224
+ headroom: {
68225
+ state: { path: paths.headroomStateFile, raw: realFsPort.readFileUtf8(paths.headroomStateFile) },
68226
+ isRunning: realIsProcessRunning
68227
+ }
68228
+ });
68229
+ return report;
68230
+ }
68231
+
67157
68232
  // node_modules/.pnpm/radash@12.1.1/node_modules/radash/dist/esm/async.mjs
67158
68233
  var guard = (func, shouldGuard) => {
67159
68234
  const _guard = (err) => {
@@ -68066,9 +69141,9 @@ function resolveFriendlyClientOptions(options) {
68066
69141
  };
68067
69142
  }
68068
69143
  function createORPCClient(link, options = {}) {
68069
- const path43 = options.path ?? [];
69144
+ const path44 = options.path ?? [];
68070
69145
  const procedureClient = async (...[input2, options2 = {}]) => {
68071
- return await link.call(path43, input2, resolveFriendlyClientOptions(options2));
69146
+ return await link.call(path44, input2, resolveFriendlyClientOptions(options2));
68072
69147
  };
68073
69148
  const recursive2 = new Proxy(procedureClient, {
68074
69149
  get(target, key) {
@@ -68077,13 +69152,293 @@ function createORPCClient(link, options = {}) {
68077
69152
  }
68078
69153
  return createORPCClient(link, {
68079
69154
  ...options,
68080
- path: [...path43, key]
69155
+ path: [...path44, key]
68081
69156
  });
68082
69157
  }
68083
69158
  });
68084
69159
  return preventNativeAwait(recursive2);
68085
69160
  }
68086
69161
 
69162
+ // src/resolve/types.ts
69163
+ var LAYER_KINDS = [
69164
+ "global-config",
69165
+ "config-profile",
69166
+ "directory-rule",
69167
+ "portable",
69168
+ "portable-local",
69169
+ "cli-override"
69170
+ ];
69171
+ var DECISION_VIAS = [
69172
+ /** The unconditional pre-cascade floor: the path's real classification is `secret`. */
69173
+ "secret-floor",
69174
+ /** Nothing in the classification map recognises the path's top-level entry. */
69175
+ "unclassified",
69176
+ /** An entries rule matched and its condition (if any) held. */
69177
+ "entry-rule",
69178
+ /** No entries rule survived; a layer's category toggle decided it. */
69179
+ "category-override",
69180
+ /** No entries rule and no category toggle; the shipped default for the category decided it. */
69181
+ "category-default"
69182
+ ];
69183
+ var DIAGNOSTIC_CODES = [
69184
+ /** A profile's `extends` graph contains a cycle. */
69185
+ "EXTENDS_CYCLE",
69186
+ /** An `extends` entry names a profile that does not exist. */
69187
+ "MISSING_PROFILE",
69188
+ /** An entries key was written under the `secret/` prefix. Rejected at compile time — `secret` can never be overridden by any layer. */
69189
+ "SECRET_ENTRY_KEY",
69190
+ /** An entries key under some other prefix matched a path whose real classification is `secret`. Neutralised at resolve time by the floor check. */
69191
+ "SECRET_PATH_NEUTRALISED",
69192
+ /** An entries key's declared category prefix disagrees with the real classification of a path it matched. */
69193
+ "CATEGORY_PREFIX_MISMATCH",
69194
+ /** An entries key is not of the form `<category>/<path>`. The schema rejects these at parse time; this fires only for a layer built in code. */
69195
+ "MALFORMED_ENTRY_KEY",
69196
+ /** An earlier layer's exact key lost to a later layer's glob. Correct per the comparator, but worth surfacing rather than resolving silently. */
69197
+ "EXACT_ENTRY_OVERRIDDEN_BY_LATER_GLOB",
69198
+ /** A `history/projects/` pattern's encoded form could plausibly correspond to more than one real path. */
69199
+ "AMBIGUOUS_PROJECT_ENCODING",
69200
+ /** A `history/projects/` key's path fragment is neither home-rooted nor absolute, so it cannot be encoded. */
69201
+ "UNROOTED_PROJECT_PATH",
69202
+ /** A `~/.claude` entry nothing in the classification map recognises. */
69203
+ "UNCLASSIFIED_ENTRY",
69204
+ /** An empty `when: {}` object, which is vacuously true and therefore has no effect. */
69205
+ "EMPTY_WHEN",
69206
+ /** The previous farm's manifest is missing or unreadable, so reconciliation ran in conservative mode. */
69207
+ "FARM_MANIFEST_MISSING",
69208
+ /** A file Claude Code wrote into a materialised farm directory differs from the canonical copy of the same path. */
69209
+ "RECONCILE_CONFLICT",
69210
+ /** Reconciliation proposed adopting a path whose real classification is `secret`. Refused: the secret floor applies to data moving into `~/.claude` exactly as it applies to data moving out. */
69211
+ "RECONCILE_SECRET_BLOCKED",
69212
+ /** A previous launch was interrupted mid-swap and this launch completed or undid the half-finished work. */
69213
+ "FARM_SWAP_RECOVERED",
69214
+ /** A superseded farm could not be discarded because it still held data the new farm has its own entry for, so it was left on disk for the user to look at. */
69215
+ "FARM_PREVIOUS_RETAINED"
69216
+ ];
69217
+ var DIAGNOSTIC_SEVERITIES = ["error", "warning", "info"];
69218
+
69219
+ // src/usage/pickReportSchema.ts
69220
+ var PoolPickCandidateViewSchema = external_exports.strictObject({
69221
+ identity: external_exports.string(),
69222
+ /** In pick order: `scored` has usable quota data, `unknown` has none, `pay-per-use` bills by use, `ineligible` is refused right now. */
69223
+ class: external_exports.enum(["scored", "unknown", "pay-per-use", "ineligible"]),
69224
+ /** Plan-size-weighted remaining quota per hour until its reset; present for `scored` only. */
69225
+ score: external_exports.number().optional(),
69226
+ /** False when the five-hour window would run dry, at the observed pace, before it resets. */
69227
+ feasible: external_exports.boolean(),
69228
+ /** When an `ineligible` member can be used again, as an ISO instant. */
69229
+ blockedUntil: external_exports.iso.datetime().optional(),
69230
+ plan: PlanClassSchema,
69231
+ /** The facts behind the class and score, in the order they matter. */
69232
+ reasons: external_exports.array(external_exports.string())
69233
+ });
69234
+ var PoolPickReportSchema = external_exports.strictObject({
69235
+ pool: external_exports.string(),
69236
+ directory: external_exports.string(),
69237
+ /** The member a launch would run as, absent when every member is refused. */
69238
+ pick: external_exports.string().optional(),
69239
+ candidates: external_exports.array(PoolPickCandidateViewSchema),
69240
+ /** Members that name an identity that does not exist; a launch skips them. */
69241
+ missing: external_exports.array(external_exports.string()),
69242
+ /** When nothing can be picked, the soonest any member returns. */
69243
+ earliestReturn: external_exports.strictObject({ identity: external_exports.string(), at: external_exports.iso.datetime() }).optional(),
69244
+ /** Why the last-pick record could not be read, when that is the case. */
69245
+ stickyProblem: external_exports.string().optional()
69246
+ });
69247
+
69248
+ // src/checkReportSchema.ts
69249
+ var CHECK_CREDENTIAL_APPLIES = ["provider", "identity", "stored-login"];
69250
+ var CheckLayerViewSchema = external_exports.strictObject({
69251
+ id: external_exports.int(),
69252
+ kind: external_exports.enum(LAYER_KINDS),
69253
+ source: external_exports.string()
69254
+ });
69255
+ var CheckEntryViewSchema = external_exports.strictObject({
69256
+ path: external_exports.string(),
69257
+ shared: external_exports.boolean(),
69258
+ via: external_exports.enum(DECISION_VIAS),
69259
+ /** The entry's real category, or null when nothing classifies it. */
69260
+ category: external_exports.enum(CATEGORY_NAMES).nullable(),
69261
+ rule: external_exports.strictObject({ key: external_exports.string(), layer: external_exports.int() }).optional(),
69262
+ /** Rules that matched but whose `when` condition failed, each with the conditions that failed. */
69263
+ eliminated: external_exports.readonly(external_exports.array(external_exports.strictObject({ key: external_exports.string(), failed: external_exports.readonly(external_exports.array(external_exports.string())) }))).optional()
69264
+ });
69265
+ var CheckDiagnosticSchema = external_exports.strictObject({
69266
+ code: external_exports.enum(DIAGNOSTIC_CODES),
69267
+ severity: external_exports.enum(DIAGNOSTIC_SEVERITIES),
69268
+ message: external_exports.string(),
69269
+ subject: external_exports.string().optional(),
69270
+ layer: external_exports.int().optional()
69271
+ });
69272
+ var CheckAmbientCredentialSchema = external_exports.union([external_exports.strictObject({ ok: external_exports.literal(true) }), external_exports.strictObject({ ok: external_exports.literal(false), variable: external_exports.string(), message: external_exports.string() })]);
69273
+ var CheckKeychainSchema = external_exports.strictObject({
69274
+ checked: external_exports.literal(true),
69275
+ found: external_exports.boolean(),
69276
+ serviceName: external_exports.string().optional(),
69277
+ note: external_exports.string()
69278
+ });
69279
+ var CheckSettingsExposureSchema = external_exports.strictObject({
69280
+ file: external_exports.string(),
69281
+ envKeyNames: external_exports.readonly(external_exports.array(external_exports.string())),
69282
+ hookEventNames: external_exports.readonly(external_exports.array(external_exports.string())),
69283
+ hookCommandCount: external_exports.int().nonnegative()
69284
+ });
69285
+ var CredentialSourceSummarySchema = external_exports.union([
69286
+ external_exports.strictObject({ kind: external_exports.literal("env"), variable: external_exports.string() }),
69287
+ external_exports.strictObject({ kind: external_exports.literal("file"), path: external_exports.string() }),
69288
+ external_exports.strictObject({ kind: external_exports.literal("command"), program: external_exports.string() }),
69289
+ external_exports.strictObject({ kind: external_exports.literal("op"), reference: external_exports.string() }),
69290
+ external_exports.strictObject({ kind: external_exports.literal("keychain"), service: external_exports.string(), account: external_exports.string().optional() }),
69291
+ external_exports.strictObject({ kind: external_exports.literal("literal") })
69292
+ ]);
69293
+ var CredentialSummarySchema = external_exports.strictObject({
69294
+ target: external_exports.enum(CREDENTIAL_TARGETS),
69295
+ sources: external_exports.readonly(external_exports.array(CredentialSourceSummarySchema)),
69296
+ cache: CredentialCacheSchema.optional()
69297
+ });
69298
+ var CachedCredentialStateSchema = external_exports.union([
69299
+ external_exports.strictObject({ store: external_exports.enum(CREDENTIAL_CACHE_STORES), status: external_exports.literal("empty") }),
69300
+ external_exports.strictObject({ store: external_exports.enum(CREDENTIAL_CACHE_STORES), status: external_exports.literal("unreadable"), reason: external_exports.string() }),
69301
+ external_exports.strictObject({ store: external_exports.enum(CREDENTIAL_CACHE_STORES), status: external_exports.enum(["fresh", "expired"]), ageMs: external_exports.number(), expiresInMs: external_exports.number().optional() })
69302
+ ]);
69303
+ var CheckCredentialProviderSchema = external_exports.union([
69304
+ external_exports.strictObject({ name: external_exports.string(), credential: CredentialSummarySchema, cached: CachedCredentialStateSchema.optional() }),
69305
+ external_exports.strictObject({ name: external_exports.string(), problem: external_exports.string() })
69306
+ ]);
69307
+ var CheckCredentialSchema = external_exports.strictObject({
69308
+ applies: external_exports.enum(CHECK_CREDENTIAL_APPLIES),
69309
+ provider: CheckCredentialProviderSchema.optional(),
69310
+ identity: CredentialSummarySchema.optional(),
69311
+ identityCached: CachedCredentialStateSchema.optional()
69312
+ });
69313
+ var CheckClaudeVersionSchema = external_exports.strictObject({
69314
+ pinned: external_exports.strictObject({ version: external_exports.string(), source: external_exports.enum(CLAUDE_VERSION_SOURCES), installed: external_exports.boolean() }).optional(),
69315
+ highestInstalled: external_exports.string().optional(),
69316
+ installed: external_exports.readonly(external_exports.array(external_exports.string()))
69317
+ });
69318
+ var CheckReportJsonSchema = external_exports.strictObject({
69319
+ identity: external_exports.strictObject({ name: external_exports.string().nullable(), source: external_exports.enum(IDENTITY_DECISION_SOURCES) }),
69320
+ /** The pool ranking, when the launch named a pool instead of an identity. */
69321
+ pool: PoolPickReportSchema.optional(),
69322
+ configProfile: external_exports.strictObject({ name: external_exports.string().nullable(), source: external_exports.enum(CONFIG_PROFILE_DECISION_SOURCES) }),
69323
+ layers: external_exports.readonly(external_exports.array(CheckLayerViewSchema)),
69324
+ entries: external_exports.readonly(external_exports.array(CheckEntryViewSchema)),
69325
+ projectEncodingAmbiguities: external_exports.readonly(
69326
+ external_exports.array(external_exports.strictObject({ fragment: external_exports.string(), encoded: external_exports.string(), reason: external_exports.enum(ENCODING_AMBIGUITY_REASONS), detail: external_exports.string() }))
69327
+ ),
69328
+ diagnostics: external_exports.readonly(external_exports.array(CheckDiagnosticSchema)),
69329
+ ambientCredential: CheckAmbientCredentialSchema,
69330
+ keychain: CheckKeychainSchema.optional(),
69331
+ settingsExposure: external_exports.readonly(external_exports.array(CheckSettingsExposureSchema)),
69332
+ credential: CheckCredentialSchema,
69333
+ claudeVersion: CheckClaudeVersionSchema.optional()
69334
+ });
69335
+
69336
+ // src/frontdoor/controlSchemas.ts
69337
+ var import_node_path33 = __toESM(require("node:path"), 1);
69338
+ var UsageListOutputSchema = external_exports.strictObject({ snapshots: external_exports.readonly(external_exports.array(UsageSnapshotSchema)) });
69339
+ var UsageWindowsInputSchema = external_exports.strictObject({
69340
+ identity: external_exports.string().min(1),
69341
+ provider: external_exports.string().min(1).optional()
69342
+ });
69343
+ var EffectiveWindowSchema = external_exports.strictObject({
69344
+ /** True when the window's reset time has passed, so the recorded observation describes a window that no longer exists. */
69345
+ reset: external_exports.boolean(),
69346
+ /** The fraction used: 0 for a reset window, otherwise what was last observed, absent when none was reported. */
69347
+ utilization: external_exports.number().optional(),
69348
+ /** The reset instant, for a window that has not reset yet and reported one. */
69349
+ resetsAtMs: external_exports.number().optional(),
69350
+ /** The window's own status, for a window that has not reset yet. */
69351
+ status: external_exports.string().optional()
69352
+ });
69353
+ var UsageWindowsOutputSchema = external_exports.strictObject({
69354
+ identity: external_exports.string(),
69355
+ provider: external_exports.string(),
69356
+ /** When the rate-limit state the windows come from was observed. */
69357
+ observedAt: external_exports.iso.datetime().optional(),
69358
+ fiveHour: EffectiveWindowSchema.optional(),
69359
+ sevenDay: EffectiveWindowSchema.optional()
69360
+ });
69361
+ var FrontDoorSessionStatusSchema = external_exports.strictObject({
69362
+ pid: external_exports.int().positive(),
69363
+ startedAt: external_exports.number(),
69364
+ alive: external_exports.boolean()
69365
+ });
69366
+ var HeadroomSocketTargetSchema = external_exports.union([external_exports.strictObject({ socketPath: external_exports.string() }), external_exports.strictObject({ refused: external_exports.string() })]);
69367
+ var FrontDoorStatusOutputSchema = external_exports.strictObject({
69368
+ state: FrontDoorStateSchema,
69369
+ supervisorAlive: external_exports.boolean(),
69370
+ sessions: external_exports.readonly(external_exports.array(FrontDoorSessionStatusSchema)),
69371
+ headroomSocket: HeadroomSocketTargetSchema.optional(),
69372
+ logPath: external_exports.string(),
69373
+ logExists: external_exports.boolean()
69374
+ });
69375
+ var FrontDoorSessionsOutputSchema = external_exports.strictObject({ sessions: external_exports.readonly(external_exports.array(FrontDoorSessionStatusSchema)) });
69376
+ var CheckRunInputSchema = external_exports.strictObject({
69377
+ path: external_exports.string().min(1),
69378
+ identity: external_exports.string().min(1).optional()
69379
+ }).refine((input2) => import_node_path33.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
69380
+ var DoctorFindingSchema = external_exports.strictObject({
69381
+ section: external_exports.enum(DOCTOR_SECTIONS),
69382
+ subject: external_exports.string().optional(),
69383
+ severity: external_exports.enum(DOCTOR_SEVERITIES),
69384
+ message: external_exports.string()
69385
+ });
69386
+ var DoctorRunOutputSchema = external_exports.strictObject({
69387
+ /** False exactly when any finding is a `fail`; a `warn` never fails the report on its own. */
69388
+ ok: external_exports.boolean(),
69389
+ findings: external_exports.readonly(external_exports.array(DoctorFindingSchema))
69390
+ });
69391
+
69392
+ // node_modules/.pnpm/@orpc+contract@1.15.4/node_modules/@orpc/contract/dist/shared/contract.D_dZrO__.mjs
69393
+ var ValidationError = class extends Error {
69394
+ issues;
69395
+ data;
69396
+ constructor(options) {
69397
+ super(options.message, options);
69398
+ this.issues = options.issues;
69399
+ this.data = options.data;
69400
+ }
69401
+ };
69402
+ function mergeErrorMap(errorMap1, errorMap2) {
69403
+ return { ...errorMap1, ...errorMap2 };
69404
+ }
69405
+ async function validateORPCError(map3, error62) {
69406
+ const { code, status, message, data, cause, defined } = error62;
69407
+ const config2 = map3?.[error62.code];
69408
+ if (!config2 || fallbackORPCErrorStatus(error62.code, config2.status) !== error62.status) {
69409
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error62;
69410
+ }
69411
+ if (!config2.data) {
69412
+ return defined ? error62 : new ORPCError(code, { defined: true, status, message, data, cause });
69413
+ }
69414
+ const validated2 = await config2.data["~standard"].validate(error62.data);
69415
+ if (validated2.issues) {
69416
+ return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error62;
69417
+ }
69418
+ return new ORPCError(code, { defined: true, status, message, data: validated2.value, cause });
69419
+ }
69420
+ var ContractProcedure = class {
69421
+ /**
69422
+ * This property holds the defined options for the contract procedure.
69423
+ */
69424
+ "~orpc";
69425
+ constructor(def) {
69426
+ if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) {
69427
+ throw new Error("[ContractProcedure] Invalid successStatus.");
69428
+ }
69429
+ if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) {
69430
+ throw new Error("[ContractProcedure] Invalid error status code.");
69431
+ }
69432
+ this["~orpc"] = def;
69433
+ }
69434
+ };
69435
+ function isContractProcedure(item) {
69436
+ if (item instanceof ContractProcedure) {
69437
+ return true;
69438
+ }
69439
+ return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
69440
+ }
69441
+
68087
69442
  // node_modules/.pnpm/@orpc+standard-server-fetch@1.15.4/node_modules/@orpc/standard-server-fetch/dist/index.mjs
68088
69443
  function toEventIterator(stream, options = {}) {
68089
69444
  const eventStream = stream?.pipeThrough(new TextDecoderStream()).pipeThrough(new EventDecoderStream());
@@ -68379,19 +69734,19 @@ var StandardLink = class {
68379
69734
  }
68380
69735
  interceptors;
68381
69736
  clientInterceptors;
68382
- call(path43, input2, options) {
69737
+ call(path44, input2, options) {
68383
69738
  return runWithSpan(
68384
- { name: `${ORPC_NAME}.${path43.join("/")}`, signal: options.signal },
69739
+ { name: `${ORPC_NAME}.${path44.join("/")}`, signal: options.signal },
68385
69740
  (span) => {
68386
69741
  span?.setAttribute("rpc.system", ORPC_NAME);
68387
- span?.setAttribute("rpc.method", path43.join("."));
69742
+ span?.setAttribute("rpc.method", path44.join("."));
68388
69743
  if (isAsyncIteratorObject(input2)) {
68389
69744
  input2 = asyncIteratorWithSpan(
68390
69745
  { name: "consume_event_iterator_input", signal: options.signal },
68391
69746
  input2
68392
69747
  );
68393
69748
  }
68394
- return intercept(this.interceptors, { ...options, path: path43, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
69749
+ return intercept(this.interceptors, { ...options, path: path44, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
68395
69750
  const otelConfig = getGlobalOtelConfig();
68396
69751
  let otelContext;
68397
69752
  const currentSpan = otelConfig?.trace.getActiveSpan() ?? span;
@@ -68626,8 +69981,8 @@ var StandardRPCJsonSerializer = class {
68626
69981
  return ref.data;
68627
69982
  }
68628
69983
  };
68629
- function toHttpPath(path43) {
68630
- return `/${path43.map(encodeURIComponent).join("/")}`;
69984
+ function toHttpPath(path44) {
69985
+ return `/${path44.map(encodeURIComponent).join("/")}`;
68631
69986
  }
68632
69987
  function toStandardHeaders2(headers) {
68633
69988
  if (typeof headers.forEach === "function") {
@@ -68652,18 +70007,18 @@ var StandardRPCLinkCodec = class {
68652
70007
  fallbackMethod;
68653
70008
  expectedMethod;
68654
70009
  headers;
68655
- async encode(path43, input2, options) {
68656
- let headers = toStandardHeaders2(await value(this.headers, options, path43, input2));
70010
+ async encode(path44, input2, options) {
70011
+ let headers = toStandardHeaders2(await value(this.headers, options, path44, input2));
68657
70012
  if (options.lastEventId !== void 0) {
68658
70013
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
68659
70014
  }
68660
- const expectedMethod = await value(this.expectedMethod, options, path43, input2);
68661
- const baseUrl = await value(this.baseUrl, options, path43, input2);
70015
+ const expectedMethod = await value(this.expectedMethod, options, path44, input2);
70016
+ const baseUrl = await value(this.baseUrl, options, path44, input2);
68662
70017
  const url2 = new URL(baseUrl);
68663
- url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path43)}`;
70018
+ url2.pathname = `${url2.pathname.replace(/\/$/, "")}${toHttpPath(path44)}`;
68664
70019
  const serialized = this.serializer.serialize(input2);
68665
70020
  if (expectedMethod === "GET" && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
68666
- const maxUrlLength = await value(this.maxUrlLength, options, path43, input2);
70021
+ const maxUrlLength = await value(this.maxUrlLength, options, path44, input2);
68667
70022
  const getUrl = new URL(url2);
68668
70023
  getUrl.searchParams.append("data", stringifyJSON(serialized));
68669
70024
  if (getUrl.toString().length <= maxUrlLength) {
@@ -68795,93 +70150,6 @@ var StandardRPCLink = class extends StandardLink {
68795
70150
  }
68796
70151
  };
68797
70152
 
68798
- // node_modules/.pnpm/@orpc+client@1.15.4/node_modules/@orpc/client/dist/adapters/fetch/index.mjs
68799
- var CompositeLinkFetchPlugin = class extends CompositeStandardLinkPlugin {
68800
- initRuntimeAdapter(options) {
68801
- for (const plugin of this.plugins) {
68802
- plugin.initRuntimeAdapter?.(options);
68803
- }
68804
- }
68805
- };
68806
- var LinkFetchClient = class {
68807
- fetch;
68808
- toFetchRequestOptions;
68809
- adapterInterceptors;
68810
- constructor(options) {
68811
- const plugin = new CompositeLinkFetchPlugin(options.plugins);
68812
- plugin.initRuntimeAdapter(options);
68813
- this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
68814
- this.toFetchRequestOptions = options;
68815
- this.adapterInterceptors = toArray(options.adapterInterceptors);
68816
- }
68817
- async call(standardRequest, options, path43, input2) {
68818
- const request7 = toFetchRequest(standardRequest, this.toFetchRequestOptions);
68819
- const fetchResponse = await intercept(
68820
- this.adapterInterceptors,
68821
- { ...options, request: request7, path: path43, input: input2, init: { redirect: "manual" } },
68822
- ({ request: request22, path: path210, input: input22, init, ...options2 }) => this.fetch(request22, init, options2, path210, input22)
68823
- );
68824
- const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request7.signal });
68825
- return lazyResponse;
68826
- }
68827
- };
68828
- var RPCLink = class extends StandardRPCLink {
68829
- constructor(options) {
68830
- const linkClient = new LinkFetchClient(options);
68831
- super(linkClient, options);
68832
- }
68833
- };
68834
-
68835
- // node_modules/.pnpm/@orpc+contract@1.15.4/node_modules/@orpc/contract/dist/shared/contract.D_dZrO__.mjs
68836
- var ValidationError = class extends Error {
68837
- issues;
68838
- data;
68839
- constructor(options) {
68840
- super(options.message, options);
68841
- this.issues = options.issues;
68842
- this.data = options.data;
68843
- }
68844
- };
68845
- function mergeErrorMap(errorMap1, errorMap2) {
68846
- return { ...errorMap1, ...errorMap2 };
68847
- }
68848
- async function validateORPCError(map3, error62) {
68849
- const { code, status, message, data, cause, defined } = error62;
68850
- const config2 = map3?.[error62.code];
68851
- if (!config2 || fallbackORPCErrorStatus(error62.code, config2.status) !== error62.status) {
68852
- return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error62;
68853
- }
68854
- if (!config2.data) {
68855
- return defined ? error62 : new ORPCError(code, { defined: true, status, message, data, cause });
68856
- }
68857
- const validated2 = await config2.data["~standard"].validate(error62.data);
68858
- if (validated2.issues) {
68859
- return defined ? new ORPCError(code, { defined: false, status, message, data, cause }) : error62;
68860
- }
68861
- return new ORPCError(code, { defined: true, status, message, data: validated2.value, cause });
68862
- }
68863
- var ContractProcedure = class {
68864
- /**
68865
- * This property holds the defined options for the contract procedure.
68866
- */
68867
- "~orpc";
68868
- constructor(def) {
68869
- if (def.route?.successStatus && isORPCErrorStatus(def.route.successStatus)) {
68870
- throw new Error("[ContractProcedure] Invalid successStatus.");
68871
- }
68872
- if (Object.values(def.errorMap).some((val) => val && val.status && !isORPCErrorStatus(val.status))) {
68873
- throw new Error("[ContractProcedure] Invalid error status code.");
68874
- }
68875
- this["~orpc"] = def;
68876
- }
68877
- };
68878
- function isContractProcedure(item) {
68879
- if (item instanceof ContractProcedure) {
68880
- return true;
68881
- }
68882
- return (typeof item === "object" || typeof item === "function") && item !== null && "~orpc" in item && typeof item["~orpc"] === "object" && item["~orpc"] !== null && "errorMap" in item["~orpc"] && "route" in item["~orpc"] && "meta" in item["~orpc"];
68883
- }
68884
-
68885
70153
  // node_modules/.pnpm/@orpc+contract@1.15.4/node_modules/@orpc/contract/dist/index.mjs
68886
70154
  function mergeMeta(meta1, meta22) {
68887
70155
  return { ...meta1, ...meta22 };
@@ -69218,7 +70486,7 @@ function middlewareOutputFn(output2) {
69218
70486
  function createProcedureClient(lazyableProcedure, ...rest) {
69219
70487
  const options = resolveMaybeOptionalOptions(rest);
69220
70488
  return async (...[input2, callerOptions]) => {
69221
- const path43 = toArray(options.path);
70489
+ const path44 = toArray(options.path);
69222
70490
  const { default: procedure } = await unlazy(lazyableProcedure);
69223
70491
  const clientContext = callerOptions?.context ?? {};
69224
70492
  const context = await value(options.context ?? {}, clientContext);
@@ -69233,7 +70501,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
69233
70501
  const output2 = await runWithSpan(
69234
70502
  { name: "call_procedure", signal: callerOptions?.signal },
69235
70503
  (span) => {
69236
- span?.setAttribute("procedure.path", [...path43]);
70504
+ span?.setAttribute("procedure.path", [...path44]);
69237
70505
  return intercept(
69238
70506
  toArray(options.interceptors),
69239
70507
  {
@@ -69241,7 +70509,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
69241
70509
  input: input2,
69242
70510
  // input only optional when it undefinable so we can safely cast it
69243
70511
  errors,
69244
- path: path43,
70512
+ path: path44,
69245
70513
  procedure,
69246
70514
  signal: callerOptions?.signal,
69247
70515
  lastEventId: callerOptions?.lastEventId
@@ -69363,10 +70631,10 @@ var HIDDEN_ROUTER_CONTRACT_SYMBOL = /* @__PURE__ */ Symbol("ORPC_HIDDEN_ROUTER_C
69363
70631
  function getHiddenRouterContract(router) {
69364
70632
  return router[HIDDEN_ROUTER_CONTRACT_SYMBOL];
69365
70633
  }
69366
- function getRouter(router, path43) {
70634
+ function getRouter(router, path44) {
69367
70635
  let current = router;
69368
- for (let i2 = 0; i2 < path43.length; i2++) {
69369
- const segment = path43[i2];
70636
+ for (let i2 = 0; i2 < path44.length; i2++) {
70637
+ const segment = path44[i2];
69370
70638
  if (!current) {
69371
70639
  return void 0;
69372
70640
  }
@@ -69381,7 +70649,7 @@ function getRouter(router, path43) {
69381
70649
  continue;
69382
70650
  }
69383
70651
  const lazied = current;
69384
- const rest = path43.slice(i2);
70652
+ const rest = path44.slice(i2);
69385
70653
  return lazy2(async () => {
69386
70654
  const unwrapped = await unlazy(lazied);
69387
70655
  const next = getRouter(unwrapped.default, rest);
@@ -69826,6 +71094,43 @@ var os7 = new Builder({
69826
71094
  dedupeLeadingMiddlewares: true
69827
71095
  });
69828
71096
 
71097
+ // node_modules/.pnpm/@orpc+client@1.15.4/node_modules/@orpc/client/dist/adapters/fetch/index.mjs
71098
+ var CompositeLinkFetchPlugin = class extends CompositeStandardLinkPlugin {
71099
+ initRuntimeAdapter(options) {
71100
+ for (const plugin of this.plugins) {
71101
+ plugin.initRuntimeAdapter?.(options);
71102
+ }
71103
+ }
71104
+ };
71105
+ var LinkFetchClient = class {
71106
+ fetch;
71107
+ toFetchRequestOptions;
71108
+ adapterInterceptors;
71109
+ constructor(options) {
71110
+ const plugin = new CompositeLinkFetchPlugin(options.plugins);
71111
+ plugin.initRuntimeAdapter(options);
71112
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);
71113
+ this.toFetchRequestOptions = options;
71114
+ this.adapterInterceptors = toArray(options.adapterInterceptors);
71115
+ }
71116
+ async call(standardRequest, options, path44, input2) {
71117
+ const request7 = toFetchRequest(standardRequest, this.toFetchRequestOptions);
71118
+ const fetchResponse = await intercept(
71119
+ this.adapterInterceptors,
71120
+ { ...options, request: request7, path: path44, input: input2, init: { redirect: "manual" } },
71121
+ ({ request: request22, path: path210, input: input22, init, ...options2 }) => this.fetch(request22, init, options2, path210, input22)
71122
+ );
71123
+ const lazyResponse = toStandardLazyResponse(fetchResponse, { signal: request7.signal });
71124
+ return lazyResponse;
71125
+ }
71126
+ };
71127
+ var RPCLink = class extends StandardRPCLink {
71128
+ constructor(options) {
71129
+ const linkClient = new LinkFetchClient(options);
71130
+ super(linkClient, options);
71131
+ }
71132
+ };
71133
+
69829
71134
  // node_modules/.pnpm/@orpc+standard-server-node@1.15.4/node_modules/@orpc/standard-server-node/dist/index.mjs
69830
71135
  var import_node_buffer = require("node:buffer");
69831
71136
  var import_node_stream = require("node:stream");
@@ -69959,8 +71264,8 @@ function toAbortSignal(stream) {
69959
71264
  function toStandardUrl(req) {
69960
71265
  const protocol = "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
69961
71266
  const origin = guard(() => new URL(`${protocol}//${req.headers.host ?? "localhost"}`).origin) ?? `${protocol}//localhost`;
69962
- const path43 = req.originalUrl ?? req.url ?? "/";
69963
- return new URL(`${origin}${path43.startsWith("/") ? "" : "/"}${path43}`);
71267
+ const path44 = req.originalUrl ?? req.url ?? "/";
71268
+ return new URL(`${origin}${path44.startsWith("/") ? "" : "/"}${path44}`);
69964
71269
  }
69965
71270
  function toStandardLazyRequest(req, res) {
69966
71271
  const signal = toAbortSignal(res);
@@ -70159,8 +71464,8 @@ var StandardRPCMatcher = class {
70159
71464
  constructor(options = {}) {
70160
71465
  this.filter = options.filter ?? true;
70161
71466
  }
70162
- init(router, path43 = []) {
70163
- const laziedOptions = traverseContractProcedures({ router, path: path43 }, (traverseOptions) => {
71467
+ init(router, path44 = []) {
71468
+ const laziedOptions = traverseContractProcedures({ router, path: path44 }, (traverseOptions) => {
70164
71469
  if (!value(this.filter, traverseOptions)) {
70165
71470
  return;
70166
71471
  }
@@ -70438,16 +71743,19 @@ var RcAnswerOutputSchema = external_exports.strictObject({
70438
71743
  // src/frontdoor/rcApi.ts
70439
71744
  var RC_ORPC_PATH_PREFIX = "/__agent-shim/orpc";
70440
71745
  var RC_SUBSCRIBER_BUFFER_EVENTS = 100;
70441
- function createRcApiRouter(deps) {
70442
- const authed = os7.$context().use(({ context, next }) => {
71746
+ function doorApiAuth(expectedToken) {
71747
+ return os7.$context().use(({ context, next }) => {
70443
71748
  const presented = context.headers.authorization;
70444
71749
  const bearerPrefix = "bearer ".length;
70445
71750
  const token = typeof presented === "string" && presented.slice(0, bearerPrefix).toLowerCase() === "bearer " ? presented.slice(bearerPrefix) : void 0;
70446
- if (token === void 0 || !isLiveCapability(token, [deps.expectedToken])) {
71751
+ if (token === void 0 || !isLiveCapability(token, [expectedToken])) {
70447
71752
  throw new ORPCError("UNAUTHORIZED", { message: "the front door's typed API demands this generation's control token as a Bearer credential" });
70448
71753
  }
70449
71754
  return next();
70450
71755
  });
71756
+ }
71757
+ function createRcApiRouter(deps) {
71758
+ const authed = doorApiAuth(deps.expectedToken);
70451
71759
  const delivered = (sessionId, result) => {
70452
71760
  if (!result.ok) {
70453
71761
  throw new ORPCError("BAD_GATEWAY", { message: result.message });
@@ -70516,16 +71824,16 @@ function createRcApiRouter(deps) {
70516
71824
  }
70517
71825
  };
70518
71826
  }
70519
- function createRcApiNodeHandler(deps) {
70520
- const handler = new RPCHandler(createRcApiRouter(deps), { plugins: [new BodyLimitPlugin({ maxBodySize: CONTROL_BODY_CAP_BYTES })] });
71827
+ function doorApiNodeHandlerOf(router) {
71828
+ const handler = new RPCHandler(router, { plugins: [new BodyLimitPlugin({ maxBodySize: CONTROL_BODY_CAP_BYTES })] });
70521
71829
  return {
70522
71830
  pathPrefix: RC_ORPC_PATH_PREFIX,
70523
71831
  handle: async (request7, response) => await handler.handle(request7, response, { context: { headers: request7.headers }, prefix: RC_ORPC_PATH_PREFIX })
70524
71832
  };
70525
71833
  }
70526
- function frontDoorRcApiClient(port, ca, token) {
71834
+ function frontDoorApiLink(port, ca, token) {
70527
71835
  const dispatcher = new import_undici2.Agent({ connect: { ca } });
70528
- const link = new RPCLink({
71836
+ return new RPCLink({
70529
71837
  url: `https://127.0.0.1:${String(port)}${RC_ORPC_PATH_PREFIX}`,
70530
71838
  headers: { authorization: `Bearer ${token}` },
70531
71839
  // undici's own Request and Response types and the global ones are distinct declarations of the same standard shapes (the package's bundled types sit beside @types/node's own), and its fetch refuses the global Request instance outright, so the call is rebuilt from the request's parts and the answer re-wrapped through the global constructors, never cast between the two. The request body is one bounded JSON object (the same protocol cap the handler enforces), so reading it whole costs nothing; it is the answer that streams.
@@ -70541,11 +71849,255 @@ function frontDoorRcApiClient(port, ca, token) {
70541
71849
  return new Response(answered.body, { status: answered.status, statusText: answered.statusText, headers: [...answered.headers] });
70542
71850
  }
70543
71851
  });
70544
- return createORPCClient(link);
71852
+ }
71853
+ function frontDoorRcApiClient(port, ca, token) {
71854
+ return createORPCClient(frontDoorApiLink(port, ca, token));
71855
+ }
71856
+
71857
+ // src/frontdoor/eventSchemas.ts
71858
+ var DOOR_EVENT_SOURCE_RC = "rc";
71859
+ var LAUNCH_EVENT_SOURCE = "launch";
71860
+ var DoorEventSchema = external_exports.strictObject({
71861
+ source: external_exports.string().min(1),
71862
+ /** A positive integer because the backbone's counters start at one and only ever increase. */
71863
+ sequence: external_exports.number().int().positive(),
71864
+ payload: external_exports.unknown()
71865
+ });
71866
+ var DoorEventSourceQuerySchema = external_exports.strictObject({
71867
+ sources: external_exports.array(external_exports.string().min(1)).min(1).optional()
71868
+ });
71869
+ var LaunchLifecycleEventSchema = external_exports.strictObject({
71870
+ kind: external_exports.enum(["registered", "pruned", "ended"]),
71871
+ pid: external_exports.number().int().positive(),
71872
+ startedAt: external_exports.number(),
71873
+ observedAt: external_exports.number()
71874
+ });
71875
+
71876
+ // src/frontdoor/eventsApi.ts
71877
+ function createEventsApiRouter(deps) {
71878
+ const authed = doorApiAuth(deps.expectedToken);
71879
+ return {
71880
+ events: {
71881
+ subscribe: authed.input(DoorEventSourceQuerySchema).output(eventIterator(DoorEventSchema)).handler(async function* ({ input: input2, signal }) {
71882
+ if (input2.sources !== void 0) {
71883
+ const live = deps.events.sources();
71884
+ const unknown2 = input2.sources.filter((source) => !live.includes(source));
71885
+ if (unknown2.length > 0) {
71886
+ throw new ORPCError("NOT_FOUND", { message: `the door publishes no event source named ${unknown2.map((source) => `"${source}"`).join(", ")}; the live sources are ${live.map((source) => `"${source}"`).join(", ")}` });
71887
+ }
71888
+ }
71889
+ const stream = deps.events.stream(input2.sources);
71890
+ const ended = new Promise((resolve) => {
71891
+ signal?.addEventListener("abort", () => {
71892
+ resolve();
71893
+ }, { once: true });
71894
+ });
71895
+ try {
71896
+ for (; ; ) {
71897
+ signal?.throwIfAborted();
71898
+ const next = await Promise.race([stream.next(), ended.then(() => ({ value: void 0, done: true }))]);
71899
+ if (next.done === true) {
71900
+ signal?.throwIfAborted();
71901
+ return;
71902
+ }
71903
+ yield withEventMeta(next.value, { id: String(next.value.sequence) });
71904
+ }
71905
+ } finally {
71906
+ stream.close();
71907
+ }
71908
+ })
71909
+ }
71910
+ };
71911
+ }
71912
+
71913
+ // src/frontdoor/controlApi.ts
71914
+ function createControlApiRouter(deps) {
71915
+ const authed = doorApiAuth(deps.expectedToken);
71916
+ return {
71917
+ usage: {
71918
+ list: authed.output(UsageListOutputSchema).handler(() => ({ snapshots: deps.usageSnapshots() })),
71919
+ effectiveWindow: authed.input(UsageWindowsInputSchema).output(UsageWindowsOutputSchema).handler(({ input: input2 }) => {
71920
+ const snapshot = deps.usageSnapshotOf(input2.identity);
71921
+ if (snapshot === void 0) {
71922
+ throw new ORPCError("NOT_FOUND", { message: `identity ${input2.identity} has no usage snapshot yet, so no quota window has been observed for it` });
71923
+ }
71924
+ const provider = input2.provider ?? ANTHROPIC_PROVIDER;
71925
+ const rateLimit = snapshot.providers[provider]?.rateLimit;
71926
+ const unified = rateLimit?.unified;
71927
+ const now = deps.now();
71928
+ return {
71929
+ identity: snapshot.identity,
71930
+ provider,
71931
+ ...rateLimit === void 0 ? {} : { observedAt: rateLimit.observedAt },
71932
+ ...unified?.fiveHour === void 0 ? {} : { fiveHour: effectiveWindow(unified.fiveHour, now) },
71933
+ ...unified?.sevenDay === void 0 ? {} : { sevenDay: effectiveWindow(unified.sevenDay, now) }
71934
+ };
71935
+ })
71936
+ },
71937
+ frontdoor: {
71938
+ status: authed.output(FrontDoorStatusOutputSchema).handler(() => deps.frontDoorStatus()),
71939
+ sessions: authed.output(FrontDoorSessionsOutputSchema).handler(() => ({ sessions: deps.frontDoorStatus().sessions }))
71940
+ },
71941
+ check: {
71942
+ // The report's own JSON shape is the contract (the same one `check --json` prints and `checkReportSchema.ts` defines), so the procedure returns exactly that conversion.
71943
+ run: authed.input(CheckRunInputSchema).output(CheckReportJsonSchema).handler(({ input: input2 }) => checkReportToJson(deps.checkReport(input2.path, input2.identity)))
71944
+ },
71945
+ doctor: {
71946
+ run: authed.output(DoctorRunOutputSchema).handler(() => deps.doctorReport())
71947
+ }
71948
+ };
71949
+ }
71950
+ function createDoorApiRouter(deps) {
71951
+ return { ...createRcApiRouter(deps), ...createControlApiRouter(deps), ...createEventsApiRouter(deps) };
71952
+ }
71953
+ function createDoorApiNodeHandler(deps) {
71954
+ return doorApiNodeHandlerOf(createDoorApiRouter(deps));
71955
+ }
71956
+
71957
+ // src/frontdoor/eventHub.ts
71958
+ var DOOR_EVENT_BUFFER_EVENTS = 100;
71959
+ function createDoorEventHub() {
71960
+ const sequences = /* @__PURE__ */ new Map();
71961
+ const registered = /* @__PURE__ */ new Set();
71962
+ const every = /* @__PURE__ */ new Set();
71963
+ const bySource = /* @__PURE__ */ new Map();
71964
+ const deliver = (event) => {
71965
+ for (const listener of every) {
71966
+ listener(event);
71967
+ }
71968
+ for (const listener of bySource.get(event.source) ?? []) {
71969
+ listener(event);
71970
+ }
71971
+ };
71972
+ const publish = (source, payload) => {
71973
+ const sequence2 = (sequences.get(source) ?? 0) + 1;
71974
+ sequences.set(source, sequence2);
71975
+ deliver({ source, sequence: sequence2, payload });
71976
+ };
71977
+ const addListener = (sources, listener) => {
71978
+ if (sources === void 0) {
71979
+ every.add(listener);
71980
+ return () => {
71981
+ every.delete(listener);
71982
+ };
71983
+ }
71984
+ const listenersFor = (source) => {
71985
+ const listeners = bySource.get(source) ?? /* @__PURE__ */ new Set();
71986
+ bySource.set(source, listeners);
71987
+ return listeners;
71988
+ };
71989
+ const detachers = sources.map((source) => {
71990
+ const listeners = listenersFor(source);
71991
+ listeners.add(listener);
71992
+ return () => {
71993
+ listeners.delete(listener);
71994
+ if (listeners.size === 0) {
71995
+ bySource.delete(source);
71996
+ }
71997
+ };
71998
+ });
71999
+ return () => {
72000
+ for (const detach of detachers) {
72001
+ detach();
72002
+ }
72003
+ };
72004
+ };
72005
+ return {
72006
+ publisher: (source) => {
72007
+ registered.add(source);
72008
+ return {
72009
+ source,
72010
+ publish: (payload) => {
72011
+ publish(source, payload);
72012
+ }
72013
+ };
72014
+ },
72015
+ subscribe: addListener,
72016
+ stream: (sources) => {
72017
+ const queue = [];
72018
+ let wake;
72019
+ let closed = false;
72020
+ const detach = addListener(sources, (event) => {
72021
+ if (queue.length >= DOOR_EVENT_BUFFER_EVENTS) {
72022
+ queue.shift();
72023
+ }
72024
+ queue.push(event);
72025
+ wake?.();
72026
+ });
72027
+ return {
72028
+ next: async () => {
72029
+ for (; ; ) {
72030
+ const event = queue.shift();
72031
+ if (event !== void 0) {
72032
+ return { value: event, done: false };
72033
+ }
72034
+ if (closed) {
72035
+ return { value: void 0, done: true };
72036
+ }
72037
+ await new Promise((resolve) => {
72038
+ wake = resolve;
72039
+ });
72040
+ }
72041
+ },
72042
+ close: () => {
72043
+ closed = true;
72044
+ detach();
72045
+ wake?.();
72046
+ }
72047
+ };
72048
+ },
72049
+ sources: () => [...registered].sort()
72050
+ };
72051
+ }
72052
+ function rcFanoutOnDoorHub(fanout, hub) {
72053
+ const publisher = hub.publisher(DOOR_EVENT_SOURCE_RC);
72054
+ return {
72055
+ publish: (event) => {
72056
+ fanout.publish(event);
72057
+ publisher.publish(event);
72058
+ },
72059
+ subscribe: (session, listener) => fanout.subscribe(session, listener)
72060
+ };
72061
+ }
72062
+
72063
+ // src/frontdoor/launchEvents.ts
72064
+ function createLaunchEventPublisher(hub, now) {
72065
+ const publisher = hub.publisher(LAUNCH_EVENT_SOURCE);
72066
+ let known;
72067
+ return {
72068
+ observe: (sessions, pruned) => {
72069
+ const previous = known;
72070
+ const listed = new Map(sessions.map((session) => [session.pid, session]));
72071
+ const prunedSet = new Set(pruned);
72072
+ known = new Map([...listed].filter(([pid]) => !prunedSet.has(pid)));
72073
+ if (previous === void 0) {
72074
+ return;
72075
+ }
72076
+ const emit = (kind, pid, startedAt) => {
72077
+ publisher.publish({ kind, pid, startedAt, observedAt: now() });
72078
+ };
72079
+ for (const pid of pruned) {
72080
+ const session = listed.get(pid);
72081
+ if (session !== void 0) {
72082
+ emit("pruned", pid, session.startedAt);
72083
+ }
72084
+ }
72085
+ for (const [pid, session] of previous) {
72086
+ if (!listed.has(pid) && !prunedSet.has(pid)) {
72087
+ emit("ended", pid, session.startedAt);
72088
+ }
72089
+ }
72090
+ for (const [pid, session] of listed) {
72091
+ if (!previous.has(pid) && !prunedSet.has(pid)) {
72092
+ emit("registered", pid, session.startedAt);
72093
+ }
72094
+ }
72095
+ }
72096
+ };
70545
72097
  }
70546
72098
 
70547
72099
  // src/frontdoor/headroomHop.ts
70548
- var http3 = __toESM(require("node:http"), 1);
72100
+ var http4 = __toESM(require("node:http"), 1);
70549
72101
  var HTTP_BAD_GATEWAY2 = HTTP_STATUS.badGateway;
70550
72102
  function responseHeaders(headers) {
70551
72103
  const result = {};
@@ -70599,7 +72151,7 @@ async function answerBadGateway(response, message) {
70599
72151
  await response.write(JSON.stringify({ type: "error", error: { type: "api_error", message } }));
70600
72152
  response.end();
70601
72153
  }
70602
- var HOP_AGENT = new http3.Agent({ keepAlive: false });
72154
+ var HOP_AGENT = new http4.Agent({ keepAlive: false });
70603
72155
  async function forwardThroughHeadroom(request7, response, target) {
70604
72156
  const { socketPath, headers } = target;
70605
72157
  await new Promise((resolve) => {
@@ -70627,7 +72179,7 @@ async function forwardThroughHeadroom(request7, response, target) {
70627
72179
  };
70628
72180
  void stream();
70629
72181
  };
70630
- const hop = http3.request({ socketPath, method: request7.method, path: request7.url, headers, agent: HOP_AGENT }, onUpstreamResponse);
72182
+ const hop = http4.request({ socketPath, method: request7.method, path: request7.url, headers, agent: HOP_AGENT }, onUpstreamResponse);
70631
72183
  hop.on("error", (error62) => {
70632
72184
  const phase = response.headersSent ? "mid-stream" : "before the response started";
70633
72185
  const code = "code" in error62 && typeof error62.code === "string" ? ` ${error62.code}` : "";
@@ -70816,7 +72368,7 @@ async function serveRouted(request7, deps) {
70816
72368
  }
70817
72369
 
70818
72370
  // src/codex/translate.ts
70819
- var import_node_crypto11 = require("node:crypto");
72371
+ var import_node_crypto13 = require("node:crypto");
70820
72372
 
70821
72373
  // src/codex/anthropic.ts
70822
72374
  var TextBlockSchema = external_exports.looseObject({ type: external_exports.literal("text"), text: external_exports.string() });
@@ -70895,7 +72447,8 @@ function resolveCodexConfig(config2) {
70895
72447
  sonnet: overrides?.sonnet ?? CODEX_DEFAULT_TIER_MODELS.sonnet,
70896
72448
  haiku: overrides?.haiku ?? CODEX_DEFAULT_TIER_MODELS.haiku
70897
72449
  },
70898
- effort: config2?.effort ?? CODEX_DEFAULT_EFFORT
72450
+ effort: config2?.effort ?? CODEX_DEFAULT_EFFORT,
72451
+ login: config2?.login ?? CODEX_DEFAULT_LOGIN
70899
72452
  };
70900
72453
  }
70901
72454
  function mapModel(requested, config2) {
@@ -70928,7 +72481,7 @@ function shortToolName(name, names) {
70928
72481
  if (name.length <= CODEX_TOOL_NAME_LIMIT) {
70929
72482
  return name;
70930
72483
  }
70931
- const hash2 = (0, import_node_crypto11.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
72484
+ const hash2 = (0, import_node_crypto13.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
70932
72485
  const shortened = `${name.slice(0, CODEX_TOOL_NAME_LIMIT - TOOL_NAME_HASH_CHARS - 1)}_${hash2}`;
70933
72486
  names.set(shortened, name);
70934
72487
  return shortened;
@@ -71204,17 +72757,17 @@ function unifiedQuotaHeaders(upstream, rejected, quotaError) {
71204
72757
  }
71205
72758
  return headers;
71206
72759
  }
71207
- var MS_PER_SECOND5 = 1e3;
72760
+ var MS_PER_SECOND6 = 1e3;
71208
72761
  function buildUsageSnapshot(upstream, quotaError, nowMs) {
71209
72762
  const used7 = upstream.get("x-codex-primary-used-percent") ?? (quotaError === void 0 ? null : EXHAUSTED_PERCENT);
71210
72763
  const reset7 = upstream.get("x-codex-primary-reset-at") ?? (quotaError?.resets_at === void 0 ? null : String(quotaError.resets_at));
71211
- const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND5).toISOString() } : void 0;
72764
+ const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND6).toISOString() } : void 0;
71212
72765
  let fiveHour;
71213
72766
  if (Number(upstream.get("x-codex-secondary-window-minutes")) > 0) {
71214
72767
  const used5 = upstream.get("x-codex-secondary-used-percent");
71215
72768
  const reset5 = upstream.get("x-codex-secondary-reset-at");
71216
72769
  if (used5 !== null && reset5 !== null) {
71217
- fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND5).toISOString() };
72770
+ fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND6).toISOString() };
71218
72771
  }
71219
72772
  }
71220
72773
  if (sevenDay === void 0 && fiveHour === void 0) {
@@ -71431,12 +72984,13 @@ function createCodexRoute(ports) {
71431
72984
  }
71432
72985
  const body = parsed.data;
71433
72986
  const requestedModel = body.model ?? "";
72987
+ const upstreamPorts = ports.upstreams[config2.login];
71434
72988
  const { request: upstreamRequest, toolNames } = translateRequest(body, config2);
71435
72989
  const started = ports.now();
71436
72990
  const elapsed = () => `${String(ports.now() - started)}ms`;
71437
72991
  let upstream;
71438
72992
  try {
71439
- upstream = await callCodex(ports.upstream, upstreamRequest, sessionIdFor(body.metadata?.user_id, ports.upstream.randomId), request7.signal);
72993
+ upstream = await callCodex(upstreamPorts, upstreamRequest, sessionIdFor(body.metadata?.user_id, upstreamPorts.randomId), request7.signal);
71440
72994
  } catch (error62) {
71441
72995
  if (request7.signal.aborted) {
71442
72996
  return errorResponse(HTTP_STATUS.clientClosedRequest, "client disconnected");
@@ -71469,7 +73023,7 @@ function createCodexRoute(ports) {
71469
73023
  });
71470
73024
  }
71471
73025
  snapshot(void 0);
71472
- const relay = createRelay({ requestedModel, toolNames, fallbackId: () => `msg_${ports.upstream.randomId()}` });
73026
+ const relay = createRelay({ requestedModel, toolNames, fallbackId: () => `msg_${upstreamPorts.randomId()}` });
71473
73027
  const upstreamBody = upstream.body;
71474
73028
  const quota = { ...quotaHeaders(upstream.headers), ...unifiedQuotaHeaders(upstream.headers, false, void 0) };
71475
73029
  const logCompleted = (message, usage) => {
@@ -71622,8 +73176,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
71622
73176
  request7.body.resume();
71623
73177
  return;
71624
73178
  }
71625
- const path43 = new URL(request7.url, "http://127.0.0.1").pathname;
71626
- const translated = { method: request7.method, path: path43, body, signal: request7.signal };
73179
+ const path44 = new URL(request7.url, "http://127.0.0.1").pathname;
73180
+ const translated = { method: request7.method, path: path44, body, signal: request7.signal };
71627
73181
  const routed = await route(translated);
71628
73182
  if (request7.signal.aborted) {
71629
73183
  return;
@@ -71634,7 +73188,7 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
71634
73188
  }
71635
73189
 
71636
73190
  // src/frontdoor/passthrough.ts
71637
- var http4 = __toESM(require("node:http"), 1);
73191
+ var http5 = __toESM(require("node:http"), 1);
71638
73192
  var https4 = __toESM(require("node:https"), 1);
71639
73193
  function responseHeaders2(headers) {
71640
73194
  const result = {};
@@ -71657,7 +73211,7 @@ function createPassthroughRoute(name, target) {
71657
73211
  headroomUpstream: target.headroomUpstream,
71658
73212
  serve: async (request7, response) => {
71659
73213
  const incoming = new URL(request7.url, "http://127.0.0.1");
71660
- const path43 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
73214
+ const path44 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
71661
73215
  const headers = forwardableHeaders(request7.headers);
71662
73216
  delete headers.host;
71663
73217
  await new Promise((resolve) => {
@@ -71665,7 +73219,7 @@ function createPassthroughRoute(name, target) {
71665
73219
  host: base.hostname,
71666
73220
  port: base.port === "" ? void 0 : Number(base.port),
71667
73221
  method: request7.method,
71668
- path: `${basePath}${path43}${incoming.search}`,
73222
+ path: `${basePath}${path44}${incoming.search}`,
71669
73223
  headers,
71670
73224
  agent
71671
73225
  };
@@ -71688,7 +73242,7 @@ function createPassthroughRoute(name, target) {
71688
73242
  };
71689
73243
  void stream();
71690
73244
  };
71691
- const forward = tls2 ? https4.request(options, onUpstreamResponse) : http4.request(options, onUpstreamResponse);
73245
+ const forward = tls2 ? https4.request(options, onUpstreamResponse) : http5.request(options, onUpstreamResponse);
71692
73246
  forward.on("error", (error62) => {
71693
73247
  if (!response.headersSent) {
71694
73248
  response.start(HTTP_STATUS.badGateway, { "Content-Type": "application/json" });
@@ -71714,7 +73268,7 @@ function createPassthroughRoute(name, target) {
71714
73268
 
71715
73269
  // src/frontdoor/providerRoute.ts
71716
73270
  function createProviderRouteResolver(deps) {
71717
- const isRcSelfHostPath = (path43) => path43 === "/v1/code/sessions" || path43.startsWith("/v1/code/sessions/") || path43 === "/v1/sessions" || path43.startsWith("/v1/sessions/");
73271
+ const isRcSelfHostPath = (path44) => path44 === "/v1/code/sessions" || path44.startsWith("/v1/code/sessions/") || path44 === "/v1/sessions" || path44.startsWith("/v1/sessions/");
71718
73272
  const oauthRoute = createPassthroughRoute("anthropic", { baseUrl: `https://${CONNECT_INTERCEPT_HOST}:${String(HTTPS_PORT)}`, stripPrefix: void 0, headroomUpstream: void 0 });
71719
73273
  const passthroughByTarget = /* @__PURE__ */ new Map();
71720
73274
  const passthroughFor = (name, target) => {
@@ -71728,13 +73282,13 @@ function createProviderRouteResolver(deps) {
71728
73282
  return route;
71729
73283
  };
71730
73284
  const resolve = (request7) => {
71731
- const path43 = new URL(request7.url, "http://127.0.0.1").pathname;
71732
- const scoped = parseProviderPath(path43);
73285
+ const path44 = new URL(request7.url, "http://127.0.0.1").pathname;
73286
+ const scoped = parseProviderPath(path44);
71733
73287
  if (scoped === void 0) {
71734
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path43)) {
73288
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path44)) {
71735
73289
  return { ok: true, route: deps.rcSelfHostRoute };
71736
73290
  }
71737
- return path43.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path43}` };
73291
+ return path44.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path44}` };
71738
73292
  }
71739
73293
  const { provider } = scoped;
71740
73294
  let definition;
@@ -71774,7 +73328,7 @@ function createProviderRouteResolver(deps) {
71774
73328
  }
71775
73329
 
71776
73330
  // src/frontdoor/rcCredentialStore.ts
71777
- var import_node_path32 = __toESM(require("node:path"), 1);
73331
+ var import_node_path34 = __toESM(require("node:path"), 1);
71778
73332
  function isSafeSessionId(sessionId) {
71779
73333
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
71780
73334
  }
@@ -71800,7 +73354,7 @@ function sequenceNumOfJson(value2) {
71800
73354
  }
71801
73355
  function createRcCredentialStore(fs19, dir) {
71802
73356
  fs19.mkdirPrivate(dir);
71803
- const fileFor = (sessionId) => import_node_path32.default.join(dir, `${sessionId}.json`);
73357
+ const fileFor = (sessionId) => import_node_path34.default.join(dir, `${sessionId}.json`);
71804
73358
  const readParsed = (sessionId) => {
71805
73359
  const raw = fs19.readFileUtf8(fileFor(sessionId));
71806
73360
  if (raw === void 0) {
@@ -71866,7 +73420,7 @@ var RC_SESSION_ID_PREFIX2 = "cse_";
71866
73420
  var RC_SELF_HOST_API_BASE_URL = "https://api.anthropic.com";
71867
73421
  var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
71868
73422
  var HTTP_CONFLICT = 409;
71869
- var MS_PER_SECOND6 = 1e3;
73423
+ var MS_PER_SECOND7 = 1e3;
71870
73424
  var HTTP_SERVICE_UNAVAILABLE = 503;
71871
73425
  var RC_SELF_HOST_WORKER_JWT_TTL_SECONDS = 46800;
71872
73426
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
@@ -71941,7 +73495,7 @@ function parseJsonObject2(body) {
71941
73495
  function mintWorkerJwt(randomToken, issuedAt) {
71942
73496
  const encode3 = (value2) => Buffer.from(JSON.stringify(value2), "utf8").toString("base64url");
71943
73497
  const header = encode3({ alg: "HS256", typ: "JWT" });
71944
- const payload = encode3({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND6) / MS_PER_SECOND6), iat: Math.floor(issuedAt / MS_PER_SECOND6) });
73498
+ const payload = encode3({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND7) / MS_PER_SECOND7), iat: Math.floor(issuedAt / MS_PER_SECOND7) });
71945
73499
  return `${header}.${payload}.${Buffer.from(randomToken(), "utf8").toString("base64url")}`;
71946
73500
  }
71947
73501
  function growthBookFeatures() {
@@ -72392,7 +73946,7 @@ data: ${JSON.stringify(envelope)}
72392
73946
  }
72393
73947
  if (method === "POST" && pathname.startsWith("/api/eval/")) {
72394
73948
  await readBody3(request7, CONTROL_BODY_CAP_BYTES);
72395
- answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND6) });
73949
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND7) });
72396
73950
  return true;
72397
73951
  }
72398
73952
  if (method === "GET" && pathname === "/api/oauth/profile") {
@@ -72450,7 +74004,7 @@ data: ${JSON.stringify(envelope)}
72450
74004
  }
72451
74005
 
72452
74006
  // src/frontdoor/rcSelfHostMint.ts
72453
- var import_node_path33 = __toESM(require("node:path"), 1);
74007
+ var import_node_path35 = __toESM(require("node:path"), 1);
72454
74008
  var CREDENTIALS_FILE = ".credentials.json";
72455
74009
  var CLAUDE_JSON2 = ".claude.json";
72456
74010
  var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
@@ -72474,7 +74028,7 @@ function readJsonObject(fs19, file2) {
72474
74028
  return isRecord6(parsed) ? parsed : void 0;
72475
74029
  }
72476
74030
  function readRcSelfHostRecord(fs19, frontdoorDir) {
72477
- const parsed = readJsonObject(fs19, import_node_path33.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
74031
+ const parsed = readJsonObject(fs19, import_node_path35.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
72478
74032
  if (parsed === void 0) {
72479
74033
  return void 0;
72480
74034
  }
@@ -72488,11 +74042,11 @@ function mintRcSelfHostCredential(deps) {
72488
74042
  if (!isIdentityName(deps.identity)) {
72489
74043
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
72490
74044
  }
72491
- const identityDir = import_node_path33.default.join(deps.identitiesDir, deps.identity);
72492
- const credentialsFile = import_node_path33.default.join(identityDir, CREDENTIALS_FILE);
72493
- const claudeJsonFile = import_node_path33.default.join(identityDir, CLAUDE_JSON2);
72494
- const recordDir = import_node_path33.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
72495
- const recordFile = import_node_path33.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
74045
+ const identityDir = import_node_path35.default.join(deps.identitiesDir, deps.identity);
74046
+ const credentialsFile = import_node_path35.default.join(identityDir, CREDENTIALS_FILE);
74047
+ const claudeJsonFile = import_node_path35.default.join(identityDir, CLAUDE_JSON2);
74048
+ const recordDir = import_node_path35.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
74049
+ const recordFile = import_node_path35.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
72496
74050
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
72497
74051
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
72498
74052
  const existingOauth = isRecord6(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -72508,7 +74062,7 @@ function mintRcSelfHostCredential(deps) {
72508
74062
  const organizationUuid = deps.newUuid();
72509
74063
  const accountUuid = deps.newUuid();
72510
74064
  const mintedAt = new Date(deps.now()).toISOString();
72511
- deps.fs.mkdirPrivate(import_node_path33.default.dirname(credentialsFile));
74065
+ deps.fs.mkdirPrivate(import_node_path35.default.dirname(credentialsFile));
72512
74066
  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)}
72513
74067
  `);
72514
74068
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -72820,6 +74374,59 @@ function createRcStreamHub(deps) {
72820
74374
  };
72821
74375
  }
72822
74376
 
74377
+ // src/frontdoor/status.ts
74378
+ function headroomSocketTarget(fsPort, trust, paths) {
74379
+ const socketPath = readHeadroomState(fsPort, paths.headroomStateFile)?.socketPath;
74380
+ return socketPath === void 0 ? void 0 : verifyHeadroomSocket(socketPath, trust);
74381
+ }
74382
+ function collectFrontDoorStatus(fsPort, socketTrust, paths, isRunning) {
74383
+ const state = readFrontDoorState(fsPort, paths.frontdoorStateFile) ?? {};
74384
+ return {
74385
+ state,
74386
+ supervisorAlive: state.supervisorPid !== void 0 && isRunning(state.supervisorPid),
74387
+ sessions: listFrontDoorSessions(fsPort, paths.frontdoorSessionsDir).map((session) => ({ ...session, alive: isRunning(session.pid) })),
74388
+ headroomSocket: headroomSocketTarget(fsPort, socketTrust, paths),
74389
+ logPath: paths.frontdoorLogPath,
74390
+ logExists: fsPort.readFileUtf8(paths.frontdoorLogPath) !== void 0
74391
+ };
74392
+ }
74393
+ function formatFrontDoorStatus(status, caCertPath) {
74394
+ const lines = [];
74395
+ if (status.state.supervisorPid === void 0) {
74396
+ lines.push("supervisor: not running");
74397
+ } else {
74398
+ lines.push(`supervisor: pid ${String(status.state.supervisorPid)} (${status.supervisorAlive ? "alive" : "NOT running"})`);
74399
+ }
74400
+ if (status.state.port === void 0) {
74401
+ lines.push(`front door: not listening${status.state.lastPort === void 0 ? "" : ` (next start on 127.0.0.1:${String(status.state.lastPort)})`}`);
74402
+ } else {
74403
+ lines.push(`front door: listening on https://127.0.0.1:${String(status.state.port)}, routing /providers/<name> requests`);
74404
+ }
74405
+ if (status.state.connectPort === void 0) {
74406
+ lines.push(`connect surface: not listening${status.state.lastConnectPort === void 0 ? "" : ` (next start on 127.0.0.1:${String(status.state.lastConnectPort)})`}`);
74407
+ } else {
74408
+ lines.push(`connect surface: listening on 127.0.0.1:${String(status.state.connectPort)}, CA ${caCertPath}`);
74409
+ }
74410
+ if (status.headroomSocket === void 0) {
74411
+ lines.push("headroom hop: the daemon is not serving (sessions asking for headroom fail until it is up)");
74412
+ } else if (status.headroomSocket.refused === void 0) {
74413
+ lines.push(`headroom hop: daemon on unix socket ${status.headroomSocket.socketPath}`);
74414
+ } else {
74415
+ lines.push(`headroom hop: REFUSING the daemon's socket (sessions asking for headroom fail until it is fixed): ${status.headroomSocket.refused}`);
74416
+ }
74417
+ if (status.sessions.length === 0) {
74418
+ lines.push("sessions: none");
74419
+ } else {
74420
+ const pids = status.sessions.map((session) => `${String(session.pid)}${session.alive ? "" : " (dead)"}`);
74421
+ lines.push(`sessions: ${String(status.sessions.length)} registered (${pids.join(", ")})`);
74422
+ }
74423
+ if (status.state.lastError !== void 0) {
74424
+ lines.push(`last error: ${status.state.lastError}`);
74425
+ }
74426
+ lines.push(`daemon log: ${status.logPath}${status.logExists ? "" : " (not created yet)"}`);
74427
+ return lines;
74428
+ }
74429
+
72823
74430
  // src/usage/providerQuota.ts
72824
74431
  var ProviderQuotaError = class extends Error {
72825
74432
  constructor(source, detail) {
@@ -72827,7 +74434,7 @@ var ProviderQuotaError = class extends Error {
72827
74434
  this.name = "ProviderQuotaError";
72828
74435
  }
72829
74436
  };
72830
- var MS_PER_SECOND7 = 1e3;
74437
+ var MS_PER_SECOND8 = 1e3;
72831
74438
  var SECONDS_PER_HOUR = 3600;
72832
74439
  var HOURS_PER_DAY3 = 24;
72833
74440
  var DAYS_PER_MONTH = 30;
@@ -72839,8 +74446,8 @@ var ZAI_QUOTA_URL = `https://${ZAI_HOST}/api/monitor/usage/quota/limit`;
72839
74446
  var ZAI_UNIT_HOURS = 3;
72840
74447
  var ZAI_UNIT_MONTHS = 5;
72841
74448
  var ZAI_UNIT_MS = /* @__PURE__ */ new Map([
72842
- [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND7],
72843
- [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND7]
74449
+ [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND8],
74450
+ [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND8]
72844
74451
  ]);
72845
74452
  var ZAI_MEASURES = { TOKENS_LIMIT: "tokens", TIME_LIMIT: "tool-calls" };
72846
74453
  var ZaiLimitSchema = external_exports.object({
@@ -72873,8 +74480,8 @@ function zaiWindow(limit) {
72873
74480
  var zaiQuotaAdapter = {
72874
74481
  source: ZAI_SOURCE,
72875
74482
  matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === ZAI_HOST,
72876
- fetch: async (apiKey, http6, signal, nowMs) => {
72877
- const response = await http6(ZAI_QUOTA_URL, { authorization: apiKey, accept: "application/json" }, signal);
74483
+ fetch: async (apiKey, http7, signal, nowMs) => {
74484
+ const response = await http7(ZAI_QUOTA_URL, { authorization: apiKey, accept: "application/json" }, signal);
72878
74485
  if (response.status !== HTTP_OK) {
72879
74486
  throw new ProviderQuotaError(ZAI_SOURCE, `answered HTTP ${String(response.status)}`);
72880
74487
  }
@@ -72904,7 +74511,7 @@ var OPENROUTER_HOST = "openrouter.ai";
72904
74511
  var OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
72905
74512
  var OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
72906
74513
  var HTTP_FORBIDDEN = 403;
72907
- var MS_PER_DAY2 = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND7;
74514
+ var MS_PER_DAY2 = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND8;
72908
74515
  var OpenRouterKeySchema = external_exports.object({
72909
74516
  data: external_exports.object({
72910
74517
  limit: external_exports.number().nonnegative().nullable(),
@@ -72915,8 +74522,8 @@ var OpenRouterKeySchema = external_exports.object({
72915
74522
  })
72916
74523
  });
72917
74524
  var OpenRouterCreditsSchema = external_exports.object({ data: external_exports.object({ total_credits: external_exports.number().nonnegative(), total_usage: external_exports.number().nonnegative() }) });
72918
- async function openRouterGet(url2, schema, apiKey, http6, signal) {
72919
- const response = await http6(url2, { authorization: `Bearer ${apiKey}`, accept: "application/json" }, signal);
74525
+ async function openRouterGet(url2, schema, apiKey, http7, signal) {
74526
+ const response = await http7(url2, { authorization: `Bearer ${apiKey}`, accept: "application/json" }, signal);
72920
74527
  if (response.status === HTTP_FORBIDDEN) {
72921
74528
  return "forbidden";
72922
74529
  }
@@ -72941,12 +74548,12 @@ function nextUtcMidnight(nowMs) {
72941
74548
  var openRouterQuotaAdapter = {
72942
74549
  source: OPENROUTER_SOURCE,
72943
74550
  matches: (baseUrl) => URL.canParse(baseUrl) && new URL(baseUrl).hostname === OPENROUTER_HOST,
72944
- fetch: async (apiKey, http6, signal, nowMs) => {
72945
- const key = await openRouterGet(OPENROUTER_KEY_URL, OpenRouterKeySchema, apiKey, http6, signal);
74551
+ fetch: async (apiKey, http7, signal, nowMs) => {
74552
+ const key = await openRouterGet(OPENROUTER_KEY_URL, OpenRouterKeySchema, apiKey, http7, signal);
72946
74553
  if (key === "forbidden") {
72947
74554
  throw new ProviderQuotaError(OPENROUTER_SOURCE, "/api/v1/key refused the key (HTTP 403)");
72948
74555
  }
72949
- const credits = await openRouterGet(OPENROUTER_CREDITS_URL, OpenRouterCreditsSchema, apiKey, http6, signal);
74556
+ const credits = await openRouterGet(OPENROUTER_CREDITS_URL, OpenRouterCreditsSchema, apiKey, http7, signal);
72950
74557
  const { limit, limit_remaining: limitRemaining, limit_reset: limitReset, free_model_daily_requests: free, is_free_tier: isFreeTier } = key.data;
72951
74558
  const windows = [];
72952
74559
  if (limit !== null && limit > 0) {
@@ -73103,15 +74710,11 @@ function createRealQuotaRefresher(params) {
73103
74710
 
73104
74711
  // src/frontdoor/commands.ts
73105
74712
  function appendLog(paths, line) {
73106
- import_node_fs12.default.mkdirSync(paths.logsDir, { recursive: true });
73107
- import_node_fs12.default.appendFileSync(paths.frontdoorLogPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
74713
+ import_node_fs13.default.mkdirSync(paths.logsDir, { recursive: true });
74714
+ import_node_fs13.default.appendFileSync(paths.frontdoorLogPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
73108
74715
  `);
73109
74716
  }
73110
74717
  var MINTED_TOKEN_RANDOM_BYTES = 32;
73111
- function headroomSocketTarget(fsPort, trust, paths) {
73112
- const socketPath = readHeadroomState(fsPort, paths.headroomStateFile)?.socketPath;
73113
- return socketPath === void 0 ? void 0 : verifyHeadroomSocket(socketPath, trust);
73114
- }
73115
74718
  function rcObservingResolver(resolve, tracker, hub) {
73116
74719
  return async (request7) => {
73117
74720
  const resolution = await resolve(request7);
@@ -73126,7 +74729,7 @@ function realFrontDoorSupervisorPorts(paths) {
73126
74729
  };
73127
74730
  let directPort = 0;
73128
74731
  const rcSelfHost = rcSelfHostFromEnv(process.env);
73129
- const codexPorts = createCodexRoutePorts(log);
74732
+ const codexPorts = createCodexRoutePorts(log, paths.chatgptSignInFile);
73130
74733
  let ca;
73131
74734
  const loadCa = () => {
73132
74735
  ca ??= ensureCa(realConnectCertStore(paths), () => generateCa(/* @__PURE__ */ new Date()));
@@ -73143,14 +74746,15 @@ function realFrontDoorSupervisorPorts(paths) {
73143
74746
  };
73144
74747
  const rcSelfHostSurface = rcSelfHost ? createRcSelfHostSurface({
73145
74748
  now: () => Date.now(),
73146
- newUuid: import_node_crypto12.randomUUID,
73147
- randomToken: () => (0, import_node_crypto12.randomBytes)(MINTED_TOKEN_RANDOM_BYTES).toString("base64url"),
74749
+ newUuid: import_node_crypto14.randomUUID,
74750
+ randomToken: () => (0, import_node_crypto14.randomBytes)(MINTED_TOKEN_RANDOM_BYTES).toString("base64url"),
73148
74751
  credentialRecord: () => readRcSelfHostRecord(realFarmFs, paths.frontdoorDir),
73149
74752
  log
73150
74753
  }) : void 0;
73151
74754
  const rcCredentialStore = createRcCredentialStore(realFarmFs, paths.frontdoorRcCredentialsDir);
73152
74755
  const rcTracker = createRcSessionTracker({ now: () => Date.now(), idleMs: RC_IDLE_EXPIRY_MS, credentialStore: rcCredentialStore });
73153
- const rcFanout = createRcEventFanout();
74756
+ const doorEvents = createDoorEventHub();
74757
+ const rcFanout = rcFanoutOnDoorHub(createRcEventFanout(), doorEvents);
73154
74758
  const rcHub = createRcStreamHub({
73155
74759
  now: () => Date.now(),
73156
74760
  credentialOf: rcTracker.credentialOf,
@@ -73161,7 +74765,7 @@ function realFrontDoorSupervisorPorts(paths) {
73161
74765
  saveSequenceNum: rcCredentialStore.writeCursor,
73162
74766
  dial: rcSelfHost ? lateRcStreamDial(rcSelfHostDialTarget) : realRcStreamDial(),
73163
74767
  fanout: rcFanout,
73164
- newClientId: import_node_crypto12.randomUUID,
74768
+ newClientId: import_node_crypto14.randomUUID,
73165
74769
  backoffMs: RC_STREAM_BACKOFF_MS,
73166
74770
  sleep: async (ms) => {
73167
74771
  await new Promise((resolve) => {
@@ -73172,7 +74776,7 @@ function realFrontDoorSupervisorPorts(paths) {
73172
74776
  appendLog(paths, `frontdoor ${String(process.pid)}: ${line}`);
73173
74777
  }
73174
74778
  });
73175
- const rcControlToken = (0, import_node_crypto12.randomUUID)();
74779
+ const rcControlToken = (0, import_node_crypto14.randomUUID)();
73176
74780
  const resolveRoute = rcObservingResolver(
73177
74781
  createProviderRouteResolver({ fs: realFsPort, providersDir: paths.providersDir, codexPorts, directPort: () => directPort, ...rcSelfHostSurface === void 0 ? {} : { rcSelfHostRoute: rcSelfHostSurface.route } }),
73178
74782
  rcTracker,
@@ -73203,8 +74807,8 @@ function realFrontDoorSupervisorPorts(paths) {
73203
74807
  now: () => Date.now(),
73204
74808
  headroomSocket: () => headroomSocketTarget(realFarmFs, realHeadroomSocketTrust, paths),
73205
74809
  // The per-generation capability the direct listener demands: held only in this process's memory, so a loopback process that discovers the direct port still cannot use it.
73206
- hopSecret: (0, import_node_crypto12.randomUUID)(),
73207
- custody: createCredentialCustody(() => (0, import_node_crypto12.randomUUID)()),
74810
+ hopSecret: (0, import_node_crypto14.randomUUID)(),
74811
+ custody: createCredentialCustody(() => (0, import_node_crypto14.randomUUID)()),
73208
74812
  log
73209
74813
  });
73210
74814
  const onListenerError = (name) => (error62) => {
@@ -73225,12 +74829,20 @@ function realFrontDoorSupervisorPorts(paths) {
73225
74829
  startProviderListener: async (preferredPort) => {
73226
74830
  const authority = loadCa();
73227
74831
  const rcDial = rcSelfHost ? lateRcEventDial(rcSelfHostDialTarget) : realRcEventDial();
73228
- const rcInject = async (sessionId, text2) => await injectRcUserMessage({ credentialOf: rcTracker.credentialOf, noteSequenceNums: rcTracker.noteSequenceNums, dial: rcDial, newUuid: import_node_crypto12.randomUUID }, sessionId, text2);
74832
+ const rcInject = async (sessionId, text2) => await injectRcUserMessage({ credentialOf: rcTracker.credentialOf, noteSequenceNums: rcTracker.noteSequenceNums, dial: rcDial, newUuid: import_node_crypto14.randomUUID }, sessionId, text2);
73229
74833
  const rcAnswer = async (sessionId, requestId, decision) => await answerRcControlRequest({ credentialOf: rcTracker.credentialOf, pendingOf: (id) => rcTracker.pendingOf(id), completePending: rcTracker.completePending, noteSequenceNums: rcTracker.noteSequenceNums, dial: rcDial }, sessionId, requestId, decision);
73230
- const rcControlRequestDeps = { credentialOf: rcTracker.credentialOf, noteSequenceNums: rcTracker.noteSequenceNums, dial: rcDial, newUuid: import_node_crypto12.randomUUID };
74834
+ const rcControlRequestDeps = { credentialOf: rcTracker.credentialOf, noteSequenceNums: rcTracker.noteSequenceNums, dial: rcDial, newUuid: import_node_crypto14.randomUUID };
73231
74835
  const rcInterrupt = async (sessionId) => await interruptRcSession(rcControlRequestDeps, sessionId);
73232
74836
  const rcSetModel = async (sessionId, model) => await setRcSessionModel(rcControlRequestDeps, sessionId, model);
73233
74837
  const rcSetPermissionMode = async (sessionId, mode) => await setRcSessionPermissionMode(rcControlRequestDeps, sessionId, mode);
74838
+ const controlDeps = {
74839
+ usageSnapshots: () => listUsageSnapshots(realFarmFs, paths.usageSnapshotsDir),
74840
+ usageSnapshotOf: (identity) => readUsageSnapshot(realFarmFs, paths.usageSnapshotsDir, identity),
74841
+ now: () => Date.now(),
74842
+ frontDoorStatus: () => collectFrontDoorStatus(realFarmFs, realHeadroomSocketTrust, paths, realIsProcessRunning),
74843
+ checkReport: (target, identity) => collectCheckReport({ paths, cwd: target, ...identity === void 0 ? {} : { identity }, env: process.env }),
74844
+ doctorReport: () => collectDoctorReport({ paths, env: process.env })
74845
+ };
73234
74846
  realFarmFs.mkdirp(paths.frontdoorDir);
73235
74847
  realFarmFs.writeFilePrivate(paths.frontdoorControlTokenFile, `${rcControlToken}
73236
74848
  `);
@@ -73241,7 +74853,20 @@ function realFrontDoorSupervisorPorts(paths) {
73241
74853
  log,
73242
74854
  mintLeaf(authority, LOOPBACK_LEAF_NAMES, /* @__PURE__ */ new Date()),
73243
74855
  createRcControlHandler({ expectedToken: rcControlToken, list: rcTracker.list, statusOf: rcTracker.statusOf, pendingOf: rcTracker.pendingOf, inject: rcInject, answer: rcAnswer, interrupt: rcInterrupt, setModel: rcSetModel, setPermissionMode: rcSetPermissionMode }),
73244
- createRcApiNodeHandler({ expectedToken: rcControlToken, list: rcTracker.list, statusOf: rcTracker.statusOf, pendingOf: rcTracker.pendingOf, inject: rcInject, answer: rcAnswer, interrupt: rcInterrupt, setModel: rcSetModel, setPermissionMode: rcSetPermissionMode, fanout: rcFanout })
74856
+ createDoorApiNodeHandler({
74857
+ expectedToken: rcControlToken,
74858
+ list: rcTracker.list,
74859
+ statusOf: rcTracker.statusOf,
74860
+ pendingOf: rcTracker.pendingOf,
74861
+ inject: rcInject,
74862
+ answer: rcAnswer,
74863
+ interrupt: rcInterrupt,
74864
+ setModel: rcSetModel,
74865
+ setPermissionMode: rcSetPermissionMode,
74866
+ fanout: rcFanout,
74867
+ ...controlDeps,
74868
+ events: doorEvents
74869
+ })
73245
74870
  );
73246
74871
  const handle = await listenFrontDoor(server, { ...preferredPort === void 0 ? {} : { preferredPort }, ca: authority.certPem, onError: onListenerError("provider") });
73247
74872
  return {
@@ -73254,14 +74879,14 @@ function realFrontDoorSupervisorPorts(paths) {
73254
74879
  },
73255
74880
  startConnectListener: async (preferredPort) => {
73256
74881
  const wantedTransparentPort = process.env.AGENT_SHIM_TRANSPARENT_SURFACE === void 0 ? void 0 : Number(process.env.AGENT_SHIM_TRANSPARENT_SURFACE);
73257
- const transparentCapability = wantedTransparentPort === void 0 || Number.isNaN(wantedTransparentPort) ? void 0 : (0, import_node_crypto12.randomUUID)();
74882
+ const transparentCapability = wantedTransparentPort === void 0 || Number.isNaN(wantedTransparentPort) ? void 0 : (0, import_node_crypto14.randomUUID)();
73258
74883
  if (transparentCapability !== void 0) {
73259
74884
  writeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, { pid: process.pid, startedAt: Date.now(), token: transparentCapability });
73260
74885
  }
73261
74886
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
73262
74887
  const capture = captureFromEnv(process.env, paths.logsDir);
73263
74888
  if (capture !== void 0) {
73264
- log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path34.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
74889
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path36.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
73265
74890
  }
73266
74891
  if (rcSelfHostSurface !== void 0) {
73267
74892
  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");
@@ -73327,58 +74952,13 @@ function realFrontDoorSupervisorPorts(paths) {
73327
74952
  return { port: handle.port, close: handle.close };
73328
74953
  },
73329
74954
  closeRcStreamHub: rcHub.close,
74955
+ // The launch lifecycle publisher over the same backbone the typed API serves: the tick's registry facts go in here, and the door's own register, prune and end moments come out as source-tagged events.
74956
+ observeLaunchRegistry: createLaunchEventPublisher(doorEvents, () => Date.now()).observe,
73330
74957
  log: (line) => {
73331
74958
  appendLog(paths, line);
73332
74959
  }
73333
74960
  };
73334
74961
  }
73335
- function collectFrontDoorStatus(fsPort, socketTrust, paths, isRunning) {
73336
- const state = readFrontDoorState(fsPort, paths.frontdoorStateFile) ?? {};
73337
- return {
73338
- state,
73339
- supervisorAlive: state.supervisorPid !== void 0 && isRunning(state.supervisorPid),
73340
- sessions: listFrontDoorSessions(fsPort, paths.frontdoorSessionsDir).map((session) => ({ ...session, alive: isRunning(session.pid) })),
73341
- headroomSocket: headroomSocketTarget(fsPort, socketTrust, paths),
73342
- logPath: paths.frontdoorLogPath,
73343
- logExists: fsPort.readFileUtf8(paths.frontdoorLogPath) !== void 0
73344
- };
73345
- }
73346
- function formatFrontDoorStatus(status, caCertPath) {
73347
- const lines = [];
73348
- if (status.state.supervisorPid === void 0) {
73349
- lines.push("supervisor: not running");
73350
- } else {
73351
- lines.push(`supervisor: pid ${String(status.state.supervisorPid)} (${status.supervisorAlive ? "alive" : "NOT running"})`);
73352
- }
73353
- if (status.state.port === void 0) {
73354
- lines.push(`front door: not listening${status.state.lastPort === void 0 ? "" : ` (next start on 127.0.0.1:${String(status.state.lastPort)})`}`);
73355
- } else {
73356
- lines.push(`front door: listening on https://127.0.0.1:${String(status.state.port)}, routing /providers/<name> requests`);
73357
- }
73358
- if (status.state.connectPort === void 0) {
73359
- lines.push(`connect surface: not listening${status.state.lastConnectPort === void 0 ? "" : ` (next start on 127.0.0.1:${String(status.state.lastConnectPort)})`}`);
73360
- } else {
73361
- lines.push(`connect surface: listening on 127.0.0.1:${String(status.state.connectPort)}, CA ${caCertPath}`);
73362
- }
73363
- if (status.headroomSocket === void 0) {
73364
- lines.push("headroom hop: the daemon is not serving (sessions asking for headroom fail until it is up)");
73365
- } else if (status.headroomSocket.refused === void 0) {
73366
- lines.push(`headroom hop: daemon on unix socket ${status.headroomSocket.socketPath}`);
73367
- } else {
73368
- lines.push(`headroom hop: REFUSING the daemon's socket (sessions asking for headroom fail until it is fixed): ${status.headroomSocket.refused}`);
73369
- }
73370
- if (status.sessions.length === 0) {
73371
- lines.push("sessions: none");
73372
- } else {
73373
- const pids = status.sessions.map((session) => `${String(session.pid)}${session.alive ? "" : " (dead)"}`);
73374
- lines.push(`sessions: ${String(status.sessions.length)} registered (${pids.join(", ")})`);
73375
- }
73376
- if (status.state.lastError !== void 0) {
73377
- lines.push(`last error: ${status.state.lastError}`);
73378
- }
73379
- lines.push(`daemon log: ${status.logPath}${status.logExists ? "" : " (not created yet)"}`);
73380
- return lines;
73381
- }
73382
74962
  function formatRcSessionList(sessions) {
73383
74963
  if (sessions.length === 0) {
73384
74964
  return ["no Remote Control sessions observed"];
@@ -73644,8 +75224,8 @@ function registerFrontDoorCommand(program2, deps) {
73644
75224
  identitiesDir: paths.identitiesDir,
73645
75225
  frontdoorDir: paths.frontdoorDir,
73646
75226
  identity,
73647
- newUuid: import_node_crypto12.randomUUID,
73648
- randomToken: () => (0, import_node_crypto12.randomBytes)(MINTED_TOKEN_RANDOM_BYTES).toString("base64url"),
75227
+ newUuid: import_node_crypto14.randomUUID,
75228
+ randomToken: () => (0, import_node_crypto14.randomBytes)(MINTED_TOKEN_RANDOM_BYTES).toString("base64url"),
73649
75229
  force: options.force === true,
73650
75230
  now: () => Date.now()
73651
75231
  });
@@ -73959,19 +75539,19 @@ function registerCompletionCommand(program2) {
73959
75539
  }
73960
75540
 
73961
75541
  // src/credentialCommand.ts
73962
- var import_node_child_process4 = require("node:child_process");
75542
+ var import_node_child_process5 = require("node:child_process");
73963
75543
 
73964
75544
  // src/identityToken.ts
73965
- var import_node_fs13 = __toESM(require("node:fs"), 1);
73966
- var import_node_path35 = __toESM(require("node:path"), 1);
75545
+ var import_node_fs14 = __toESM(require("node:fs"), 1);
75546
+ var import_node_path37 = __toESM(require("node:path"), 1);
73967
75547
  var TOKEN_FILE_MODE = 384;
73968
75548
  var TOKEN_DIR_MODE = 448;
73969
75549
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
73970
75550
  function identityTokenDir(paths) {
73971
- return import_node_path35.default.join(paths.root, "credentials");
75551
+ return import_node_path37.default.join(paths.root, "credentials");
73972
75552
  }
73973
75553
  function identityTokenPath(paths, identityName) {
73974
- return import_node_path35.default.join(identityTokenDir(paths), `${identityName}.token`);
75554
+ return import_node_path37.default.join(identityTokenDir(paths), `${identityName}.token`);
73975
75555
  }
73976
75556
  function storeIdentityToken(paths, identityName, raw) {
73977
75557
  const token = raw.trim();
@@ -73979,13 +75559,13 @@ function storeIdentityToken(paths, identityName, raw) {
73979
75559
  throw new UsageError("That is not a claude setup-token token (expected it to start with sk-ant-oat). Run `claude setup-token` and pass its token on standard input.");
73980
75560
  }
73981
75561
  const dir = identityTokenDir(paths);
73982
- import_node_fs13.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
73983
- import_node_fs13.default.chmodSync(dir, TOKEN_DIR_MODE);
75562
+ import_node_fs14.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
75563
+ import_node_fs14.default.chmodSync(dir, TOKEN_DIR_MODE);
73984
75564
  const target = identityTokenPath(paths, identityName);
73985
- const temp = import_node_path35.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
73986
- import_node_fs13.default.writeFileSync(temp, `${token}
75565
+ const temp = import_node_path37.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
75566
+ import_node_fs14.default.writeFileSync(temp, `${token}
73987
75567
  `, { mode: TOKEN_FILE_MODE });
73988
- import_node_fs13.default.renameSync(temp, target);
75568
+ import_node_fs14.default.renameSync(temp, target);
73989
75569
  return target;
73990
75570
  }
73991
75571
 
@@ -74011,7 +75591,7 @@ function realCommandPorts(deps) {
74011
75591
  cache: createRealCredentialCache(deps.paths.root),
74012
75592
  platform: process.platform,
74013
75593
  now: () => Date.now(),
74014
- ssh: (host, remoteCommand, input2) => (0, import_node_child_process4.spawnSync)("ssh", ["--", host, remoteCommand], { input: input2, stdio: ["pipe", "inherit", "inherit"] }).status
75594
+ ssh: (host, remoteCommand, input2) => (0, import_node_child_process5.spawnSync)("ssh", ["--", host, remoteCommand], { input: input2, stdio: ["pipe", "inherit", "inherit"] }).status
74015
75595
  };
74016
75596
  }
74017
75597
  var REMOTE_ROOT_SCRIPT = 'root="${AGENT_SHIM_HOME:-${CLAUDE_USE_HOME:-}}"; if [ -z "$root" ]; then if [ ! -d "$HOME/.agent-shim" ] && [ -d "$HOME/.claude-use" ]; then root="$HOME/.claude-use"; else root="$HOME/.agent-shim"; fi; fi';
@@ -74119,509 +75699,6 @@ function subjectName(positional, provider) {
74119
75699
  return name;
74120
75700
  }
74121
75701
 
74122
- // src/doctorReport.ts
74123
- var import_node_fs14 = __toESM(require("node:fs"), 1);
74124
- var import_node_path36 = __toESM(require("node:path"), 1);
74125
- function refinePathShadow(status, ownExecutablePath, realpath) {
74126
- if (status.status !== "shadowed") {
74127
- return status;
74128
- }
74129
- return realpath(status.by) === realpath(ownExecutablePath) ? { status: "ok" } : status;
74130
- }
74131
- function validateJson(schema, input2) {
74132
- if (input2.raw === void 0) {
74133
- return { ok: false, message: `${input2.path} is missing.` };
74134
- }
74135
- let parsed;
74136
- try {
74137
- parsed = JSON.parse(input2.raw);
74138
- } catch (error62) {
74139
- return { ok: false, message: `${input2.path} is not valid JSON: ${error62 instanceof Error ? error62.message : String(error62)}` };
74140
- }
74141
- const result = schema.safeParse(parsed);
74142
- if (!result.success) {
74143
- return { ok: false, message: new ConfigValidationError(input2.path, result.error.issues).message };
74144
- }
74145
- return { ok: true, data: result.data };
74146
- }
74147
- function pushPathResolution(push, resolution) {
74148
- const ownDir = import_node_path36.default.dirname(resolution.ownExecutablePath);
74149
- switch (resolution.agentShim.status) {
74150
- case "ok":
74151
- push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
74152
- break;
74153
- case "not-on-path":
74154
- push(
74155
- "path-resolution",
74156
- "warn",
74157
- `${ownDir} is not on PATH, so a bare \`agent-shim\` does not reach ${resolution.ownExecutablePath}. Add it to PATH, or keep invoking this executable by its full path.`,
74158
- "agent-shim"
74159
- );
74160
- break;
74161
- case "shadowed":
74162
- push(
74163
- "path-resolution",
74164
- "fail",
74165
- `\`agent-shim\` on PATH resolves to ${resolution.agentShim.by}, not this running executable, ${resolution.ownExecutablePath}. Every command you type runs that one instead, at whatever version it happens to be \u2014 including the checks in this report, which describe this executable. Remove ${resolution.agentShim.by}, repoint it at ${resolution.ownExecutablePath}, or put ${ownDir} ahead of it on PATH.`,
74166
- "agent-shim"
74167
- );
74168
- break;
74169
- }
74170
- if (resolution.claude === void 0) {
74171
- return;
74172
- }
74173
- switch (resolution.claude.status) {
74174
- case "ok":
74175
- push("path-resolution", "pass", "`claude` on PATH resolves to the enabled shim.", "claude");
74176
- break;
74177
- case "not-on-path":
74178
- push("path-resolution", "warn", "The enabled `claude` shim's directory is not on PATH \u2014 add it, or use `agent-shim run` instead.", "claude");
74179
- break;
74180
- case "shadowed":
74181
- push(
74182
- "path-resolution",
74183
- "warn",
74184
- `\`claude\` on PATH resolves to ${resolution.claude.by}, not the enabled shim. Put the shim's directory ahead of it on PATH, or run \`agent-shim shim disable\` if you meant to launch that one directly.`,
74185
- "claude"
74186
- );
74187
- break;
74188
- }
74189
- }
74190
- function cacheClause(cacheEnv, owner, block2) {
74191
- if (cacheEnv === void 0 || block2.cache === void 0) {
74192
- return { text: "", unreadable: false };
74193
- }
74194
- const state = describeCachedCredential({ port: cacheEnv.port, platform: cacheEnv.platform, owner, cache: block2.cache, nowMs: cacheEnv.now() });
74195
- return { text: `; ${formatCachedCredentialState(state)}`, unreadable: state.status === "unreadable" };
74196
- }
74197
- function pushProvider(push, entry, cacheEnv) {
74198
- if (entry.raw === void 0) {
74199
- push("provider", "fail", `${entry.path} is missing.`, entry.name);
74200
- return;
74201
- }
74202
- let parsed;
74203
- try {
74204
- parsed = JSON.parse(entry.raw);
74205
- } catch (error62) {
74206
- push("provider", "fail", `${entry.path} is not valid JSON: ${error62 instanceof Error ? error62.message : String(error62)}`, entry.name);
74207
- return;
74208
- }
74209
- const conversion = legacyProviderConversion(parsed);
74210
- if (conversion !== void 0) {
74211
- push("provider", "fail", new LegacyProviderFileError(entry.path, conversion).message, entry.name);
74212
- return;
74213
- }
74214
- const validated2 = ProviderSchema.safeParse(parsed);
74215
- if (!validated2.success) {
74216
- push("provider", "fail", new ConfigValidationError(entry.path, validated2.error.issues).message, entry.name);
74217
- return;
74218
- }
74219
- const cache = cacheClause(cacheEnv, `provider ${entry.name}`, validated2.data.credential);
74220
- push("provider", cache.unreadable ? "fail" : "pass", `${entry.name} is valid (${describeProviderEndpoint(validated2.data)}, credential ${describeCredential(validated2.data.credential)})${cache.text}.`, entry.name);
74221
- if (validated2.data.env?.ENABLE_TOOL_SEARCH === void 0) {
74222
- push("provider", "warn", `${entry.name} does not set ENABLE_TOOL_SEARCH: a session on this provider loads MCP tools upfront rather than deferring them, because its base URL is the front door, which Claude Code treats as a non-first-party host. Set ENABLE_TOOL_SEARCH in the provider's env block to restore deferred loading, when the upstream backend supports the tool_reference payloads it sends.`, entry.name);
74223
- }
74224
- }
74225
- function pushLegacyName(push, params) {
74226
- const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
74227
- if (legacyVariables.length === 0 && import_node_path36.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
74228
- push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
74229
- return;
74230
- }
74231
- for (const name of legacyVariables) {
74232
- 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);
74233
- }
74234
- if (import_node_path36.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
74235
- push(
74236
- "legacy-name",
74237
- "warn",
74238
- `The state root is the former ${params.rootPath}, used in place. Leave it where it is: macOS Claude Code keys each identity's Keychain login on its exact configuration directory path, so moving it signs every identity out.`
74239
- );
74240
- }
74241
- }
74242
- function runDoctor(params) {
74243
- const findings = [];
74244
- const push = (section, severity, message, subject) => {
74245
- findings.push({ section, severity, message, ...subject === void 0 ? {} : { subject } });
74246
- };
74247
- const checkPin = (section, subject, where, version2) => {
74248
- const installed = params.installedClaudeVersions;
74249
- if (version2 === void 0 || installed === void 0 || installed.includes(version2)) {
74250
- return;
74251
- }
74252
- push(section, "warn", `${where} pins Claude Code ${version2}, which is not installed (installed: ${installed.length === 0 ? "none" : installed.join(", ")}); a launch that resolves to it fails.`, subject);
74253
- };
74254
- const ambient = detectAmbientCredential(params.env);
74255
- if (ambient === void 0) {
74256
- push("ambient-credential", "pass", "No ambient-credential environment variable is set.");
74257
- } else {
74258
- push("ambient-credential", "warn", formatAmbientCredentialGuardMessage(ambient.variable));
74259
- }
74260
- if (params.binaryDiscovery.ok) {
74261
- const { binary } = params.binaryDiscovery;
74262
- const versionNote = binary.version === void 0 ? "" : `, version ${binary.version}`;
74263
- push("binary-discovery", "pass", `Found ${binary.path} (${binary.source}${versionNote}).`);
74264
- } else {
74265
- push("binary-discovery", "fail", params.binaryDiscovery.message);
74266
- }
74267
- if (params.claudeShim.state === void 0) {
74268
- push("claude-shim", "pass", "No `claude` command shim enabled (the default). Run `agent-shim shim enable` to add one.");
74269
- } else if (!params.claudeShim.targetExists) {
74270
- push(
74271
- "claude-shim",
74272
- "warn",
74273
- `claude-shim.json records a \`claude\` shim at ${params.claudeShim.state.targetPath}, but nothing is there. Run \`agent-shim shim enable\` again, or \`agent-shim shim disable\` to clear the stale record.`
74274
- );
74275
- } else {
74276
- push(
74277
- "claude-shim",
74278
- "pass",
74279
- `\`claude\` is enabled at ${params.claudeShim.state.targetPath} (${params.claudeShim.state.method}). If you've upgraded agent-shim since, re-run \`agent-shim shim enable\` to refresh it.`
74280
- );
74281
- }
74282
- pushPathResolution(push, params.pathResolution);
74283
- pushLegacyName(push, params);
74284
- const profileSources = /* @__PURE__ */ new Map();
74285
- for (const entry of params.configProfiles) {
74286
- const validated2 = validateJson(ConfigProfileSchema, entry);
74287
- if (!validated2.ok) {
74288
- push("config-profile", "fail", validated2.message, entry.name);
74289
- continue;
74290
- }
74291
- profileSources.set(entry.name, { name: entry.name, profile: validated2.data });
74292
- checkPin("config-profile", entry.name, `Configuration profile "${entry.name}"`, validated2.data.launch?.claudeVersion);
74293
- }
74294
- const loadProfile = (name) => profileSources.get(name);
74295
- for (const name of profileSources.keys()) {
74296
- const linearised = lineariseProfile(name, loadProfile);
74297
- if (linearised.diagnostics.length === 0) {
74298
- push("config-profile", "pass", `${name} is valid and its extends chain resolves cleanly.`, name);
74299
- } else {
74300
- for (const diagnostic of linearised.diagnostics) {
74301
- push("config-profile", "fail", diagnostic.message, name);
74302
- }
74303
- }
74304
- }
74305
- const validProfileNames = new Set(profileSources.keys());
74306
- const validIdentityNames = /* @__PURE__ */ new Set();
74307
- for (const entry of params.identities) {
74308
- const validated2 = validateJson(IdentitySchema, entry);
74309
- if (!validated2.ok) {
74310
- push("identity", "fail", validated2.message, entry.name);
74311
- continue;
74312
- }
74313
- validIdentityNames.add(entry.name);
74314
- const defaultProfile = validated2.data.defaultConfigProfile;
74315
- if (defaultProfile !== void 0 && !validProfileNames.has(defaultProfile)) {
74316
- push(
74317
- "identity",
74318
- "fail",
74319
- `Identity "${entry.name}" names configuration profile "${defaultProfile}" as its default, but no such profile exists.`,
74320
- entry.name
74321
- );
74322
- } else {
74323
- const credential = validated2.data.credential;
74324
- const cache = credential === void 0 ? { text: "", unreadable: false } : cacheClause(params.credentialCache, `identity ${entry.name}`, credential);
74325
- push(
74326
- "identity",
74327
- cache.unreadable ? "fail" : "pass",
74328
- `${entry.name} is valid and authenticates with ${credential === void 0 ? "its stored login" : `credential ${describeCredential(credential)}`}${cache.text}.`,
74329
- entry.name
74330
- );
74331
- }
74332
- }
74333
- const validatedGlobalConfig = params.globalConfig.raw === void 0 ? void 0 : validateJson(GlobalConfigSchema, params.globalConfig);
74334
- const pools = validatedGlobalConfig?.ok === true ? validatedGlobalConfig.data.pools ?? {} : {};
74335
- for (const [poolName, pool] of Object.entries(pools)) {
74336
- const missing = pool.identities.filter((member) => !validIdentityNames.has(member));
74337
- if (missing.length === 0) {
74338
- push("pool", "pass", `${poolName} is valid (${pool.identities.join(", ")}).`, poolName);
74339
- } else {
74340
- push("pool", "fail", `Pool "${poolName}" names ${missing.map((member) => `identity "${member}"`).join(" and ")}, which ${missing.length === 1 ? "does" : "do"} not exist.`, poolName);
74341
- }
74342
- }
74343
- const selectionExists = (selector) => {
74344
- const poolName = poolNameOf(selector);
74345
- return poolName === void 0 ? validIdentityNames.has(selector) : poolName in pools;
74346
- };
74347
- for (const entry of params.providers) {
74348
- pushProvider(push, entry, params.credentialCache);
74349
- }
74350
- if (params.platform !== "darwin" || params.run === void 0) {
74351
- push("keychain", "pass", "Skipped (not macOS).");
74352
- } else {
74353
- for (const entry of params.identities) {
74354
- const result = lookupKeychainService(params.run, entry.farmRoot);
74355
- push("keychain", result.found ? "pass" : "warn", result.note, entry.name);
74356
- }
74357
- }
74358
- if (params.directoryRules.raw === void 0) {
74359
- push("directory-rules", "pass", "No directory-rules.json configured.");
74360
- } else {
74361
- const validated2 = validateJson(DirectoryRulesSchema, params.directoryRules);
74362
- if (!validated2.ok) {
74363
- push("directory-rules", "fail", validated2.message);
74364
- } else {
74365
- push("directory-rules", "pass", `${params.directoryRules.path} is valid.`);
74366
- for (const rule of validated2.data.rules) {
74367
- const badRefs = [];
74368
- if (rule.identity !== void 0 && !selectionExists(rule.identity)) {
74369
- badRefs.push(poolNameOf(rule.identity) === void 0 ? `identity "${rule.identity}"` : `pool "${poolNameOf(rule.identity) ?? ""}"`);
74370
- }
74371
- if (rule.configProfile !== void 0 && !validProfileNames.has(rule.configProfile)) {
74372
- badRefs.push(`configuration profile "${rule.configProfile}"`);
74373
- }
74374
- checkPin("directory-rules", rule.path, `Rule for "${rule.path}"`, rule.launch?.claudeVersion);
74375
- if (badRefs.length > 0) {
74376
- push("directory-rules", "fail", `Rule for "${rule.path}" names ${badRefs.join(" and ")}, which do not exist.`, rule.path);
74377
- } else {
74378
- push("directory-rules", "pass", `Rule for "${rule.path}" is valid.`, rule.path);
74379
- }
74380
- }
74381
- }
74382
- }
74383
- if (params.globalConfig.raw === void 0) {
74384
- push("global-config", "pass", "No config.json configured.");
74385
- } else {
74386
- const validated2 = validateJson(GlobalConfigSchema, params.globalConfig);
74387
- if (!validated2.ok) {
74388
- push("global-config", "fail", validated2.message);
74389
- } else {
74390
- const defaultProfile = validated2.data.defaultConfigProfile;
74391
- if (defaultProfile !== void 0 && !validProfileNames.has(defaultProfile)) {
74392
- push(
74393
- "global-config",
74394
- "fail",
74395
- `config.json names configuration profile "${defaultProfile}" as its default, but no such profile exists.`
74396
- );
74397
- } else {
74398
- push("global-config", "pass", `${params.globalConfig.path} is valid.`);
74399
- checkPin("global-config", void 0, "config.json", validated2.data.launch?.claudeVersion);
74400
- }
74401
- }
74402
- }
74403
- if (params.categoriesLocal.raw === void 0) {
74404
- push("categories-local", "pass", "No categories.local.json configured.");
74405
- } else {
74406
- const validated2 = validateJson(CategoryClassificationOverlaySchema, params.categoriesLocal);
74407
- push(
74408
- "categories-local",
74409
- validated2.ok ? "pass" : "fail",
74410
- validated2.ok ? `${params.categoriesLocal.path} is valid.` : validated2.message
74411
- );
74412
- }
74413
- if (params.headroom.state.raw === void 0) {
74414
- push("headroom", "pass", "No headroom daemon has ever run; nothing to check.");
74415
- } else {
74416
- const validated2 = validateJson(HeadroomStateSchema, params.headroom.state);
74417
- if (!validated2.ok) {
74418
- push("headroom", "fail", validated2.message);
74419
- } else {
74420
- const state = validated2.data;
74421
- const supervisorAlive = state.supervisorPid !== void 0 && params.headroom.isRunning(state.supervisorPid);
74422
- const headroomAlive = state.headroomPid !== void 0 && params.headroom.isRunning(state.headroomPid);
74423
- if (state.supervisorPid === void 0) {
74424
- if (state.lastError === void 0) {
74425
- push("headroom", "pass", "Headroom daemon is stopped (idle shutdown) with no recorded error.");
74426
- } else {
74427
- push("headroom", "warn", `Headroom supervisor is not running; last error: ${state.lastError}`);
74428
- }
74429
- } else if (!supervisorAlive) {
74430
- push(
74431
- "headroom",
74432
- "warn",
74433
- `Headroom state names supervisor pid ${String(state.supervisorPid)}, which is not running; the next launch through headroom will start a replacement.`
74434
- );
74435
- } else if (state.headroomPid === void 0 || state.socketPath === void 0) {
74436
- push(
74437
- "headroom",
74438
- "warn",
74439
- state.lastError === void 0 ? "Headroom supervisor is running but the daemon has no healthy process; it should be restarting it." : `Headroom supervisor is running but the daemon is down; last error: ${state.lastError}`
74440
- );
74441
- } else if (!headroomAlive) {
74442
- push(
74443
- "headroom",
74444
- "warn",
74445
- `Headroom state names daemon pid ${String(state.headroomPid)}, which is not running; its supervisor should be restarting it.`
74446
- );
74447
- } else {
74448
- push(
74449
- "headroom",
74450
- "pass",
74451
- `Headroom daemon is up on unix socket ${state.socketPath} (supervisor ${String(state.supervisorPid)}, daemon ${String(state.headroomPid)}).`
74452
- );
74453
- }
74454
- if (state.lastError !== void 0 && supervisorAlive) {
74455
- push("headroom", "warn", `Headroom recorded a previous error: ${state.lastError}`);
74456
- }
74457
- if (state.installedSource !== void 0 && isMovingGitSource(state.installedSource)) {
74458
- push(
74459
- "headroom",
74460
- "warn",
74461
- `Headroom is installed from a git ref that can move (${state.installedSource}); pin headroom.source to a full commit SHA so a rebased or deleted branch cannot change or break the install.`
74462
- );
74463
- }
74464
- }
74465
- }
74466
- if (params.activeIdentity.raw === void 0) {
74467
- push("active-identity", "pass", "No active identity set.");
74468
- } else {
74469
- const trimmed = params.activeIdentity.raw.trim();
74470
- if (trimmed === "") {
74471
- push("active-identity", "warn", "active-identity is present but empty \u2014 treated the same as unset.");
74472
- } else if (!selectionExists(trimmed)) {
74473
- push("active-identity", "fail", `active-identity names "${trimmed}", which does not exist.`);
74474
- } else {
74475
- push("active-identity", "pass", `Active identity "${trimmed}" is valid.`);
74476
- }
74477
- }
74478
- return { findings, ok: !findings.some((finding) => finding.severity === "fail") };
74479
- }
74480
- var SECTION_TITLES = {
74481
- "ambient-credential": "Ambient-credential exposure",
74482
- "binary-discovery": "Claude Code binary discovery",
74483
- "claude-shim": "`claude` command shim",
74484
- "path-resolution": "PATH resolution",
74485
- "legacy-name": "Former `claude-use` name",
74486
- "config-profile": "Configuration profiles",
74487
- identity: "Identities",
74488
- pool: "Pools",
74489
- provider: "Providers",
74490
- keychain: "macOS Keychain",
74491
- "directory-rules": "Directory rules",
74492
- "global-config": "Global config",
74493
- headroom: "Headroom daemon",
74494
- "categories-local": "categories.local.json",
74495
- "active-identity": "Active identity"
74496
- };
74497
- var SECTION_ORDER = [
74498
- "ambient-credential",
74499
- "binary-discovery",
74500
- "claude-shim",
74501
- "path-resolution",
74502
- "config-profile",
74503
- "identity",
74504
- "pool",
74505
- "provider",
74506
- "keychain",
74507
- "directory-rules",
74508
- "global-config",
74509
- "headroom",
74510
- "categories-local",
74511
- "active-identity"
74512
- ];
74513
- function severityPrefix(severity) {
74514
- switch (severity) {
74515
- case "pass":
74516
- return "[PASS]";
74517
- case "warn":
74518
- return "[WARN]";
74519
- case "fail":
74520
- return "[FAIL]";
74521
- default:
74522
- return severity;
74523
- }
74524
- }
74525
- function formatDoctorReport(report) {
74526
- const lines = [];
74527
- for (const section of SECTION_ORDER) {
74528
- const sectionFindings = report.findings.filter((finding) => finding.section === section);
74529
- if (sectionFindings.length === 0) {
74530
- continue;
74531
- }
74532
- lines.push("", `${SECTION_TITLES[section]}:`);
74533
- for (const finding of sectionFindings) {
74534
- const subject = finding.subject === void 0 ? "" : `${finding.subject}: `;
74535
- lines.push(` ${severityPrefix(finding.severity)} ${subject}${finding.message}`);
74536
- }
74537
- }
74538
- const failCount = report.findings.filter((finding) => finding.severity === "fail").length;
74539
- lines.push("", report.ok ? "All checks passed." : `${String(failCount)} check(s) failed.`);
74540
- return lines;
74541
- }
74542
- function realpathOrSelf(target) {
74543
- try {
74544
- return import_node_fs14.default.realpathSync(target);
74545
- } catch {
74546
- return target;
74547
- }
74548
- }
74549
- function collectDoctorReport(params) {
74550
- const { paths } = params;
74551
- 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() : [];
74552
- const identities = identityNames.map((name) => {
74553
- const farmRoot = import_node_path36.default.join(paths.identitiesDir, name);
74554
- const identityPath = import_node_path36.default.join(farmRoot, "identity.json");
74555
- return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
74556
- });
74557
- 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() : [];
74558
- const configProfiles = profileNames.map((name) => {
74559
- const profilePath = import_node_path36.default.join(paths.configProfilesDir, `${name}.json`);
74560
- return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
74561
- });
74562
- 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() : [];
74563
- const providers = providerNames.map((name) => {
74564
- const providerPath = import_node_path36.default.join(paths.providersDir, `${name}.json`);
74565
- return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
74566
- });
74567
- const ownExecutablePath = realOwnExecutablePath();
74568
- let binaryDiscovery;
74569
- try {
74570
- const binary = realResolveClaudeBinary(resolveOwnBinaryCheck(paths, realContentSourcePath()))();
74571
- binaryDiscovery = { ok: true, binary };
74572
- } catch (error62) {
74573
- binaryDiscovery = { ok: false, message: error62 instanceof Error ? error62.message : String(error62) };
74574
- }
74575
- const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
74576
- const pathDirs = (params.env.PATH ?? "").split(import_node_path36.default.delimiter).filter((dir) => dir !== "");
74577
- const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
74578
- findPathShadow({
74579
- pathDirs,
74580
- targetDir: import_node_path36.default.dirname(shimState.targetPath),
74581
- targetFilename: import_node_path36.default.basename(shimState.targetPath),
74582
- findExecutableInDir
74583
- }),
74584
- shimState.targetPath,
74585
- realpathOrSelf
74586
- );
74587
- const report = runDoctor({
74588
- env: params.env,
74589
- credentialCache: realCredentialCacheEnv(paths),
74590
- installedClaudeVersions: realInstalledClaudeVersions(),
74591
- identities,
74592
- configProfiles,
74593
- providers,
74594
- directoryRules: { path: paths.directoryRulesFile, raw: realFsPort.readFileUtf8(paths.directoryRulesFile) },
74595
- globalConfig: { path: paths.globalConfigFile, raw: realFsPort.readFileUtf8(paths.globalConfigFile) },
74596
- categoriesLocal: { path: paths.categoriesLocalFile, raw: realFsPort.readFileUtf8(paths.categoriesLocalFile) },
74597
- activeIdentity: { path: paths.activeIdentityFile, raw: realFsPort.readFileUtf8(paths.activeIdentityFile) },
74598
- binaryDiscovery,
74599
- claudeShim: { state: shimState, targetExists: shimState !== void 0 && import_node_fs14.default.existsSync(shimState.targetPath) },
74600
- rootPath: paths.root,
74601
- pathResolution: {
74602
- ownExecutablePath,
74603
- agentShim: refinePathShadow(
74604
- findPathShadow({
74605
- pathDirs,
74606
- targetDir: import_node_path36.default.dirname(ownExecutablePath),
74607
- targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
74608
- findExecutableInDir
74609
- }),
74610
- ownExecutablePath,
74611
- realpathOrSelf
74612
- ),
74613
- ...claudeShimShadow === void 0 ? {} : { claude: claudeShimShadow }
74614
- },
74615
- run: realRunPort,
74616
- platform: process.platform,
74617
- headroom: {
74618
- state: { path: paths.headroomStateFile, raw: realFsPort.readFileUtf8(paths.headroomStateFile) },
74619
- isRunning: realIsProcessRunning
74620
- }
74621
- });
74622
- return report;
74623
- }
74624
-
74625
75702
  // src/doctor.ts
74626
75703
  function registerDoctorCommand(program2, deps) {
74627
75704
  const { paths } = deps;
@@ -74645,15 +75722,15 @@ function registerDoctorCommand(program2, deps) {
74645
75722
 
74646
75723
  // src/headroom/commands.ts
74647
75724
  var import_node_fs16 = __toESM(require("node:fs"), 1);
74648
- var import_node_http2 = __toESM(require("node:http"), 1);
74649
- var import_node_path38 = __toESM(require("node:path"), 1);
74650
- var import_node_child_process5 = require("node:child_process");
75725
+ var import_node_http3 = __toESM(require("node:http"), 1);
75726
+ var import_node_path39 = __toESM(require("node:path"), 1);
75727
+ var import_node_child_process6 = require("node:child_process");
74651
75728
 
74652
75729
  // src/frontdoor/realFrontDoorPort.ts
74653
75730
  var import_node_fs15 = __toESM(require("node:fs"), 1);
74654
75731
 
74655
75732
  // src/frontdoor/ensure.ts
74656
- var import_node_crypto13 = require("node:crypto");
75733
+ var import_node_crypto15 = require("node:crypto");
74657
75734
  var FRONTDOOR_START_TIMEOUT_MS = 3e4;
74658
75735
  var FRONTDOOR_LAUNCHER_POLL_MS = 100;
74659
75736
  var FrontDoorStartError = class extends CliError {
@@ -74687,7 +75764,7 @@ function ensureFrontDoor(params) {
74687
75764
  continue;
74688
75765
  }
74689
75766
  if (verdict.ok) {
74690
- const token = (0, import_node_crypto13.randomUUID)();
75767
+ const token = (0, import_node_crypto15.randomUUID)();
74691
75768
  writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token });
74692
75769
  return { port: state.port, connectPort: state.connectPort, token };
74693
75770
  }
@@ -74791,12 +75868,12 @@ function probeFrontDoorSync(port, caPem) {
74791
75868
  }
74792
75869
 
74793
75870
  // src/frontdoor/trust.ts
74794
- var import_node_crypto14 = require("node:crypto");
74795
- var import_node_path37 = __toESM(require("node:path"), 1);
75871
+ var import_node_crypto16 = require("node:crypto");
75872
+ var import_node_path38 = __toESM(require("node:path"), 1);
74796
75873
  var BUNDLE_NAME_HEX_DIGITS = 16;
74797
75874
  function resolveTrustBundle(params) {
74798
75875
  const { caCertFile, bundlesDir, variable, inherited, fs: fs19 } = params;
74799
- if (inherited === void 0 || inherited === "" || import_node_path37.default.resolve(inherited) === import_node_path37.default.resolve(caCertFile)) {
75876
+ if (inherited === void 0 || inherited === "" || import_node_path38.default.resolve(inherited) === import_node_path38.default.resolve(caCertFile)) {
74800
75877
  return { path: caCertFile };
74801
75878
  }
74802
75879
  const caPem = fs19.readFileUtf8(caCertFile);
@@ -74814,7 +75891,7 @@ function resolveTrustBundle(params) {
74814
75891
  }
74815
75892
  const combined = `${inheritedPem.trimEnd()}
74816
75893
  ${caPem}`;
74817
- const bundle = import_node_path37.default.join(bundlesDir, `${(0, import_node_crypto14.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
75894
+ const bundle = import_node_path38.default.join(bundlesDir, `${(0, import_node_crypto16.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
74818
75895
  if (!fs19.exists(bundle)) {
74819
75896
  fs19.mkdirp(bundlesDir);
74820
75897
  fs19.writeFileAtomic(bundle, combined);
@@ -74954,7 +76031,7 @@ function headroomProxyArgs(socketPath, settings2) {
74954
76031
  }
74955
76032
  async function readyOverSocket(socketPath) {
74956
76033
  return await new Promise((resolve) => {
74957
- const probe = import_node_http2.default.get({ socketPath, path: "/readyz", timeout: READY_FETCH_TIMEOUT_MS }, (response) => {
76034
+ const probe = import_node_http3.default.get({ socketPath, path: "/readyz", timeout: READY_FETCH_TIMEOUT_MS }, (response) => {
74958
76035
  response.resume();
74959
76036
  resolve(response.statusCode === HTTP_STATUS.ok);
74960
76037
  });
@@ -74968,16 +76045,16 @@ async function readyOverSocket(socketPath) {
74968
76045
  }
74969
76046
  var HEADROOM_TOOL_NAME = "headroom-ai";
74970
76047
  function readInstalledHeadroomCommit() {
74971
- const toolDir = (0, import_node_child_process5.spawnSync)("uv", ["tool", "dir"], { encoding: "utf8" });
76048
+ const toolDir = (0, import_node_child_process6.spawnSync)("uv", ["tool", "dir"], { encoding: "utf8" });
74972
76049
  if (toolDir.status !== 0) {
74973
76050
  return void 0;
74974
76051
  }
74975
- const libDir = import_node_path38.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
76052
+ const libDir = import_node_path39.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
74976
76053
  for (const python of realFarmFs.readdir(libDir)) {
74977
- const sitePackages = import_node_path38.default.join(libDir, python, "site-packages");
76054
+ const sitePackages = import_node_path39.default.join(libDir, python, "site-packages");
74978
76055
  for (const entry of realFarmFs.readdir(sitePackages)) {
74979
76056
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
74980
- const directUrl = realFarmFs.readFileUtf8(import_node_path38.default.join(sitePackages, entry, "direct_url.json"));
76057
+ const directUrl = realFarmFs.readFileUtf8(import_node_path39.default.join(sitePackages, entry, "direct_url.json"));
74981
76058
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
74982
76059
  }
74983
76060
  }
@@ -75008,7 +76085,7 @@ function realSupervisorPorts(paths) {
75008
76085
  }
75009
76086
  const logFd = import_node_fs16.default.openSync(paths.headroomLogPath, "a");
75010
76087
  try {
75011
- const child = (0, import_node_child_process5.spawn)("headroom", headroomProxyArgs(socketPath, settings2), {
76088
+ const child = (0, import_node_child_process6.spawn)("headroom", headroomProxyArgs(socketPath, settings2), {
75012
76089
  detached: true,
75013
76090
  stdio: ["ignore", logFd, logFd],
75014
76091
  env: headroomSpawnEnv(process.env, allowlist, settings2, trust?.path)
@@ -75048,7 +76125,7 @@ function realSupervisorPorts(paths) {
75048
76125
  },
75049
76126
  ready: readyOverSocket,
75050
76127
  install: (spec) => {
75051
- const result = (0, import_node_child_process5.spawnSync)("uv", ["tool", "install", spec], { encoding: "utf8" });
76128
+ const result = (0, import_node_child_process6.spawnSync)("uv", ["tool", "install", spec], { encoding: "utf8" });
75052
76129
  if (result.error !== void 0) {
75053
76130
  return { ok: false, error: `uv is not installed or not on PATH (${result.error.message})` };
75054
76131
  }
@@ -75061,7 +76138,7 @@ function realSupervisorPorts(paths) {
75061
76138
  return result.status === 0 ? { ok: true } : { ok: false, error: `uv tool install exited ${String(result.status)}` };
75062
76139
  },
75063
76140
  headroomVersion: () => {
75064
- const result = (0, import_node_child_process5.spawnSync)("headroom", ["--version"], { encoding: "utf8" });
76141
+ const result = (0, import_node_child_process6.spawnSync)("headroom", ["--version"], { encoding: "utf8" });
75065
76142
  return result.status === 0 ? result.stdout.trim() : void 0;
75066
76143
  },
75067
76144
  installedCommit: readInstalledHeadroomCommit,
@@ -75244,13 +76321,14 @@ function toProviderView(name, provider) {
75244
76321
  };
75245
76322
  }
75246
76323
  function codexConfigFromOptions(options) {
75247
- if (options.codexDefaultModel === void 0 && options.codexModel === void 0 && options.codexEffort === void 0) {
76324
+ if (options.codexDefaultModel === void 0 && options.codexModel === void 0 && options.codexEffort === void 0 && options.codexLogin === void 0) {
75248
76325
  return void 0;
75249
76326
  }
75250
76327
  const candidate = {
75251
76328
  ...options.codexDefaultModel === void 0 ? {} : { defaultModel: options.codexDefaultModel },
75252
76329
  ...options.codexModel === void 0 ? {} : { models: options.codexModel },
75253
- ...options.codexEffort === void 0 ? {} : { effort: options.codexEffort }
76330
+ ...options.codexEffort === void 0 ? {} : { effort: options.codexEffort },
76331
+ ...options.codexLogin === void 0 ? {} : { login: options.codexLogin }
75254
76332
  };
75255
76333
  const parsed = CodexProviderConfigSchema.safeParse(candidate);
75256
76334
  if (!parsed.success) {
@@ -75273,7 +76351,7 @@ function registerProviderCommand(program2, deps) {
75273
76351
  new Option("--credential-target <target>", "Where the token goes: bearer sets ANTHROPIC_AUTH_TOKEN (default), apiKey sets ANTHROPIC_API_KEY.").choices(
75274
76352
  PROVIDER_CREDENTIAL_TARGETS
75275
76353
  )
75276
- ).option("--env <KEY=VALUE>", "Extra environment entry for the child (repeatable).", collectStringPair).option("--codex-default-model <model>", "Codex providers: the codex model a request maps to when no tier matches.").option("--codex-model <tier=model>", "Codex providers: the codex model one tier (fable, opus, sonnet or haiku) maps to (repeatable).", collectStringPair).addOption(new Option("--codex-effort <effort>", "Codex providers: the reasoning effort when a request asks for none the backend accepts.").choices(CODEX_EFFORTS)).option("--json", "Print the result as JSON.").action((name, options) => {
76354
+ ).option("--env <KEY=VALUE>", "Extra environment entry for the child (repeatable).", collectStringPair).option("--codex-default-model <model>", "Codex providers: the codex model a request maps to when no tier matches.").option("--codex-model <tier=model>", "Codex providers: the codex model one tier (fable, opus, sonnet or haiku) maps to (repeatable).", collectStringPair).addOption(new Option("--codex-effort <effort>", "Codex providers: the reasoning effort when a request asks for none the backend accepts.").choices(CODEX_EFFORTS)).addOption(new Option("--codex-login <login>", "Codex providers: which login the upstream call uses, the Codex CLI's own login or a Sign in with ChatGPT grant from `agent-shim codex login`.").choices(CODEX_LOGINS)).option("--json", "Print the result as JSON.").action((name, options) => {
75277
76355
  const codex = codexConfigFromOptions(options);
75278
76356
  const created = addProvider(paths, name, {
75279
76357
  ...options.kind === void 0 ? {} : { kind: options.kind },
@@ -75305,14 +76383,14 @@ function registerProviderCommand(program2, deps) {
75305
76383
  new Option("--credential-target <target>", "Where the token goes: bearer sets ANTHROPIC_AUTH_TOKEN, apiKey sets ANTHROPIC_API_KEY.").choices(
75306
76384
  PROVIDER_CREDENTIAL_TARGETS
75307
76385
  )
75308
- ).option("--env <KEY=VALUE>", "Add or replace an environment entry for the child (repeatable).", collectStringPair).option("--unset-env <KEY>", "Remove an environment entry (repeatable).", collectRepeated).option("--codex-default-model <model>", "Codex providers: replace the model a request maps to when no tier matches.").option("--codex-model <tier=model>", "Codex providers: set the codex model one tier maps to (repeatable; other tiers are kept).", collectStringPair).addOption(new Option("--codex-effort <effort>", "Codex providers: replace the default reasoning effort.").choices(CODEX_EFFORTS));
76386
+ ).option("--env <KEY=VALUE>", "Add or replace an environment entry for the child (repeatable).", collectStringPair).option("--unset-env <KEY>", "Remove an environment entry (repeatable).", collectRepeated).option("--codex-default-model <model>", "Codex providers: replace the model a request maps to when no tier matches.").option("--codex-model <tier=model>", "Codex providers: set the codex model one tier maps to (repeatable; other tiers are kept).", collectStringPair).addOption(new Option("--codex-effort <effort>", "Codex providers: replace the default reasoning effort.").choices(CODEX_EFFORTS)).addOption(new Option("--codex-login <login>", "Codex providers: replace which login the upstream call uses.").choices(CODEX_LOGINS));
75309
76387
  addCredentialCacheOptions(providerSet);
75310
76388
  withExamples(
75311
76389
  providerSet.option("--json", "Print the result as JSON.").action((name, allOptions) => {
75312
76390
  const { json: json2, ...options } = allOptions;
75313
76391
  if (Object.entries(allOptions).every(([key, value2]) => key === "json" || value2 === void 0)) {
75314
76392
  throw new UsageError(
75315
- "Nothing to change: pass --display-name, --base-url, --credential, --credential-target, a --credential-cache option, --env, --unset-env, --codex-default-model, --codex-model or --codex-effort."
76393
+ "Nothing to change: pass --display-name, --base-url, --credential, --credential-target, a --credential-cache option, --env, --unset-env, --codex-default-model, --codex-model, --codex-effort or --codex-login."
75316
76394
  );
75317
76395
  }
75318
76396
  const codex = codexConfigFromOptions(options);
@@ -75373,6 +76451,7 @@ function registerProviderCommand(program2, deps) {
75373
76451
  const config2 = resolveCodexConfig(found.codex);
75374
76452
  console.log(`Codex models: ${CODEX_TIERS.map((tier) => `${tier}=${config2.models[tier]}`).join(", ")}, otherwise ${config2.defaultModel}`);
75375
76453
  console.log(`Codex effort: ${config2.effort}`);
76454
+ console.log(`Codex login: ${config2.login}`);
75376
76455
  } else {
75377
76456
  console.log(`Base URL: ${found.baseUrl}`);
75378
76457
  }
@@ -75780,11 +76859,11 @@ function buildProgram(deps) {
75780
76859
 
75781
76860
  // src/launchWiring.ts
75782
76861
  var import_node_os8 = __toESM(require("node:os"), 1);
75783
- var import_node_crypto16 = require("node:crypto");
76862
+ var import_node_crypto18 = require("node:crypto");
75784
76863
 
75785
76864
  // src/launcher.ts
75786
- var import_node_crypto15 = require("node:crypto");
75787
- var import_node_path40 = __toESM(require("node:path"), 1);
76865
+ var import_node_crypto17 = require("node:crypto");
76866
+ var import_node_path41 = __toESM(require("node:path"), 1);
75788
76867
 
75789
76868
  // src/launcher/cliOverride.ts
75790
76869
  var InvalidCliCategoryError = class extends CliError {
@@ -75868,7 +76947,7 @@ function buildCliOverride(params) {
75868
76947
  }
75869
76948
 
75870
76949
  // src/launcher/flags.ts
75871
- var import_node_path39 = __toESM(require("node:path"), 1);
76950
+ var import_node_path40 = __toESM(require("node:path"), 1);
75872
76951
 
75873
76952
  // src/headroom/headers.ts
75874
76953
  function mergeAnthropicCustomHeaders(existing, additions) {
@@ -75938,7 +77017,7 @@ function buildEnv(params) {
75938
77017
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
75939
77018
  let providerCustomHeaders;
75940
77019
  if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
75941
- env.CLAUDE_CONFIG_DIR = import_node_path39.default.join(params.identitiesDir, params.resolvedIdentityName);
77020
+ env.CLAUDE_CONFIG_DIR = import_node_path40.default.join(params.identitiesDir, params.resolvedIdentityName);
75942
77021
  }
75943
77022
  if (params.provider !== void 0) {
75944
77023
  const providerEnv = params.provider.definition.env ?? {};
@@ -76122,7 +77201,7 @@ function prepareLaunch(params) {
76122
77201
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
76123
77202
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
76124
77203
  });
76125
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs19.readConfigFile(import_node_path40.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
77204
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs19.readConfigFile(import_node_path41.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
76126
77205
  log.error(
76127
77206
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
76128
77207
  );
@@ -76284,7 +77363,7 @@ function prepareLaunch(params) {
76284
77363
  ...identityCredential === void 0 ? {} : { identityCredential },
76285
77364
  ...frontDoor === void 0 ? {} : { frontdoor: frontDoor },
76286
77365
  ...headroom === void 0 ? {} : { headroom },
76287
- sessionId: (0, import_node_crypto15.randomUUID)()
77366
+ sessionId: (0, import_node_crypto17.randomUUID)()
76288
77367
  });
76289
77368
  const releases = [...headroom === void 0 || headroomPort === void 0 ? [] : [headroomPort.release], ...frontDoorRelease === void 0 ? [] : [frontDoorRelease]];
76290
77369
  const release = () => {
@@ -76329,7 +77408,7 @@ function buildFarmRuntime(paths, cwd) {
76329
77408
  ...cliOverride === void 0 ? {} : { cliOverride }
76330
77409
  }).input,
76331
77410
  now: () => Date.now(),
76332
- uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto16.randomUUID)()}`,
77411
+ uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto18.randomUUID)()}`,
76333
77412
  // Zombie-aware on purpose: a previous launcher that crashed out of a resync without releasing the lock may sit unreaped, still answering signal 0 as alive, and must read as a dead holder so this launch takes the lock over instead of timing out.
76334
77413
  lock: { pid: process.pid, isRunning: realIsProcessRunning, sleep: realSleepSync }
76335
77414
  },
@@ -76468,7 +77547,7 @@ async function runClaude(argvOverride) {
76468
77547
  // src/cli.ts
76469
77548
  async function main() {
76470
77549
  aliasLegacyEnv(process.env);
76471
- const invokedName = import_node_path41.default.basename(process.argv[1] ?? "agent-shim");
77550
+ const invokedName = import_node_path42.default.basename(process.argv[1] ?? "agent-shim");
76472
77551
  if (isInvokedAsClaude(invokedName)) {
76473
77552
  await runClaude();
76474
77553
  return;