claude-use 9.13.0 → 9.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -318,10 +318,10 @@ function mergeDefs(...defs) {
318
318
  function cloneDef(schema) {
319
319
  return mergeDefs(schema._zod.def);
320
320
  }
321
- function getElementAtPath(obj, path51) {
322
- if (!path51)
321
+ function getElementAtPath(obj, path52) {
322
+ if (!path52)
323
323
  return obj;
324
- return path51.reduce((acc, key) => acc?.[key], obj);
324
+ return path52.reduce((acc, key) => acc?.[key], obj);
325
325
  }
326
326
  function promiseAllObject(promisesObj) {
327
327
  const keys = Object.keys(promisesObj);
@@ -580,11 +580,11 @@ function explicitlyAborted(x, startIndex = 0) {
580
580
  }
581
581
  return false;
582
582
  }
583
- function prefixIssues(path51, issues) {
583
+ function prefixIssues(path52, issues) {
584
584
  return issues.map((iss) => {
585
585
  var _a4;
586
586
  (_a4 = iss).path ?? (_a4.path = []);
587
- iss.path.unshift(path51);
587
+ iss.path.unshift(path52);
588
588
  return iss;
589
589
  });
590
590
  }
@@ -1105,16 +1105,16 @@ function flattenError(error63, mapper = (issue2) => issue2.message) {
1105
1105
  }
1106
1106
  function formatError(error63, mapper = (issue2) => issue2.message) {
1107
1107
  const fieldErrors = { _errors: [] };
1108
- const processError = (error64, path51 = []) => {
1108
+ const processError = (error64, path52 = []) => {
1109
1109
  for (const issue2 of error64.issues) {
1110
1110
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1111
- issue2.errors.map((issues) => processError({ issues }, [...path51, ...issue2.path]));
1111
+ issue2.errors.map((issues) => processError({ issues }, [...path52, ...issue2.path]));
1112
1112
  } else if (issue2.code === "invalid_key") {
1113
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1113
+ processError({ issues: issue2.issues }, [...path52, ...issue2.path]);
1114
1114
  } else if (issue2.code === "invalid_element") {
1115
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1115
+ processError({ issues: issue2.issues }, [...path52, ...issue2.path]);
1116
1116
  } else {
1117
- const fullpath = [...path51, ...issue2.path];
1117
+ const fullpath = [...path52, ...issue2.path];
1118
1118
  if (fullpath.length === 0) {
1119
1119
  fieldErrors._errors.push(mapper(issue2));
1120
1120
  } else {
@@ -1153,17 +1153,17 @@ function formatError(error63, mapper = (issue2) => issue2.message) {
1153
1153
  }
1154
1154
  function treeifyError(error63, mapper = (issue2) => issue2.message) {
1155
1155
  const result = { errors: [] };
1156
- const processError = (error64, path51 = []) => {
1156
+ const processError = (error64, path52 = []) => {
1157
1157
  var _a4;
1158
1158
  for (const issue2 of error64.issues) {
1159
1159
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1160
- issue2.errors.map((issues) => processError({ issues }, [...path51, ...issue2.path]));
1160
+ issue2.errors.map((issues) => processError({ issues }, [...path52, ...issue2.path]));
1161
1161
  } else if (issue2.code === "invalid_key") {
1162
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1162
+ processError({ issues: issue2.issues }, [...path52, ...issue2.path]);
1163
1163
  } else if (issue2.code === "invalid_element") {
1164
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1164
+ processError({ issues: issue2.issues }, [...path52, ...issue2.path]);
1165
1165
  } else {
1166
- const fullpath = [...path51, ...issue2.path];
1166
+ const fullpath = [...path52, ...issue2.path];
1167
1167
  if (fullpath.length === 0) {
1168
1168
  result.errors.push(mapper(issue2));
1169
1169
  continue;
@@ -1202,8 +1202,8 @@ function treeifyError(error63, mapper = (issue2) => issue2.message) {
1202
1202
  }
1203
1203
  function toDotPath(_path) {
1204
1204
  const segs = [];
1205
- const path51 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
- for (const seg of path51) {
1205
+ const path52 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
+ for (const seg of path52) {
1207
1207
  if (typeof seg === "number")
1208
1208
  segs.push(`[${seg}]`);
1209
1209
  else if (typeof seg === "symbol")
@@ -19199,13 +19199,13 @@ function resolveRef(ref, ctx) {
19199
19199
  if (!ref.startsWith("#")) {
19200
19200
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19201
19201
  }
19202
- const path51 = ref.slice(1).split("/").filter(Boolean);
19203
- if (path51.length === 0) {
19202
+ const path52 = ref.slice(1).split("/").filter(Boolean);
19203
+ if (path52.length === 0) {
19204
19204
  return ctx.rootSchema;
19205
19205
  }
19206
19206
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19207
- if (path51[0] === defsKey) {
19208
- const key = path51[1] === void 0 ? void 0 : decodeJSONPointerSegment(path51[1]);
19207
+ if (path52[0] === defsKey) {
19208
+ const key = path52[1] === void 0 ? void 0 : decodeJSONPointerSegment(path52[1]);
19209
19209
  if (!key || !ctx.defs[key]) {
19210
19210
  throw new Error(`Reference not found: ${ref}`);
19211
19211
  }
@@ -23712,42 +23712,42 @@ var require_defaults = __commonJS({
23712
23712
  var require_env_paths = __commonJS({
23713
23713
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
23714
23714
  "use strict";
23715
- var path51 = require("path");
23715
+ var path52 = require("path");
23716
23716
  var os12 = require("os");
23717
23717
  var homedir = os12.homedir();
23718
23718
  var tmpdir = os12.tmpdir();
23719
23719
  var { env } = process;
23720
23720
  var macos = (name) => {
23721
- const library = path51.join(homedir, "Library");
23721
+ const library = path52.join(homedir, "Library");
23722
23722
  return {
23723
- data: path51.join(library, "Application Support", name),
23724
- config: path51.join(library, "Preferences", name),
23725
- cache: path51.join(library, "Caches", name),
23726
- log: path51.join(library, "Logs", name),
23727
- temp: path51.join(tmpdir, name)
23723
+ data: path52.join(library, "Application Support", name),
23724
+ config: path52.join(library, "Preferences", name),
23725
+ cache: path52.join(library, "Caches", name),
23726
+ log: path52.join(library, "Logs", name),
23727
+ temp: path52.join(tmpdir, name)
23728
23728
  };
23729
23729
  };
23730
23730
  var windows = (name) => {
23731
- const appData = env.APPDATA || path51.join(homedir, "AppData", "Roaming");
23732
- const localAppData = env.LOCALAPPDATA || path51.join(homedir, "AppData", "Local");
23731
+ const appData = env.APPDATA || path52.join(homedir, "AppData", "Roaming");
23732
+ const localAppData = env.LOCALAPPDATA || path52.join(homedir, "AppData", "Local");
23733
23733
  return {
23734
23734
  // Data/config/cache/log are invented by me as Windows isn't opinionated about this
23735
- data: path51.join(localAppData, name, "Data"),
23736
- config: path51.join(appData, name, "Config"),
23737
- cache: path51.join(localAppData, name, "Cache"),
23738
- log: path51.join(localAppData, name, "Log"),
23739
- temp: path51.join(tmpdir, name)
23735
+ data: path52.join(localAppData, name, "Data"),
23736
+ config: path52.join(appData, name, "Config"),
23737
+ cache: path52.join(localAppData, name, "Cache"),
23738
+ log: path52.join(localAppData, name, "Log"),
23739
+ temp: path52.join(tmpdir, name)
23740
23740
  };
23741
23741
  };
23742
23742
  var linux = (name) => {
23743
- const username = path51.basename(homedir);
23743
+ const username = path52.basename(homedir);
23744
23744
  return {
23745
- data: path51.join(env.XDG_DATA_HOME || path51.join(homedir, ".local", "share"), name),
23746
- config: path51.join(env.XDG_CONFIG_HOME || path51.join(homedir, ".config"), name),
23747
- cache: path51.join(env.XDG_CACHE_HOME || path51.join(homedir, ".cache"), name),
23745
+ data: path52.join(env.XDG_DATA_HOME || path52.join(homedir, ".local", "share"), name),
23746
+ config: path52.join(env.XDG_CONFIG_HOME || path52.join(homedir, ".config"), name),
23747
+ cache: path52.join(env.XDG_CACHE_HOME || path52.join(homedir, ".cache"), name),
23748
23748
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
23749
- log: path51.join(env.XDG_STATE_HOME || path51.join(homedir, ".local", "state"), name),
23750
- temp: path51.join(tmpdir, username, name)
23749
+ log: path52.join(env.XDG_STATE_HOME || path52.join(homedir, ".local", "state"), name),
23750
+ temp: path52.join(tmpdir, username, name)
23751
23751
  };
23752
23752
  };
23753
23753
  var envPaths = (name, options) => {
@@ -23815,11 +23815,11 @@ var require_util = __commonJS({
23815
23815
  return result;
23816
23816
  }
23817
23817
  exports2.emplace = emplace;
23818
- function getPropertyByPath(source, path51) {
23819
- if (typeof path51 === "string" && Object.prototype.hasOwnProperty.call(source, path51)) {
23820
- return source[path51];
23818
+ function getPropertyByPath(source, path52) {
23819
+ if (typeof path52 === "string" && Object.prototype.hasOwnProperty.call(source, path52)) {
23820
+ return source[path52];
23821
23821
  }
23822
- const parsedPath = typeof path51 === "string" ? path51.split(".") : path51;
23822
+ const parsedPath = typeof path52 === "string" ? path52.split(".") : path52;
23823
23823
  return parsedPath.reduce((previous, key) => {
23824
23824
  if (previous === void 0) {
23825
23825
  return previous;
@@ -23842,9 +23842,9 @@ var require_util = __commonJS({
23842
23842
  return Object.fromEntries(Object.entries(options).filter(([, value2]) => value2 !== void 0));
23843
23843
  }
23844
23844
  exports2.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
23845
- async function isDirectory(path51) {
23845
+ async function isDirectory(path52) {
23846
23846
  try {
23847
- const stat = await fs_1.promises.stat(path51);
23847
+ const stat = await fs_1.promises.stat(path52);
23848
23848
  return stat.isDirectory();
23849
23849
  } catch (e14) {
23850
23850
  if (e14.code === "ENOENT") {
@@ -23854,9 +23854,9 @@ var require_util = __commonJS({
23854
23854
  }
23855
23855
  }
23856
23856
  exports2.isDirectory = isDirectory;
23857
- function isDirectorySync(path51) {
23857
+ function isDirectorySync(path52) {
23858
23858
  try {
23859
- const stat = fs_1.default.statSync(path51);
23859
+ const stat = fs_1.default.statSync(path52);
23860
23860
  return stat.isDirectory();
23861
23861
  } catch (e14) {
23862
23862
  if (e14.code === "ENOENT") {
@@ -23954,7 +23954,7 @@ var require_ExplorerBase = __commonJS({
23954
23954
  const idx = importStack.indexOf(fullPath);
23955
23955
  if (idx !== -1) {
23956
23956
  throw new Error(`Circular import detected:
23957
- ${[...importStack, fullPath].map((path51, i10) => `${i10 + 1}. ${path51}`).join("\n")} (same as ${idx + 1}.)`);
23957
+ ${[...importStack, fullPath].map((path52, i10) => `${i10 + 1}. ${path52}`).join("\n")} (same as ${idx + 1}.)`);
23958
23958
  }
23959
23959
  }
23960
23960
  }
@@ -24142,9 +24142,9 @@ var require_Explorer = __commonJS({
24142
24142
  throw error63;
24143
24143
  }
24144
24144
  }
24145
- async #fileExists(path51) {
24145
+ async #fileExists(path52) {
24146
24146
  try {
24147
- await promises_1.default.stat(path51);
24147
+ await promises_1.default.stat(path52);
24148
24148
  return true;
24149
24149
  } catch (e14) {
24150
24150
  return false;
@@ -24304,9 +24304,9 @@ var require_ExplorerSync = __commonJS({
24304
24304
  throw error63;
24305
24305
  }
24306
24306
  }
24307
- #fileExists(path51) {
24307
+ #fileExists(path52) {
24308
24308
  try {
24309
- fs_1.default.statSync(path51);
24309
+ fs_1.default.statSync(path52);
24310
24310
  return true;
24311
24311
  } catch (e14) {
24312
24312
  return false;
@@ -24430,7 +24430,7 @@ var require_dist = __commonJS({
24430
24430
  };
24431
24431
  }
24432
24432
  function getResolvedSearchPlaces(moduleName, toolDefinedSearchPlaces, userConfiguredOptions) {
24433
- const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path51) => path51.replace("{name}", moduleName));
24433
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path52) => path52.replace("{name}", moduleName));
24434
24434
  if (userConfiguredOptions.mergeSearchPlaces) {
24435
24435
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
24436
24436
  }
@@ -26799,7 +26799,15 @@ function isCodexProvider(provider) {
26799
26799
  function poolMemberIdentity(member) {
26800
26800
  return typeof member === "string" ? member : member.identity;
26801
26801
  }
26802
- var import_node_path4, CATEGORY_NAMES, OVERRIDABLE_CATEGORIES, CategoryMapSchema, DURATION_RE, DurationSchema, WhenConditionObjectSchema, WhenSchema, EntryValueSchema, ENTRY_KEY_RE, EntriesSchema, LaunchSchema, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETS, CREDENTIAL_TARGET_VARS, ArgvSchema, CommandSourceOptions, EnvCredentialSourceSchema, FileCredentialSourceSchema, CommandCredentialSourceSchema, OpCredentialSourceSchema, KeychainCredentialSourceSchema, LiteralCredentialSourceSchema, CredentialSourceSchema, RemoteCredentialSourceSchema, CREDENTIAL_CACHE_STORES, CredentialCacheSchema, CredentialSchema, ProviderCredentialSchema, RESERVED_PROVIDER_ENV_KEYS, ProviderEnvSchema, PROVIDER_KINDS, CODEX_TIERS, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, HttpProviderSchema, CodexProviderSchema, ProviderSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, IDENTITY_NAME_PATTERN, PoolNameSchema, SELECTOR_RE, IdentitySelectorSchema, PoolMemberSchema, POOL_PREFERENCES, PoolPreferenceSchema, PoolSchema, DirectoryRuleSchema, DirectoryRulesSchema, PortableConfigSchema, HEADROOM_MODES, HEADROOM_CCR_MODES, HEADROOM_ROLLOUT_CHANNELS, INTERCEPT_CHANNELS, READ_MATURATION_CHANNELS, HeadroomGlobalConfigObjectSchema, HeadroomGlobalConfigSchema, HEADROOM_DEFAULT_SOURCE, HEADROOM_DEFAULT_IDLE_SHUTDOWN_MINUTES, FRONTDOOR_DEFAULT_IDLE_SHUTDOWN_MINUTES, FrontDoorGlobalConfigSchema, UPDATE_MODES, UpdateGlobalConfigSchema, GlobalConfigSchema, IdentitySchema, CategoryClassificationSchema, CategoryClassificationOverlaySchema, SHIPPED_CATEGORY_DEFAULTS;
26802
+ function isTimeZone(name) {
26803
+ try {
26804
+ new Intl.DateTimeFormat("en", { timeZone: name });
26805
+ return true;
26806
+ } catch {
26807
+ return false;
26808
+ }
26809
+ }
26810
+ var import_node_path4, CATEGORY_NAMES, OVERRIDABLE_CATEGORIES, CategoryMapSchema, DURATION_RE, DurationSchema, WhenConditionObjectSchema, WhenSchema, EntryValueSchema, ENTRY_KEY_RE, EntriesSchema, LaunchSchema, CREDENTIAL_TARGETS, PROVIDER_CREDENTIAL_TARGETS, CREDENTIAL_TARGET_VARS, ArgvSchema, CommandSourceOptions, EnvCredentialSourceSchema, FileCredentialSourceSchema, CommandCredentialSourceSchema, OpCredentialSourceSchema, KeychainCredentialSourceSchema, LiteralCredentialSourceSchema, CredentialSourceSchema, RemoteCredentialSourceSchema, CREDENTIAL_CACHE_STORES, CredentialCacheSchema, CredentialSchema, ProviderCredentialSchema, RESERVED_PROVIDER_ENV_KEYS, ProviderEnvSchema, PROVIDER_KINDS, CODEX_TIERS, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, HttpProviderSchema, CodexProviderSchema, ProviderSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, IDENTITY_NAME_PATTERN, PoolNameSchema, SELECTOR_RE, IdentitySelectorSchema, PoolMemberSchema, POOL_PREFERENCES, PoolPreferenceSchema, PoolSchema, DirectoryRuleSchema, DirectoryRulesSchema, PortableConfigSchema, HEADROOM_MODES, HEADROOM_CCR_MODES, HEADROOM_ROLLOUT_CHANNELS, INTERCEPT_CHANNELS, READ_MATURATION_CHANNELS, HeadroomGlobalConfigObjectSchema, HeadroomGlobalConfigSchema, HEADROOM_DEFAULT_SOURCE, HEADROOM_DEFAULT_IDLE_SHUTDOWN_MINUTES, FRONTDOOR_DEFAULT_IDLE_SHUTDOWN_MINUTES, FrontDoorGlobalConfigSchema, UPDATE_MODES, UpdateGlobalConfigSchema, GlobalConfigSchema, WEEKDAYS, AnchorSchema, IdentitySchema, CategoryClassificationSchema, CategoryClassificationOverlaySchema, SHIPPED_CATEGORY_DEFAULTS;
26803
26811
  var init_schema = __esm({
26804
26812
  "src/config/schema.ts"() {
26805
26813
  "use strict";
@@ -27044,12 +27052,20 @@ var init_schema = __esm({
27044
27052
  update: UpdateGlobalConfigSchema.optional(),
27045
27053
  pools: external_exports.record(PoolNameSchema, PoolSchema).optional()
27046
27054
  });
27055
+ WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
27056
+ AnchorSchema = external_exports.strictObject({
27057
+ days: external_exports.array(external_exports.enum(WEEKDAYS)).min(1).refine((days) => new Set(days).size === days.length, "an anchor names each weekday at most once"),
27058
+ time: external_exports.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "a 24-hour time such as 06:00"),
27059
+ timeZone: external_exports.string().refine(isTimeZone, "an IANA time zone such as Europe/London").optional()
27060
+ });
27047
27061
  IdentitySchema = external_exports.strictObject({
27048
27062
  $schema: external_exports.string().optional(),
27049
27063
  name: external_exports.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9._@-]*$/),
27050
27064
  defaultConfigProfile: external_exports.string().min(1).optional(),
27051
27065
  allowAmbientCredential: external_exports.boolean().default(false),
27052
- credential: CredentialSchema.optional()
27066
+ credential: CredentialSchema.optional(),
27067
+ /** When this identity's five-hour window should be open: the front door opens one at each anchor if none is. Absent, nothing is opened on a schedule. */
27068
+ anchors: external_exports.array(AnchorSchema).min(1).optional()
27053
27069
  });
27054
27070
  CategoryClassificationSchema = external_exports.strictObject({
27055
27071
  $schema: external_exports.string().optional(),
@@ -28911,8 +28927,8 @@ var require_utils = __commonJS({
28911
28927
  }
28912
28928
  return output2;
28913
28929
  };
28914
- exports2.basename = (path51, { windows } = {}) => {
28915
- const segs = path51.split(windows ? /[\\/]/ : "/");
28930
+ exports2.basename = (path52, { windows } = {}) => {
28931
+ const segs = path52.split(windows ? /[\\/]/ : "/");
28916
28932
  const last = segs[segs.length - 1];
28917
28933
  if (last === "") {
28918
28934
  return segs[segs.length - 2];
@@ -32578,6 +32594,7 @@ function buildLayoutPaths(root) {
32578
32594
  usageLogDir: import_node_path19.default.join(root, "usage", "log"),
32579
32595
  usageSnapshotsDir: import_node_path19.default.join(root, "usage", "snapshots"),
32580
32596
  usagePicksFile: import_node_path19.default.join(root, "usage", "picks.json"),
32597
+ usageAnchorsFile: import_node_path19.default.join(root, "usage", "anchors.json"),
32581
32598
  mcpPermissionsFile: import_node_path19.default.join(root, "mcp", "permissions.json")
32582
32599
  };
32583
32600
  }
@@ -32595,6 +32612,47 @@ var init_paths = __esm({
32595
32612
  }
32596
32613
  });
32597
32614
 
32615
+ // src/cli/pairs.ts
32616
+ function splitCommas(input2) {
32617
+ if (input2 === "") {
32618
+ return [];
32619
+ }
32620
+ return input2.split(",");
32621
+ }
32622
+ function parsePair(input2) {
32623
+ const eqIndex = input2.indexOf("=");
32624
+ if (eqIndex === -1) {
32625
+ throw new Error(`Expected "<key>=<value>", got "${input2}" (no "=" found)`);
32626
+ }
32627
+ const key = input2.slice(0, eqIndex);
32628
+ const value2 = input2.slice(eqIndex + 1);
32629
+ if (key === "") {
32630
+ throw new Error(`Expected a non-empty key before "=" in "${input2}"`);
32631
+ }
32632
+ return { key, value: value2 };
32633
+ }
32634
+ function parseBool(input2) {
32635
+ const parsed = parseBoolWord(input2);
32636
+ if (parsed === void 0) {
32637
+ throw new Error(`Expected "true", "false", "1" or "0", got "${input2}"`);
32638
+ }
32639
+ return parsed;
32640
+ }
32641
+ function parseBoolPairList(input2) {
32642
+ const result = {};
32643
+ for (const piece of splitCommas(input2)) {
32644
+ const { key, value: value2 } = parsePair(piece);
32645
+ result[key] = parseBool(value2);
32646
+ }
32647
+ return result;
32648
+ }
32649
+ var init_pairs = __esm({
32650
+ "src/cli/pairs.ts"() {
32651
+ "use strict";
32652
+ init_bool();
32653
+ }
32654
+ });
32655
+
32598
32656
  // src/usage/schema.ts
32599
32657
  function isRateLimitHeader(name) {
32600
32658
  const lower = name.toLowerCase();
@@ -32794,7 +32852,7 @@ function epochSecondsToIso(value2) {
32794
32852
  return void 0;
32795
32853
  }
32796
32854
  const seconds = Number(value2);
32797
- return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * MS_PER_SECOND).toISOString() : void 0;
32855
+ return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * MS_PER_SECOND2).toISOString() : void 0;
32798
32856
  }
32799
32857
  function nonNegativeNumber(value2) {
32800
32858
  if (value2 === void 0 || value2.trim() === "") {
@@ -32878,7 +32936,7 @@ function retryAfterSeconds(value2, nowMs) {
32878
32936
  return seconds;
32879
32937
  }
32880
32938
  const date5 = Date.parse(value2);
32881
- return Number.isNaN(date5) ? void 0 : Math.max(0, Math.ceil((date5 - nowMs) / MS_PER_SECOND));
32939
+ return Number.isNaN(date5) ? void 0 : Math.max(0, Math.ceil((date5 - nowMs) / MS_PER_SECOND2));
32882
32940
  }
32883
32941
  function classifyLimit(params) {
32884
32942
  const { status, headers, error: error63 } = params;
@@ -32917,14 +32975,14 @@ function classifyLimit(params) {
32917
32975
  evidence
32918
32976
  };
32919
32977
  }
32920
- var TOO_MANY_REQUESTS, PAYMENT_REQUIRED, MS_PER_SECOND, UNIFIED_PREFIX, QUOTA_EXHAUSTED_ERRORS, QUOTA_EXHAUSTED_MESSAGE, EVIDENCE_TOKEN;
32978
+ var TOO_MANY_REQUESTS, PAYMENT_REQUIRED, MS_PER_SECOND2, UNIFIED_PREFIX, QUOTA_EXHAUSTED_ERRORS, QUOTA_EXHAUSTED_MESSAGE, EVIDENCE_TOKEN;
32921
32979
  var init_rateLimit = __esm({
32922
32980
  "src/usage/rateLimit.ts"() {
32923
32981
  "use strict";
32924
32982
  init_schema2();
32925
32983
  TOO_MANY_REQUESTS = 429;
32926
32984
  PAYMENT_REQUIRED = 402;
32927
- MS_PER_SECOND = 1e3;
32985
+ MS_PER_SECOND2 = 1e3;
32928
32986
  UNIFIED_PREFIX = "anthropic-ratelimit-unified-";
32929
32987
  QUOTA_EXHAUSTED_ERRORS = /* @__PURE__ */ new Set(["usage_limit_reached", "insufficient_quota", "1308", "1309", "1310", "1316", "1317", "1318", "1319", "1320", "1321"]);
32930
32988
  QUOTA_EXHAUSTED_MESSAGE = /usage limit|quota (?:exceeded|exhausted)|limit exhausted|insufficient (?:balance|credits|quota)/i;
@@ -32934,11 +32992,11 @@ var init_rateLimit = __esm({
32934
32992
 
32935
32993
  // src/usage/preflight.ts
32936
32994
  function formatAge(ms2) {
32937
- const minutes = Math.floor(ms2 / (MS_PER_SECOND2 * SECONDS_PER_MINUTE));
32938
- if (minutes < MINUTES_PER_HOUR) {
32995
+ const minutes = Math.floor(ms2 / (MS_PER_SECOND3 * SECONDS_PER_MINUTE));
32996
+ if (minutes < MINUTES_PER_HOUR2) {
32939
32997
  return `${String(Math.max(minutes, 0))}m`;
32940
32998
  }
32941
- const hours = Math.floor(minutes / MINUTES_PER_HOUR);
32999
+ const hours = Math.floor(minutes / MINUTES_PER_HOUR2);
32942
33000
  return hours < HOURS_PER_DAY ? `${String(hours)}h` : `${String(Math.floor(hours / HOURS_PER_DAY))}d`;
32943
33001
  }
32944
33002
  function effectiveWindow(window, nowMs) {
@@ -32975,14 +33033,14 @@ function quotaWarnings(snapshot, provider, nowMs) {
32975
33033
  return [`agent-shim: identity ${snapshot.identity}: the ${name} quota is ${verdict}${reset} (last seen ${age2} ago)`];
32976
33034
  });
32977
33035
  }
32978
- var MS_PER_SECOND2, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, WARNING_STATUSES;
33036
+ var MS_PER_SECOND3, SECONDS_PER_MINUTE, MINUTES_PER_HOUR2, HOURS_PER_DAY, WARNING_STATUSES;
32979
33037
  var init_preflight = __esm({
32980
33038
  "src/usage/preflight.ts"() {
32981
33039
  "use strict";
32982
33040
  init_rateLimit();
32983
- MS_PER_SECOND2 = 1e3;
33041
+ MS_PER_SECOND3 = 1e3;
32984
33042
  SECONDS_PER_MINUTE = 60;
32985
- MINUTES_PER_HOUR = 60;
33043
+ MINUTES_PER_HOUR2 = 60;
32986
33044
  HOURS_PER_DAY = 24;
32987
33045
  WARNING_STATUSES = /* @__PURE__ */ new Set(["allowed_warning", "rejected"]);
32988
33046
  }
@@ -33237,54 +33295,13 @@ var init_credential = __esm({
33237
33295
  }
33238
33296
  });
33239
33297
 
33240
- // src/cli/pairs.ts
33241
- function splitCommas(input2) {
33242
- if (input2 === "") {
33243
- return [];
33244
- }
33245
- return input2.split(",");
33246
- }
33247
- function parsePair(input2) {
33248
- const eqIndex = input2.indexOf("=");
33249
- if (eqIndex === -1) {
33250
- throw new Error(`Expected "<key>=<value>", got "${input2}" (no "=" found)`);
33251
- }
33252
- const key = input2.slice(0, eqIndex);
33253
- const value2 = input2.slice(eqIndex + 1);
33254
- if (key === "") {
33255
- throw new Error(`Expected a non-empty key before "=" in "${input2}"`);
33256
- }
33257
- return { key, value: value2 };
33258
- }
33259
- function parseBool(input2) {
33260
- const parsed = parseBoolWord(input2);
33261
- if (parsed === void 0) {
33262
- throw new Error(`Expected "true", "false", "1" or "0", got "${input2}"`);
33263
- }
33264
- return parsed;
33265
- }
33266
- function parseBoolPairList(input2) {
33267
- const result = {};
33268
- for (const piece of splitCommas(input2)) {
33269
- const { key, value: value2 } = parsePair(piece);
33270
- result[key] = parseBool(value2);
33271
- }
33272
- return result;
33273
- }
33274
- var init_pairs = __esm({
33275
- "src/cli/pairs.ts"() {
33276
- "use strict";
33277
- init_bool();
33278
- }
33279
- });
33280
-
33281
33298
  // package.json
33282
33299
  var package_default;
33283
33300
  var init_package = __esm({
33284
33301
  "package.json"() {
33285
33302
  package_default = {
33286
33303
  name: "claude-use",
33287
- version: "9.13.0",
33304
+ version: "9.14.0",
33288
33305
  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.",
33289
33306
  license: "MIT",
33290
33307
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -33555,11 +33572,11 @@ function identifyRequest(headers) {
33555
33572
  function directOrigin(port) {
33556
33573
  return `http://127.0.0.1:${String(port)}`;
33557
33574
  }
33558
- function parseProviderPath(path51) {
33559
- if (!path51.startsWith(PROVIDER_PATH_PREFIX)) {
33575
+ function parseProviderPath(path52) {
33576
+ if (!path52.startsWith(PROVIDER_PATH_PREFIX)) {
33560
33577
  return void 0;
33561
33578
  }
33562
- const tail = path51.slice(PROVIDER_PATH_PREFIX.length);
33579
+ const tail = path52.slice(PROVIDER_PATH_PREFIX.length);
33563
33580
  const slash = tail.indexOf("/");
33564
33581
  if (slash <= 0) {
33565
33582
  return void 0;
@@ -33885,9 +33902,9 @@ function decoderFor(encoding) {
33885
33902
  return void 0;
33886
33903
  }
33887
33904
  }
33888
- function destinationOf(path51) {
33889
- const scoped = parseProviderPath(path51);
33890
- return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path51 } : { provider: scoped.provider, endpoint: scoped.rest };
33905
+ function destinationOf(path52) {
33906
+ const scoped = parseProviderPath(path52);
33907
+ return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path52 } : { provider: scoped.provider, endpoint: scoped.rest };
33891
33908
  }
33892
33909
  function buildRecord(event, context) {
33893
33910
  const { scan } = context;
@@ -34044,7 +34061,7 @@ function limitBlockedUntil(state, nowMs) {
34044
34061
  if (state.lastRequestAt !== void 0 && Date.parse(state.lastRequestAt) > Date.parse(limit.observedAt)) {
34045
34062
  return void 0;
34046
34063
  }
34047
- const until = limit.resetAt === void 0 ? limit.retryAfterSeconds === void 0 ? void 0 : Date.parse(limit.observedAt) + limit.retryAfterSeconds * MS_PER_SECOND3 : Date.parse(limit.resetAt);
34064
+ const until = limit.resetAt === void 0 ? limit.retryAfterSeconds === void 0 ? void 0 : Date.parse(limit.observedAt) + limit.retryAfterSeconds * MS_PER_SECOND4 : Date.parse(limit.resetAt);
34048
34065
  return until !== void 0 && until > nowMs ? until : void 0;
34049
34066
  }
34050
34067
  function windowBlockedUntil(windows) {
@@ -34167,10 +34184,10 @@ function assessIdentity(member, nowMs) {
34167
34184
  return { candidate: { ...base, class: "unknown", reasons: ["quota windows reported no utilisation", ...windowReasons, ...planReasons] } };
34168
34185
  }
34169
34186
  const remaining = Math.max(0, 1 - basis.window.utilization);
34170
- const untilResetMs = basis.window.resetsAtMs === void 0 ? basis.windowMs : Math.max(basis.window.resetsAtMs - nowMs, MS_PER_SECOND3);
34187
+ const untilResetMs = basis.window.resetsAtMs === void 0 ? basis.windowMs : Math.max(basis.window.resetsAtMs - nowMs, MS_PER_SECOND4);
34171
34188
  const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR2);
34172
34189
  const fiveRemaining = five?.utilization === void 0 ? void 0 : Math.max(0, 1 - five.utilization);
34173
- const fiveUntil = five?.resetsAtMs === void 0 ? FIVE_HOUR_WINDOW_MS : Math.max(five.resetsAtMs - nowMs, MS_PER_SECOND3);
34190
+ const fiveUntil = five?.resetsAtMs === void 0 ? FIVE_HOUR_WINDOW_MS : Math.max(five.resetsAtMs - nowMs, MS_PER_SECOND4);
34174
34191
  const ratio = windowRatio(member.records);
34175
34192
  const fiveHourScore = basis.name === "sevenDay" && fiveRemaining !== void 0 && ratio !== void 0 ? Math.min(fiveRemaining * ratio, remaining) * plan.capacity / (fiveUntil / MS_PER_HOUR2) : void 0;
34176
34193
  const fiveHourLeads = fiveHourScore !== void 0 && fiveHourScore > weeklyScore;
@@ -34179,7 +34196,7 @@ function assessIdentity(member, nowMs) {
34179
34196
  const fiveHourTermReasons = basis.name !== "sevenDay" || fiveRemaining === void 0 ? [] : ratio === void 0 ? ["5h reset not scored: no measured 5h to 7d ratio yet"] : fiveHourLeads ? [`5h term leads: ${percent(fiveRemaining)} of 5h unused is about ${percent(Math.min(fiveRemaining * ratio, remaining))} of the week at the measured ratio, resets in ${formatAge(fiveUntil)}`] : [];
34180
34197
  const burn = windowBurn(member.records, "fiveHour");
34181
34198
  const sevenRemaining = seven?.utilization === void 0 ? void 0 : Math.max(0, 1 - seven.utilization);
34182
- const sevenUntil = seven?.resetsAtMs === void 0 ? SEVEN_DAY_WINDOW_MS : Math.max(seven.resetsAtMs - nowMs, MS_PER_SECOND3);
34199
+ const sevenUntil = seven?.resetsAtMs === void 0 ? SEVEN_DAY_WINDOW_MS : Math.max(seven.resetsAtMs - nowMs, MS_PER_SECOND4);
34183
34200
  const sevenDayBurn = windowBurn(member.records, "sevenDay");
34184
34201
  return {
34185
34202
  candidate: { ...base, class: "scored", score, scoreWindow, reasons: [...fiveHourTermReasons, ...windowReasons.map((reason, index) => index === windowReasons.length - 1 ? `${reason}${observedAgo}` : reason), ...planReasons] },
@@ -34273,7 +34290,7 @@ function rankPool(input2) {
34273
34290
  ...pick2?.planReturnsAtMs === void 0 ? {} : { planReturn: { identity: pick2.identity, atMs: pick2.planReturnsAtMs } }
34274
34291
  };
34275
34292
  }
34276
- var MS_PER_SECOND3, MS_PER_HOUR2, HOURS_PER_DAY2, FIVE_HOURS, PROMPT_CACHE_TTL_HOURS, PERCENT, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
34293
+ var MS_PER_SECOND4, MS_PER_HOUR2, HOURS_PER_DAY2, FIVE_HOURS, PROMPT_CACHE_TTL_HOURS, PERCENT, SEVEN_DAYS, FIVE_HOUR_WINDOW_MS, SEVEN_DAY_WINDOW_MS, PROMPT_CACHE_TTL_MS, CLASS_ORDER;
34277
34294
  var init_pick = __esm({
34278
34295
  "src/usage/pick.ts"() {
34279
34296
  "use strict";
@@ -34283,7 +34300,7 @@ var init_pick = __esm({
34283
34300
  init_preflight();
34284
34301
  init_quotaFacts();
34285
34302
  init_rateLimit();
34286
- MS_PER_SECOND3 = 1e3;
34303
+ MS_PER_SECOND4 = 1e3;
34287
34304
  MS_PER_HOUR2 = 36e5;
34288
34305
  HOURS_PER_DAY2 = 24;
34289
34306
  FIVE_HOURS = 5;
@@ -34568,7 +34585,7 @@ function createUsageStore(deps) {
34568
34585
  })
34569
34586
  };
34570
34587
  }
34571
- var import_node_path25, DAY_MS2, DAYS_IN_WEEK, USAGE_RETENTION_MS;
34588
+ var import_node_path25, DAY_MS2, DAYS_IN_WEEK2, USAGE_RETENTION_MS;
34572
34589
  var init_store2 = __esm({
34573
34590
  "src/usage/store.ts"() {
34574
34591
  "use strict";
@@ -34578,8 +34595,8 @@ var init_store2 = __esm({
34578
34595
  init_read();
34579
34596
  init_schema2();
34580
34597
  DAY_MS2 = 864e5;
34581
- DAYS_IN_WEEK = 7;
34582
- USAGE_RETENTION_MS = DAYS_IN_WEEK * DAY_MS2;
34598
+ DAYS_IN_WEEK2 = 7;
34599
+ USAGE_RETENTION_MS = DAYS_IN_WEEK2 * DAY_MS2;
34583
34600
  }
34584
34601
  });
34585
34602
 
@@ -36323,14 +36340,14 @@ var require_util2 = __commonJS({
36323
36340
  }
36324
36341
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
36325
36342
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
36326
- let path51 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36343
+ let path52 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36327
36344
  if (origin[origin.length - 1] === "/") {
36328
36345
  origin = origin.slice(0, origin.length - 1);
36329
36346
  }
36330
- if (path51 && path51[0] !== "/") {
36331
- path51 = `/${path51}`;
36347
+ if (path52 && path52[0] !== "/") {
36348
+ path52 = `/${path52}`;
36332
36349
  }
36333
- return new URL(`${origin}${path51}`);
36350
+ return new URL(`${origin}${path52}`);
36334
36351
  }
36335
36352
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
36336
36353
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -37151,9 +37168,9 @@ var require_diagnostics = __commonJS({
37151
37168
  "undici:client:sendHeaders",
37152
37169
  (evt) => {
37153
37170
  const {
37154
- request: { method, path: path51, origin }
37171
+ request: { method, path: path52, origin }
37155
37172
  } = evt;
37156
- debugLog("sending request to %s %s%s", method, origin, path51);
37173
+ debugLog("sending request to %s %s%s", method, origin, path52);
37157
37174
  }
37158
37175
  );
37159
37176
  }
@@ -37171,14 +37188,14 @@ var require_diagnostics = __commonJS({
37171
37188
  "undici:request:headers",
37172
37189
  (evt) => {
37173
37190
  const {
37174
- request: { method, path: path51, origin },
37191
+ request: { method, path: path52, origin },
37175
37192
  response: { statusCode }
37176
37193
  } = evt;
37177
37194
  debugLog(
37178
37195
  "received response to %s %s%s - HTTP %d",
37179
37196
  method,
37180
37197
  origin,
37181
- path51,
37198
+ path52,
37182
37199
  statusCode
37183
37200
  );
37184
37201
  }
@@ -37187,23 +37204,23 @@ var require_diagnostics = __commonJS({
37187
37204
  "undici:request:trailers",
37188
37205
  (evt) => {
37189
37206
  const {
37190
- request: { method, path: path51, origin }
37207
+ request: { method, path: path52, origin }
37191
37208
  } = evt;
37192
- debugLog("trailers received from %s %s%s", method, origin, path51);
37209
+ debugLog("trailers received from %s %s%s", method, origin, path52);
37193
37210
  }
37194
37211
  );
37195
37212
  diagnosticsChannel.subscribe(
37196
37213
  "undici:request:error",
37197
37214
  (evt) => {
37198
37215
  const {
37199
- request: { method, path: path51, origin },
37216
+ request: { method, path: path52, origin },
37200
37217
  error: error63
37201
37218
  } = evt;
37202
37219
  debugLog(
37203
37220
  "request to %s %s%s errored - %s",
37204
37221
  method,
37205
37222
  origin,
37206
- path51,
37223
+ path52,
37207
37224
  error63.message
37208
37225
  );
37209
37226
  }
@@ -37318,7 +37335,7 @@ var require_request = __commonJS({
37318
37335
  var kHandler = /* @__PURE__ */ Symbol("handler");
37319
37336
  var Request2 = class {
37320
37337
  constructor(origin, {
37321
- path: path51,
37338
+ path: path52,
37322
37339
  method,
37323
37340
  body,
37324
37341
  headers,
@@ -37335,11 +37352,11 @@ var require_request = __commonJS({
37335
37352
  maxRedirections,
37336
37353
  typeOfService
37337
37354
  }, handler) {
37338
- if (typeof path51 !== "string") {
37355
+ if (typeof path52 !== "string") {
37339
37356
  throw new InvalidArgumentError2("path must be a string");
37340
- } else if (path51[0] !== "/" && !(path51.startsWith("http://") || path51.startsWith("https://")) && method !== "CONNECT") {
37357
+ } else if (path52[0] !== "/" && !(path52.startsWith("http://") || path52.startsWith("https://")) && method !== "CONNECT") {
37341
37358
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
37342
- } else if (invalidPathRegex.test(path51)) {
37359
+ } else if (invalidPathRegex.test(path52)) {
37343
37360
  throw new InvalidArgumentError2("invalid request path");
37344
37361
  }
37345
37362
  if (typeof method !== "string") {
@@ -37414,7 +37431,7 @@ var require_request = __commonJS({
37414
37431
  this.completed = false;
37415
37432
  this.aborted = false;
37416
37433
  this.upgrade = upgrade || null;
37417
- this.path = query ? serializePathWithQuery(path51, query) : path51;
37434
+ this.path = query ? serializePathWithQuery(path52, query) : path52;
37418
37435
  this.origin = origin;
37419
37436
  this.protocol = getProtocolFromUrlString(origin);
37420
37437
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -42596,7 +42613,7 @@ var require_client_h1 = __commonJS({
42596
42613
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
42597
42614
  }
42598
42615
  function writeH1(client, request7) {
42599
- const { method, path: path51, host, upgrade, blocking, reset } = request7;
42616
+ const { method, path: path52, host, upgrade, blocking, reset } = request7;
42600
42617
  let { body, headers, contentLength } = request7;
42601
42618
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
42602
42619
  if (util2.isFormDataLike(body)) {
@@ -42674,7 +42691,7 @@ var require_client_h1 = __commonJS({
42674
42691
  if (socket.setTypeOfService) {
42675
42692
  socket.setTypeOfService(request7.typeOfService);
42676
42693
  }
42677
- let header = `${method} ${path51} HTTP/1.1\r
42694
+ let header = `${method} ${path52} HTTP/1.1\r
42678
42695
  `;
42679
42696
  if (typeof host === "string") {
42680
42697
  header += `host: ${host}\r
@@ -43353,7 +43370,7 @@ var require_client_h2 = __commonJS({
43353
43370
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
43354
43371
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
43355
43372
  const session = client[kHTTP2Session];
43356
- const { method, path: path51, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43373
+ const { method, path: path52, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43357
43374
  let { body } = request7;
43358
43375
  if (upgrade != null && upgrade !== "websocket") {
43359
43376
  util2.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -43422,7 +43439,7 @@ var require_client_h2 = __commonJS({
43422
43439
  }
43423
43440
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
43424
43441
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
43425
- headers[HTTP2_HEADER_PATH] = path51;
43442
+ headers[HTTP2_HEADER_PATH] = path52;
43426
43443
  if (protocol === "ws:" || protocol === "wss:") {
43427
43444
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
43428
43445
  } else {
@@ -43464,7 +43481,7 @@ var require_client_h2 = __commonJS({
43464
43481
  stream.setTimeout(headersTimeout);
43465
43482
  return true;
43466
43483
  }
43467
- headers[HTTP2_HEADER_PATH] = path51;
43484
+ headers[HTTP2_HEADER_PATH] = path52;
43468
43485
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
43469
43486
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
43470
43487
  if (body && typeof body.read === "function") {
@@ -45816,10 +45833,10 @@ var require_proxy_agent = __commonJS({
45816
45833
  };
45817
45834
  const {
45818
45835
  origin,
45819
- path: path51 = "/",
45836
+ path: path52 = "/",
45820
45837
  headers = {}
45821
45838
  } = opts;
45822
- opts.path = origin + path51;
45839
+ opts.path = origin + path52;
45823
45840
  if (!("host" in headers) && !("Host" in headers)) {
45824
45841
  const { host } = new URL(origin);
45825
45842
  headers.host = host;
@@ -47928,20 +47945,20 @@ var require_mock_utils = __commonJS({
47928
47945
  }
47929
47946
  return normalizedQp;
47930
47947
  }
47931
- function safeUrl(path51) {
47932
- if (typeof path51 !== "string") {
47933
- return path51;
47948
+ function safeUrl(path52) {
47949
+ if (typeof path52 !== "string") {
47950
+ return path52;
47934
47951
  }
47935
- const pathSegments = path51.split("?", 3);
47952
+ const pathSegments = path52.split("?", 3);
47936
47953
  if (pathSegments.length !== 2) {
47937
- return path51;
47954
+ return path52;
47938
47955
  }
47939
47956
  const qp2 = new URLSearchParams(pathSegments.pop());
47940
47957
  qp2.sort();
47941
47958
  return [...pathSegments, qp2.toString()].join("?");
47942
47959
  }
47943
- function matchKey(mockDispatch2, { path: path51, method, body, headers }) {
47944
- const pathMatch = matchValue(mockDispatch2.path, path51);
47960
+ function matchKey(mockDispatch2, { path: path52, method, body, headers }) {
47961
+ const pathMatch = matchValue(mockDispatch2.path, path52);
47945
47962
  const methodMatch = matchValue(mockDispatch2.method, method);
47946
47963
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
47947
47964
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -47966,8 +47983,8 @@ var require_mock_utils = __commonJS({
47966
47983
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
47967
47984
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
47968
47985
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
47969
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path51, ignoreTrailingSlash }) => {
47970
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path51)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path51), resolvedPath);
47986
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path52, ignoreTrailingSlash }) => {
47987
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path52)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path52), resolvedPath);
47971
47988
  });
47972
47989
  if (matchedMockDispatches.length === 0) {
47973
47990
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -48006,19 +48023,19 @@ var require_mock_utils = __commonJS({
48006
48023
  mockDispatches.splice(index, 1);
48007
48024
  }
48008
48025
  }
48009
- function removeTrailingSlash(path51) {
48010
- while (path51.endsWith("/")) {
48011
- path51 = path51.slice(0, -1);
48026
+ function removeTrailingSlash(path52) {
48027
+ while (path52.endsWith("/")) {
48028
+ path52 = path52.slice(0, -1);
48012
48029
  }
48013
- if (path51.length === 0) {
48014
- path51 = "/";
48030
+ if (path52.length === 0) {
48031
+ path52 = "/";
48015
48032
  }
48016
- return path51;
48033
+ return path52;
48017
48034
  }
48018
48035
  function buildKey(opts) {
48019
- const { path: path51, method, body, headers, query } = opts;
48036
+ const { path: path52, method, body, headers, query } = opts;
48020
48037
  return {
48021
- path: path51,
48038
+ path: path52,
48022
48039
  method,
48023
48040
  body,
48024
48041
  headers,
@@ -48708,10 +48725,10 @@ var require_pending_interceptors_formatter = __commonJS({
48708
48725
  }
48709
48726
  format(pendingInterceptors) {
48710
48727
  const withPrettyHeaders = pendingInterceptors.map(
48711
- ({ method, path: path51, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48728
+ ({ method, path: path52, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48712
48729
  Method: method,
48713
48730
  Origin: origin,
48714
- Path: path51,
48731
+ Path: path52,
48715
48732
  "Status code": statusCode,
48716
48733
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
48717
48734
  Invocations: timesInvoked,
@@ -48793,9 +48810,9 @@ var require_mock_agent = __commonJS({
48793
48810
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
48794
48811
  const dispatchOpts = { ...opts };
48795
48812
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
48796
- const [path51, searchParams] = dispatchOpts.path.split("?");
48813
+ const [path52, searchParams] = dispatchOpts.path.split("?");
48797
48814
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
48798
- dispatchOpts.path = `${path51}?${normalizedSearchParams}`;
48815
+ dispatchOpts.path = `${path52}?${normalizedSearchParams}`;
48799
48816
  }
48800
48817
  return this[kAgent].dispatch(dispatchOpts, handler);
48801
48818
  }
@@ -49196,12 +49213,12 @@ var require_snapshot_recorder = __commonJS({
49196
49213
  * @return {Promise<void>} - Resolves when snapshots are loaded
49197
49214
  */
49198
49215
  async loadSnapshots(filePath) {
49199
- const path51 = filePath || this.#snapshotPath;
49200
- if (!path51) {
49216
+ const path52 = filePath || this.#snapshotPath;
49217
+ if (!path52) {
49201
49218
  throw new InvalidArgumentError2("Snapshot path is required");
49202
49219
  }
49203
49220
  try {
49204
- const data = await readFile(resolve2(path51), "utf8");
49221
+ const data = await readFile(resolve2(path52), "utf8");
49205
49222
  const parsed = JSON.parse(data);
49206
49223
  if (Array.isArray(parsed)) {
49207
49224
  this.#snapshots.clear();
@@ -49215,7 +49232,7 @@ var require_snapshot_recorder = __commonJS({
49215
49232
  if (error63.code === "ENOENT") {
49216
49233
  this.#snapshots.clear();
49217
49234
  } else {
49218
- throw new UndiciError(`Failed to load snapshots from ${path51}`, { cause: error63 });
49235
+ throw new UndiciError(`Failed to load snapshots from ${path52}`, { cause: error63 });
49219
49236
  }
49220
49237
  }
49221
49238
  }
@@ -49226,11 +49243,11 @@ var require_snapshot_recorder = __commonJS({
49226
49243
  * @returns {Promise<void>} - Resolves when snapshots are saved
49227
49244
  */
49228
49245
  async saveSnapshots(filePath) {
49229
- const path51 = filePath || this.#snapshotPath;
49230
- if (!path51) {
49246
+ const path52 = filePath || this.#snapshotPath;
49247
+ if (!path52) {
49231
49248
  throw new InvalidArgumentError2("Snapshot path is required");
49232
49249
  }
49233
- const resolvedPath = resolve2(path51);
49250
+ const resolvedPath = resolve2(path52);
49234
49251
  await mkdir(dirname3(resolvedPath), { recursive: true });
49235
49252
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
49236
49253
  hash: hash2,
@@ -49862,15 +49879,15 @@ var require_redirect_handler = __commonJS({
49862
49879
  return;
49863
49880
  }
49864
49881
  const { origin, pathname, search } = util2.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
49865
- const path51 = search ? `${pathname}${search}` : pathname;
49866
- const redirectUrlString = `${origin}${path51}`;
49882
+ const path52 = search ? `${pathname}${search}` : pathname;
49883
+ const redirectUrlString = `${origin}${path52}`;
49867
49884
  for (const historyUrl of this.history) {
49868
49885
  if (historyUrl.toString() === redirectUrlString) {
49869
49886
  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.`);
49870
49887
  }
49871
49888
  }
49872
49889
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
49873
- this.opts.path = path51;
49890
+ this.opts.path = path52;
49874
49891
  this.opts.origin = origin;
49875
49892
  this.opts.query = null;
49876
49893
  }
@@ -51630,10 +51647,10 @@ var require_cache_handler = __commonJS({
51630
51647
  }
51631
51648
  return locationUrl.pathname + locationUrl.search;
51632
51649
  }
51633
- function deleteCachedUri(store, cacheKey, path51) {
51650
+ function deleteCachedUri(store, cacheKey, path52) {
51634
51651
  deleteCachedValue(store, {
51635
51652
  ...cacheKey,
51636
- path: path51
51653
+ path: path52
51637
51654
  });
51638
51655
  for (let i10 = 0; i10 < util2.safeHTTPMethods.length; i10++) {
51639
51656
  const method = util2.safeHTTPMethods[i10];
@@ -51641,7 +51658,7 @@ var require_cache_handler = __commonJS({
51641
51658
  deleteCachedValue(store, {
51642
51659
  ...cacheKey,
51643
51660
  method,
51644
- path: path51
51661
+ path: path52
51645
51662
  });
51646
51663
  }
51647
51664
  }
@@ -51652,9 +51669,9 @@ var require_cache_handler = __commonJS({
51652
51669
  }
51653
51670
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
51654
51671
  for (let i10 = 0; i10 < values.length; i10++) {
51655
- const path51 = getSameOriginPath(cacheKey, values[i10]);
51656
- if (path51 !== void 0) {
51657
- deleteCachedUri(store, cacheKey, path51);
51672
+ const path52 = getSameOriginPath(cacheKey, values[i10]);
51673
+ if (path52 !== void 0) {
51674
+ deleteCachedUri(store, cacheKey, path52);
51658
51675
  }
51659
51676
  }
51660
51677
  }
@@ -56654,11 +56671,11 @@ var require_fetch = __commonJS({
56654
56671
  function dispatch({ body }) {
56655
56672
  const url2 = requestCurrentURL(request7);
56656
56673
  const agent = fetchParams.controller.dispatcher;
56657
- const path51 = url2.pathname + url2.search;
56674
+ const path52 = url2.pathname + url2.search;
56658
56675
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
56659
56676
  return new Promise((resolve2, reject) => agent.dispatch(
56660
56677
  {
56661
- path: hasTrailingQuestionMark ? `${path51}?` : path51,
56678
+ path: hasTrailingQuestionMark ? `${path52}?` : path52,
56662
56679
  origin: url2.origin,
56663
56680
  method: request7.method,
56664
56681
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -57605,9 +57622,9 @@ var require_util5 = __commonJS({
57605
57622
  }
57606
57623
  }
57607
57624
  }
57608
- function validateCookiePath(path51) {
57609
- for (let i10 = 0; i10 < path51.length; ++i10) {
57610
- const code = path51.charCodeAt(i10);
57625
+ function validateCookiePath(path52) {
57626
+ for (let i10 = 0; i10 < path52.length; ++i10) {
57627
+ const code = path52.charCodeAt(i10);
57611
57628
  if (code < 32 || // exclude CTLs (0-31)
57612
57629
  code > 126 || // exclude DEL and non-ascii
57613
57630
  code === 59) {
@@ -60955,11 +60972,11 @@ var require_undici = __commonJS({
60955
60972
  if (typeof opts.path !== "string") {
60956
60973
  throw new InvalidArgumentError2("invalid opts.path");
60957
60974
  }
60958
- let path51 = opts.path;
60975
+ let path52 = opts.path;
60959
60976
  if (!opts.path.startsWith("/")) {
60960
- path51 = `/${path51}`;
60977
+ path52 = `/${path52}`;
60961
60978
  }
60962
- url2 = new URL(util2.parseOrigin(url2).origin + path51);
60979
+ url2 = new URL(util2.parseOrigin(url2).origin + path52);
60963
60980
  } else {
60964
60981
  if (!opts) {
60965
60982
  opts = typeof url2 === "object" ? url2 : {};
@@ -62874,6 +62891,57 @@ var init_launchWiring = __esm({
62874
62891
  }
62875
62892
  });
62876
62893
 
62894
+ // src/usage/identityClaude.ts
62895
+ function definedEnvironment(env) {
62896
+ return Object.fromEntries(Object.entries(env).flatMap(([name, value2]) => value2 === void 0 ? [] : [[name, value2]]));
62897
+ }
62898
+ function identityLaunchArgv(identity, flags) {
62899
+ return [`@${identity}`, IDENTITY_ONLY_FLAG, ...flags];
62900
+ }
62901
+ async function withIdentityClaude(params, identity, flags, use2) {
62902
+ const refusals = [];
62903
+ const plan = prepareLaunch(
62904
+ realPrepareLaunchParams(params.paths, {
62905
+ proc: {
62906
+ env: Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== CONFIG_DIR_VARIABLE)),
62907
+ argv: [...identityLaunchArgv(identity, flags)],
62908
+ exit: (code) => {
62909
+ throw new LaunchRefusedError(refusals.join("\n") || `the launch was refused (exit ${String(code)})`, code);
62910
+ }
62911
+ },
62912
+ log: {
62913
+ info: () => void 0,
62914
+ warn: () => void 0,
62915
+ error: (message) => {
62916
+ refusals.push(message);
62917
+ }
62918
+ },
62919
+ spawnDaemon: params.spawnDaemon,
62920
+ farm: buildFarmRuntime(params.paths, params.cwd)
62921
+ })
62922
+ );
62923
+ const abort = new AbortController();
62924
+ const timer = setTimeout(() => {
62925
+ abort.abort();
62926
+ }, params.timeoutMs);
62927
+ try {
62928
+ return await use2({ bin: plan.bin, env: definedEnvironment(plan.env), cwd: params.cwd, abort });
62929
+ } finally {
62930
+ clearTimeout(timer);
62931
+ plan.release();
62932
+ }
62933
+ }
62934
+ var CONFIG_DIR_VARIABLE, IDENTITY_ONLY_FLAG;
62935
+ var init_identityClaude = __esm({
62936
+ "src/usage/identityClaude.ts"() {
62937
+ "use strict";
62938
+ init_launchWiring();
62939
+ init_launcher();
62940
+ CONFIG_DIR_VARIABLE = "CLAUDE_CONFIG_DIR";
62941
+ IDENTITY_ONLY_FLAG = "--no-provider";
62942
+ }
62943
+ });
62944
+
62877
62945
  // src/usage/providerQuota.ts
62878
62946
  function zaiWindow(limit) {
62879
62947
  const unitMs = ZAI_UNIT_MS.get(limit.unit);
@@ -62908,7 +62976,7 @@ async function openRouterGet(url2, schema, apiKey, http8, signal) {
62908
62976
  return parsed.data;
62909
62977
  }
62910
62978
  function nextUtcMidnight(nowMs) {
62911
- return new Date((Math.floor(nowMs / MS_PER_DAY) + 1) * MS_PER_DAY).toISOString();
62979
+ return new Date((Math.floor(nowMs / MS_PER_DAY2) + 1) * MS_PER_DAY2).toISOString();
62912
62980
  }
62913
62981
  function adapterFor(baseUrl) {
62914
62982
  return PROVIDER_QUOTA_ADAPTERS.find((adapter) => adapter.matches(baseUrl));
@@ -62917,7 +62985,7 @@ function quotaFreshnessMs(quota) {
62917
62985
  const lengths = quota.windows.flatMap((window) => window.periodMs === void 0 ? [] : [window.periodMs]);
62918
62986
  return lengths.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...lengths) / PERCENT3;
62919
62987
  }
62920
- var ProviderQuotaError, MS_PER_SECOND5, SECONDS_PER_HOUR, HOURS_PER_DAY3, DAYS_PER_MONTH, PERCENT3, HTTP_OK, ZAI_SOURCE, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZAI_MEASURES, ZaiLimitSchema, ZaiResponseSchema, zaiQuotaAdapter, OPENROUTER_SOURCE, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, HTTP_FORBIDDEN, MS_PER_DAY, OpenRouterKeySchema, OpenRouterCreditsSchema, openRouterQuotaAdapter, PROVIDER_QUOTA_ADAPTERS;
62988
+ var ProviderQuotaError, MS_PER_SECOND6, SECONDS_PER_HOUR, HOURS_PER_DAY3, DAYS_PER_MONTH, PERCENT3, HTTP_OK, ZAI_SOURCE, ZAI_HOST, ZAI_QUOTA_URL, ZAI_UNIT_HOURS, ZAI_UNIT_MONTHS, ZAI_UNIT_MS, ZAI_MEASURES, ZaiLimitSchema, ZaiResponseSchema, zaiQuotaAdapter, OPENROUTER_SOURCE, OPENROUTER_HOST, OPENROUTER_KEY_URL, OPENROUTER_CREDITS_URL, HTTP_FORBIDDEN, MS_PER_DAY2, OpenRouterKeySchema, OpenRouterCreditsSchema, openRouterQuotaAdapter, PROVIDER_QUOTA_ADAPTERS;
62921
62989
  var init_providerQuota = __esm({
62922
62990
  "src/usage/providerQuota.ts"() {
62923
62991
  "use strict";
@@ -62929,7 +62997,7 @@ var init_providerQuota = __esm({
62929
62997
  this.name = "ProviderQuotaError";
62930
62998
  }
62931
62999
  };
62932
- MS_PER_SECOND5 = 1e3;
63000
+ MS_PER_SECOND6 = 1e3;
62933
63001
  SECONDS_PER_HOUR = 3600;
62934
63002
  HOURS_PER_DAY3 = 24;
62935
63003
  DAYS_PER_MONTH = 30;
@@ -62941,8 +63009,8 @@ var init_providerQuota = __esm({
62941
63009
  ZAI_UNIT_HOURS = 3;
62942
63010
  ZAI_UNIT_MONTHS = 5;
62943
63011
  ZAI_UNIT_MS = /* @__PURE__ */ new Map([
62944
- [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND5],
62945
- [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND5]
63012
+ [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND6],
63013
+ [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND6]
62946
63014
  ]);
62947
63015
  ZAI_MEASURES = { TOKENS_LIMIT: "tokens", TIME_LIMIT: "tool-calls" };
62948
63016
  ZaiLimitSchema = external_exports.object({
@@ -62994,7 +63062,7 @@ var init_providerQuota = __esm({
62994
63062
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
62995
63063
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
62996
63064
  HTTP_FORBIDDEN = 403;
62997
- MS_PER_DAY = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND5;
63065
+ MS_PER_DAY2 = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND6;
62998
63066
  OpenRouterKeySchema = external_exports.object({
62999
63067
  data: external_exports.object({
63000
63068
  limit: external_exports.number().nonnegative().nullable(),
@@ -63025,7 +63093,7 @@ var init_providerQuota = __esm({
63025
63093
  windows.push({ measures: "account-credits", period: "prepaid", utilization: used / total, limit: total, used, remaining: Math.max(total - used, 0) });
63026
63094
  }
63027
63095
  if (free !== void 0 && free.limit > 0) {
63028
- windows.push({ measures: "free-model-requests", periodMs: MS_PER_DAY, utilization: free.used / free.limit, resetsAt: nextUtcMidnight(nowMs), limit: free.limit, used: free.used, remaining: Math.max(free.remaining, 0) });
63096
+ windows.push({ measures: "free-model-requests", periodMs: MS_PER_DAY2, utilization: free.used / free.limit, resetsAt: nextUtcMidnight(nowMs), limit: free.limit, used: free.used, remaining: Math.max(free.remaining, 0) });
63029
63097
  }
63030
63098
  return ProviderQuotaSchema.parse({
63031
63099
  observedAt: new Date(nowMs).toISOString(),
@@ -96617,9 +96685,6 @@ var realAnthropicUsageProbe_exports = {};
96617
96685
  __export(realAnthropicUsageProbe_exports, {
96618
96686
  createRealAnthropicUsageRefresher: () => createRealAnthropicUsageRefresher
96619
96687
  });
96620
- function definedEnvironment(env) {
96621
- return Object.fromEntries(Object.entries(env).flatMap(([name, value2]) => value2 === void 0 ? [] : [[name, value2]]));
96622
- }
96623
96688
  function idlePrompt(signal) {
96624
96689
  return {
96625
96690
  [Symbol.asyncIterator]: () => ({
@@ -96632,58 +96697,28 @@ function idlePrompt(signal) {
96632
96697
  };
96633
96698
  }
96634
96699
  function createRealAnthropicUsageProbe(params) {
96635
- return async (identity) => {
96636
- const refusals = [];
96637
- const plan = prepareLaunch(
96638
- realPrepareLaunchParams(params.paths, {
96639
- proc: {
96640
- env: Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== CONFIG_DIR_VARIABLE)),
96641
- argv: [`@${identity}`, ...PROBE_LAUNCH_FLAGS],
96642
- exit: (code) => {
96643
- throw new LaunchRefusedError(refusals.join("\n") || `the launch was refused (exit ${String(code)})`, code);
96644
- }
96645
- },
96646
- log: {
96647
- info: () => void 0,
96648
- warn: () => void 0,
96649
- error: (message) => {
96650
- refusals.push(message);
96651
- }
96652
- },
96653
- spawnDaemon: params.spawnDaemon,
96654
- farm: buildFarmRuntime(params.paths, params.cwd)
96655
- })
96656
- );
96700
+ return async (identity) => await withIdentityClaude(params, identity, PROBE_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
96657
96701
  const { query } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
96658
- const abort = new AbortController();
96659
- const timer = setTimeout(() => {
96660
- abort.abort();
96661
- }, params.timeoutMs);
96662
- try {
96663
- const session = query({
96664
- prompt: idlePrompt(abort.signal),
96665
- options: {
96666
- pathToClaudeCodeExecutable: plan.bin,
96667
- env: definedEnvironment(plan.env),
96668
- cwd: params.cwd,
96669
- abortController: abort,
96670
- settingSources: [],
96671
- mcpServers: {},
96672
- strictMcpConfig: true,
96673
- persistSession: false
96674
- }
96675
- });
96676
- try {
96677
- const report = await session.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
96678
- return unifiedFromReportedLimits(report.rate_limits_available ? report.rate_limits : null);
96679
- } finally {
96680
- session.close();
96702
+ const session = query({
96703
+ prompt: idlePrompt(abort.signal),
96704
+ options: {
96705
+ pathToClaudeCodeExecutable: bin,
96706
+ env,
96707
+ cwd,
96708
+ abortController: abort,
96709
+ settingSources: [],
96710
+ mcpServers: {},
96711
+ strictMcpConfig: true,
96712
+ persistSession: false
96681
96713
  }
96714
+ });
96715
+ try {
96716
+ const report = await session.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
96717
+ return unifiedFromReportedLimits(report.rate_limits_available ? report.rate_limits : null);
96682
96718
  } finally {
96683
- clearTimeout(timer);
96684
- plan.release();
96719
+ session.close();
96685
96720
  }
96686
- };
96721
+ });
96687
96722
  }
96688
96723
  function createRealAnthropicUsageRefresher(params) {
96689
96724
  return createAnthropicUsageRefresher({
@@ -96696,18 +96731,16 @@ function createRealAnthropicUsageRefresher(params) {
96696
96731
  concurrency: (0, import_node_os11.availableParallelism)()
96697
96732
  });
96698
96733
  }
96699
- var import_node_os11, PROBE_LAUNCH_FLAGS, CONFIG_DIR_VARIABLE;
96734
+ var import_node_os11, PROBE_LAUNCH_FLAGS;
96700
96735
  var init_realAnthropicUsageProbe = __esm({
96701
96736
  "src/usage/realAnthropicUsageProbe.ts"() {
96702
96737
  "use strict";
96703
96738
  import_node_os11 = require("node:os");
96704
- init_launchWiring();
96705
- init_launcher();
96706
96739
  init_anthropicUsageRefresh();
96740
+ init_identityClaude();
96707
96741
  init_middleware();
96708
96742
  init_quotaRefresh();
96709
96743
  PROBE_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control"];
96710
- CONFIG_DIR_VARIABLE = "CLAUDE_CONFIG_DIR";
96711
96744
  }
96712
96745
  });
96713
96746
 
@@ -99940,8 +99973,8 @@ var require_utils3 = __commonJS({
99940
99973
  }
99941
99974
  return ind;
99942
99975
  }
99943
- function removeDotSegments(path51) {
99944
- let input2 = path51;
99976
+ function removeDotSegments(path52) {
99977
+ let input2 = path52;
99945
99978
  const output2 = [];
99946
99979
  let nextSlash = -1;
99947
99980
  let len = 0;
@@ -100350,8 +100383,8 @@ var require_schemes = __commonJS({
100350
100383
  }
100351
100384
  if (wsComponent.resourceName) {
100352
100385
  const queryIndex = wsComponent.resourceName.indexOf("?");
100353
- const path51 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
100354
- wsComponent.path = path51 && path51 !== "/" ? path51 : void 0;
100386
+ const path52 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
100387
+ wsComponent.path = path52 && path52 !== "/" ? path52 : void 0;
100355
100388
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
100356
100389
  wsComponent.resourceName = void 0;
100357
100390
  }
@@ -103878,7 +103911,7 @@ var require_dist2 = __commonJS({
103878
103911
  });
103879
103912
 
103880
103913
  // src/cli.ts
103881
- var import_node_path50 = __toESM(require("node:path"), 1);
103914
+ var import_node_path51 = __toESM(require("node:path"), 1);
103882
103915
 
103883
103916
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
103884
103917
  var CommanderError = class extends Error {
@@ -106991,9 +107024,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
106991
107024
  * @param {string} [path]
106992
107025
  * @return {(string|null|Command)}
106993
107026
  */
106994
- executableDir(path51) {
106995
- if (path51 === void 0) return this._executableDir;
106996
- this._executableDir = path51;
107027
+ executableDir(path52) {
107028
+ if (path52 === void 0) return this._executableDir;
107029
+ this._executableDir = path52;
106997
107030
  return this;
106998
107031
  }
106999
107032
  /**
@@ -108642,19 +108675,19 @@ function writePools(paths, pools) {
108642
108675
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
108643
108676
  }
108644
108677
  function poolCycleOf(pools, name) {
108645
- const walk = (current, path51) => {
108678
+ const walk = (current, path52) => {
108646
108679
  for (const entry of pools[current]?.identities ?? []) {
108647
108680
  const nested = poolNameOf(poolMemberIdentity(entry));
108648
108681
  if (nested === void 0) {
108649
108682
  continue;
108650
108683
  }
108651
108684
  if (nested === name) {
108652
- return [...path51, nested];
108685
+ return [...path52, nested];
108653
108686
  }
108654
- if (path51.includes(nested)) {
108687
+ if (path52.includes(nested)) {
108655
108688
  continue;
108656
108689
  }
108657
- const found = walk(nested, [...path51, nested]);
108690
+ const found = walk(nested, [...path52, nested]);
108658
108691
  if (found !== void 0) {
108659
108692
  return found;
108660
108693
  }
@@ -108805,6 +108838,18 @@ function listIdentities(paths) {
108805
108838
  }
108806
108839
  return result;
108807
108840
  }
108841
+ function listAnchoredIdentities(paths) {
108842
+ return listIdentities(paths).flatMap(({ name }) => {
108843
+ const anchors = readIdentity(paths, name)?.anchors;
108844
+ return anchors === void 0 ? [] : [{ identity: name, anchors }];
108845
+ });
108846
+ }
108847
+ function setIdentityAnchors(paths, identityName, anchors) {
108848
+ if (!identityExists(paths, identityName)) {
108849
+ throw new IdentityNotFoundError(identityName);
108850
+ }
108851
+ return applyPatch(identityJsonPath(paths, identityName), IdentitySchema, { anchors: anchors === void 0 ? void 0 : [...anchors] });
108852
+ }
108808
108853
  function setDefaultConfigProfile(paths, identityName, profileName) {
108809
108854
  if (!identityExists(paths, identityName)) {
108810
108855
  throw new IdentityNotFoundError(identityName);
@@ -109583,6 +109628,135 @@ function cacheChange(options, existing) {
109583
109628
  }
109584
109629
  }
109585
109630
 
109631
+ // src/usage/anchor.ts
109632
+ init_schema();
109633
+ var MS_PER_SECOND = 1e3;
109634
+ var MS_PER_MINUTE2 = 6e4;
109635
+ var MINUTES_PER_HOUR = 60;
109636
+ var DAYS_IN_WEEK = 7;
109637
+ var MS_PER_DAY = 864e5;
109638
+ var SEARCH_MARGIN_DAYS = 1;
109639
+ var WORKING_DAYS = 5;
109640
+ var WEEKDAY_SHORTHANDS = { daily: WEEKDAYS, weekdays: WEEKDAYS.slice(0, WORKING_DAYS) };
109641
+ function zoneOffsetMs(utcMs, timeZone) {
109642
+ const wholeSecondMs = Math.floor(utcMs / MS_PER_SECOND) * MS_PER_SECOND;
109643
+ const parts = new Intl.DateTimeFormat("en-GB", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" }).formatToParts(new Date(wholeSecondMs));
109644
+ const field = (type2) => Number(parts.find((part) => part.type === type2)?.value);
109645
+ return Date.UTC(field("year"), field("month") - 1, field("day"), field("hour"), field("minute"), field("second")) - wholeSecondMs;
109646
+ }
109647
+ function wallTimeToUtcMs(date5, minutesOfDay, timeZone) {
109648
+ const asUtc = Date.UTC(date5.year, date5.month - 1, date5.day) + minutesOfDay * MS_PER_MINUTE2;
109649
+ const candidates = [zoneOffsetMs(asUtc - MS_PER_DAY, timeZone), zoneOffsetMs(asUtc + MS_PER_DAY, timeZone)].map((offset) => ({ offset, instant: asUtc - offset }));
109650
+ const valid = candidates.filter(({ offset, instant }) => zoneOffsetMs(instant, timeZone) === offset).map(({ instant }) => instant);
109651
+ return valid.length === 0 ? asUtc - (candidates[0]?.offset ?? 0) : Math.min(...valid);
109652
+ }
109653
+ function localDate(utcMs, timeZone) {
109654
+ const local = new Date(utcMs + zoneOffsetMs(utcMs, timeZone));
109655
+ return { year: local.getUTCFullYear(), month: local.getUTCMonth() + 1, day: local.getUTCDate() };
109656
+ }
109657
+ function weekdayOf(date5) {
109658
+ const sundayFirst = new Date(Date.UTC(date5.year, date5.month - 1, date5.day)).getUTCDay();
109659
+ const day = WEEKDAYS[(sundayFirst + DAYS_IN_WEEK - 1) % DAYS_IN_WEEK];
109660
+ if (day === void 0) {
109661
+ throw new RangeError(`no weekday for day number ${String(sundayFirst)}`);
109662
+ }
109663
+ return day;
109664
+ }
109665
+ function minutesOfDayOf(time4) {
109666
+ const [hours, minutes] = time4.split(":").map(Number);
109667
+ return (hours ?? 0) * MINUTES_PER_HOUR + (minutes ?? 0);
109668
+ }
109669
+ function anchorInstants(anchors, afterMs, uptoMs, defaultTimeZone) {
109670
+ const instants = anchors.flatMap((anchor2) => {
109671
+ const timeZone = anchor2.timeZone ?? defaultTimeZone;
109672
+ const minutesOfDay = minutesOfDayOf(anchor2.time);
109673
+ const first = localDate(afterMs - SEARCH_MARGIN_DAYS * MS_PER_DAY, timeZone);
109674
+ const found = [];
109675
+ for (let offset = 0; ; offset += 1) {
109676
+ const date5 = localDate(Date.UTC(first.year, first.month - 1, first.day + offset) + MS_PER_DAY / 2, "UTC");
109677
+ const instant = wallTimeToUtcMs(date5, minutesOfDay, timeZone);
109678
+ if (instant > uptoMs + SEARCH_MARGIN_DAYS * MS_PER_DAY) {
109679
+ return found;
109680
+ }
109681
+ if (instant > afterMs && instant <= uptoMs && anchor2.days.includes(weekdayOf(date5))) {
109682
+ found.push(instant);
109683
+ }
109684
+ }
109685
+ });
109686
+ return instants.sort((left, right) => left - right);
109687
+ }
109688
+ function dueAnchor(anchors, nowMs, handledMs, defaultTimeZone) {
109689
+ const since = Math.max(handledMs, nowMs - DAYS_IN_WEEK * MS_PER_DAY);
109690
+ return anchorInstants(anchors, since, nowMs, defaultTimeZone).at(-1);
109691
+ }
109692
+ function parseDayItem(item) {
109693
+ const [from, to2, ...extra] = item.split("-");
109694
+ const index = (name) => WEEKDAYS.findIndex((day) => day === name);
109695
+ if (from === void 0 || extra.length > 0 || index(from) === -1 || to2 !== void 0 && index(to2) === -1) {
109696
+ throw new Error(`"${item}" is not a weekday (${WEEKDAYS.join(", ")}) or a range such as mon-fri`);
109697
+ }
109698
+ if (to2 === void 0) {
109699
+ return [WEEKDAYS[index(from)] ?? "mon"];
109700
+ }
109701
+ const length = (index(to2) - index(from) + DAYS_IN_WEEK) % DAYS_IN_WEEK + 1;
109702
+ return Array.from({ length }, (_, step2) => WEEKDAYS[(index(from) + step2) % DAYS_IN_WEEK] ?? "mon");
109703
+ }
109704
+ function parseAnchor(spec) {
109705
+ const match = /^(?<days>[^@]+)@(?<time>[^/]+)(?:\/(?<zone>.+))?$/.exec(spec);
109706
+ const { days, time: time4, zone } = match?.groups ?? {};
109707
+ if (days === void 0 || time4 === void 0) {
109708
+ throw new Error(`"${spec}" is not an anchor: write <days>@<HH:MM>[/<time zone>], such as mon-fri@06:00 or sat,sun@08:30/Europe/London`);
109709
+ }
109710
+ const named = WEEKDAY_SHORTHANDS[days] ?? days.split(",").flatMap(parseDayItem);
109711
+ const parsed = AnchorSchema.safeParse({ days: [...new Set(named)], time: time4, ...zone === void 0 ? {} : { timeZone: zone } });
109712
+ if (!parsed.success) {
109713
+ throw new Error(`"${spec}" is not an anchor: ${parsed.error.issues.map((issue2) => issue2.message).join("; ")}`);
109714
+ }
109715
+ return parsed.data;
109716
+ }
109717
+ var ANCHOR_SYNTAX = "<days>@<HH:MM>[/<time zone>], where days are daily, weekdays, or weekday names and ranges such as mon,wed or mon-fri, and the zone defaults to the machine's own";
109718
+ function formatAnchor(anchor2) {
109719
+ return `${anchor2.days.join(",")}@${anchor2.time}${anchor2.timeZone === void 0 ? "" : `/${anchor2.timeZone}`}`;
109720
+ }
109721
+ function machineTimeZone() {
109722
+ return new Intl.DateTimeFormat().resolvedOptions().timeZone;
109723
+ }
109724
+
109725
+ // src/cli/parsers.ts
109726
+ init_conditions();
109727
+ init_pairs();
109728
+ function asInvalidArgument(parse4) {
109729
+ try {
109730
+ return parse4();
109731
+ } catch (error63) {
109732
+ if (error63 instanceof Error && !(error63 instanceof InvalidArgumentError)) {
109733
+ throw new InvalidArgumentError(error63.message);
109734
+ }
109735
+ throw error63;
109736
+ }
109737
+ }
109738
+ function collectBoolPair(value2, previous = {}) {
109739
+ return asInvalidArgument(() => {
109740
+ const { key, value: raw } = parsePair(value2);
109741
+ return { ...previous, [key]: parseBool(raw) };
109742
+ });
109743
+ }
109744
+ function collectStringPair(value2, previous = {}) {
109745
+ return asInvalidArgument(() => {
109746
+ const { key, value: raw } = parsePair(value2);
109747
+ return { ...previous, [key]: raw };
109748
+ });
109749
+ }
109750
+ function collectRepeated(value2, previous = []) {
109751
+ return [...previous, value2];
109752
+ }
109753
+ function collectAnchor(value2, previous = []) {
109754
+ return [...previous, asInvalidArgument(() => parseAnchor(value2))];
109755
+ }
109756
+ function parseDurationOption(value2) {
109757
+ return asInvalidArgument(() => parseDuration(value2));
109758
+ }
109759
+
109586
109760
  // src/identityManager.ts
109587
109761
  init_classify();
109588
109762
  init_schema();
@@ -109636,40 +109810,6 @@ async function resolveFarmConflicts(params) {
109636
109810
 
109637
109811
  // src/configProfiles.ts
109638
109812
  init_commandDeps();
109639
-
109640
- // src/cli/parsers.ts
109641
- init_conditions();
109642
- init_pairs();
109643
- function asInvalidArgument(parse4) {
109644
- try {
109645
- return parse4();
109646
- } catch (error63) {
109647
- if (error63 instanceof Error && !(error63 instanceof InvalidArgumentError)) {
109648
- throw new InvalidArgumentError(error63.message);
109649
- }
109650
- throw error63;
109651
- }
109652
- }
109653
- function collectBoolPair(value2, previous = {}) {
109654
- return asInvalidArgument(() => {
109655
- const { key, value: raw } = parsePair(value2);
109656
- return { ...previous, [key]: parseBool(raw) };
109657
- });
109658
- }
109659
- function collectStringPair(value2, previous = {}) {
109660
- return asInvalidArgument(() => {
109661
- const { key, value: raw } = parsePair(value2);
109662
- return { ...previous, [key]: raw };
109663
- });
109664
- }
109665
- function collectRepeated(value2, previous = []) {
109666
- return [...previous, value2];
109667
- }
109668
- function parseDurationOption(value2) {
109669
- return asInvalidArgument(() => parseDuration(value2));
109670
- }
109671
-
109672
- // src/configProfiles.ts
109673
109813
  init_cliError();
109674
109814
  async function ensureProfileExists(deps, name) {
109675
109815
  if (profileExists(deps.paths, name)) {
@@ -109899,7 +110039,8 @@ function toIdentityView(paths, entry) {
109899
110039
  ...entry.problem === void 0 ? {
109900
110040
  ...entry.identity.defaultConfigProfile === void 0 ? {} : { defaultConfigProfile: entry.identity.defaultConfigProfile },
109901
110041
  allowAmbientCredential: entry.identity.allowAmbientCredential,
109902
- ...entry.identity.credential === void 0 ? {} : { credential: summariseCredential(entry.identity.credential) }
110042
+ ...entry.identity.credential === void 0 ? {} : { credential: summariseCredential(entry.identity.credential) },
110043
+ ...entry.identity.anchors === void 0 ? {} : { anchors: entry.identity.anchors }
109903
110044
  } : { problem: entry.problem }
109904
110045
  };
109905
110046
  }
@@ -109968,6 +110109,7 @@ function registerIdentityCommand(program2, deps) {
109968
110109
  console.log(`Default configuration profile: ${view.defaultConfigProfile ?? "(none)"}`);
109969
110110
  console.log(`Allows ambient credential: ${view.allowAmbientCredential === true ? "yes" : "no"}`);
109970
110111
  console.log(`Credential: ${entry.identity?.credential === void 0 ? "(none; uses its stored login)" : describeCredential(entry.identity.credential)}`);
110112
+ console.log(`Anchors: ${view.anchors === void 0 ? "(none)" : view.anchors.map(formatAnchor).join(" ")}`);
109971
110113
  }),
109972
110114
  ["agent-shim identity show work", "agent-shim identity show work --json"]
109973
110115
  );
@@ -109975,7 +110117,11 @@ function registerIdentityCommand(program2, deps) {
109975
110117
  "--credential <source>",
109976
110118
  `Authenticate this identity from a token instead of its stored login, replacing any existing sources (repeatable, in the order tried): ${CREDENTIAL_SOURCE_SYNTAX}.`,
109977
110119
  collectCredentialSource
109978
- ).option("--no-credential", "Remove this identity's credential, returning it to its stored login.").addOption(
110120
+ ).option("--no-credential", "Remove this identity's credential, returning it to its stored login.").option(
110121
+ "--anchor <spec>",
110122
+ `Have the front door open a five-hour window for this identity at these times when none is open, so its window resets when you want (repeatable, replacing any existing anchors): ${ANCHOR_SYNTAX}.`,
110123
+ collectAnchor
110124
+ ).option("--no-anchor", "Remove this identity's anchors.").addOption(
109979
110125
  new Option(
109980
110126
  "--credential-target <target>",
109981
110127
  "Where the token goes: oauthToken sets CLAUDE_CODE_OAUTH_TOKEN (a `claude setup-token` token), bearer sets ANTHROPIC_AUTH_TOKEN (the default), apiKey sets ANTHROPIC_API_KEY."
@@ -109987,7 +110133,7 @@ function registerIdentityCommand(program2, deps) {
109987
110133
  const { json: json2, ...options } = allOptions;
109988
110134
  if (Object.entries(allOptions).every(([key, value2]) => key === "json" || value2 === void 0)) {
109989
110135
  throw new UsageError(
109990
- "Nothing to change: pass --default-profile, --no-default-profile, --allow-ambient-credential, --no-allow-ambient-credential, --credential, --no-credential, --credential-target or a --credential-cache option."
110136
+ "Nothing to change: pass --default-profile, --no-default-profile, --allow-ambient-credential, --no-allow-ambient-credential, --credential, --no-credential, --credential-target, --anchor, --no-anchor or a --credential-cache option."
109991
110137
  );
109992
110138
  }
109993
110139
  if (!identityExists(paths, name)) {
@@ -110022,6 +110168,10 @@ function registerIdentityCommand(program2, deps) {
110022
110168
  messages.push(`Identity "${name}" now authenticates with credential ${describeCredential(updated.credential)}.`);
110023
110169
  }
110024
110170
  }
110171
+ if (options.anchor !== void 0) {
110172
+ const updated = setIdentityAnchors(paths, name, options.anchor === false ? void 0 : options.anchor);
110173
+ messages.push(updated.anchors === void 0 ? `Identity "${name}" no longer has anchors.` : `Identity "${name}" now has anchors ${updated.anchors.map(formatAnchor).join(" ")}.`);
110174
+ }
110025
110175
  reportMutation(json2, { action: "updated", kind: "identity", name, value: readIdentity(paths, name) }, () => {
110026
110176
  for (const message of messages) {
110027
110177
  console.log(message);
@@ -110032,7 +110182,9 @@ function registerIdentityCommand(program2, deps) {
110032
110182
  "agent-shim identity set work --default-profile client-acme",
110033
110183
  "agent-shim identity set work --allow-ambient-credential",
110034
110184
  "agent-shim identity set work --credential-target oauthToken --credential op:op://vault/claude-work/token",
110035
- "agent-shim identity set work --no-credential"
110185
+ "agent-shim identity set work --no-credential",
110186
+ "agent-shim identity set work --anchor mon-fri@06:00",
110187
+ "agent-shim identity set work --no-anchor"
110036
110188
  ]
110037
110189
  );
110038
110190
  withExamples(
@@ -110782,7 +110934,7 @@ var SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
110782
110934
  var SIWC_CALLBACK_PORT = 1455;
110783
110935
  var SIWC_CALLBACK_PATH = "/auth/callback";
110784
110936
  var SIWC_RANDOM_BYTES = 32;
110785
- var MS_PER_SECOND4 = 1e3;
110937
+ var MS_PER_SECOND5 = 1e3;
110786
110938
  var ID_TOKEN_ALGORITHM = "RS256";
110787
110939
  var SiwcError = class extends Error {
110788
110940
  constructor(message) {
@@ -110878,7 +111030,7 @@ function grantTokens(ports, answer) {
110878
111030
  refreshToken: answer.refresh_token,
110879
111031
  idToken: answer.id_token,
110880
111032
  scopes: answer.scope === void 0 ? void 0 : answer.scope.split(" ").filter((part) => part !== ""),
110881
- expiresAt: ports.now().getTime() + answer.expires_in * MS_PER_SECOND4
111033
+ expiresAt: ports.now().getTime() + answer.expires_in * MS_PER_SECOND5
110882
111034
  };
110883
111035
  }
110884
111036
  async function exchangeCode(ports, request7) {
@@ -110939,7 +111091,7 @@ async function verifyIdToken(ports, idToken, expected) {
110939
111091
  if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expected.clientId)) {
110940
111092
  throw new SiwcError("the ID token was issued for a different client");
110941
111093
  }
110942
- if (claims.exp * MS_PER_SECOND4 <= ports.now().getTime()) {
111094
+ if (claims.exp * MS_PER_SECOND5 <= ports.now().getTime()) {
110943
111095
  throw new SiwcError("the ID token has already expired");
110944
111096
  }
110945
111097
  if (expected.nonce !== void 0 && claims.nonce !== expected.nonce) {
@@ -111471,7 +111623,7 @@ function registerCodexCommand(program2, deps) {
111471
111623
 
111472
111624
  // src/frontdoor/commands.ts
111473
111625
  var import_node_crypto20 = require("node:crypto");
111474
- var import_node_path45 = __toESM(require("node:path"), 1);
111626
+ var import_node_path46 = __toESM(require("node:path"), 1);
111475
111627
  var import_node_fs16 = __toESM(require("node:fs"), 1);
111476
111628
  init_commandDeps();
111477
111629
  init_schema();
@@ -111686,6 +111838,140 @@ async function refreshStalePoolMembers(params) {
111686
111838
  init_anthropicUsageRefresh();
111687
111839
  init_poolPick();
111688
111840
  init_realAnthropicUsageProbe();
111841
+
111842
+ // src/usage/realWindowOpener.ts
111843
+ init_identityClaude();
111844
+ var OPENER_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
111845
+ var WINDOW_OPENING_MODEL = "haiku";
111846
+ var WINDOW_OPENING_PROMPT = "ok";
111847
+ var WINDOW_OPENING_SYSTEM_PROMPT = "Reply with one word.";
111848
+ var WINDOW_OPEN_TIMEOUT_MS = 6e4;
111849
+ function createRealWindowOpener(params) {
111850
+ return async (identity) => {
111851
+ await withIdentityClaude({ ...params, timeoutMs: WINDOW_OPEN_TIMEOUT_MS }, identity, OPENER_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
111852
+ const { query } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
111853
+ const session = query({
111854
+ prompt: WINDOW_OPENING_PROMPT,
111855
+ options: {
111856
+ pathToClaudeCodeExecutable: bin,
111857
+ env,
111858
+ cwd,
111859
+ abortController: abort,
111860
+ settingSources: [],
111861
+ mcpServers: {},
111862
+ strictMcpConfig: true,
111863
+ persistSession: false,
111864
+ model: WINDOW_OPENING_MODEL,
111865
+ maxTurns: 1,
111866
+ tools: [],
111867
+ systemPrompt: WINDOW_OPENING_SYSTEM_PROMPT,
111868
+ thinking: { type: "disabled" }
111869
+ }
111870
+ });
111871
+ try {
111872
+ for await (const message of session) {
111873
+ if (message.type === "result") {
111874
+ if (message.subtype !== "success") {
111875
+ throw new Error(`the opening request ended as ${message.subtype}`);
111876
+ }
111877
+ return;
111878
+ }
111879
+ }
111880
+ throw new Error("the opening request ended without a result");
111881
+ } finally {
111882
+ session.close();
111883
+ }
111884
+ });
111885
+ };
111886
+ }
111887
+
111888
+ // src/usage/windowKeeper.ts
111889
+ var import_node_path38 = __toESM(require("node:path"), 1);
111890
+ init_zod();
111891
+ init_preflight();
111892
+ init_pick();
111893
+ init_middleware();
111894
+ var STAMPS_SCHEMA_VERSION = 1;
111895
+ var StampsFileSchema = external_exports.strictObject({
111896
+ schemaVersion: external_exports.literal(STAMPS_SCHEMA_VERSION),
111897
+ handled: external_exports.record(external_exports.string().min(1), external_exports.iso.datetime())
111898
+ });
111899
+ function readStamps(fs22, file2) {
111900
+ const raw = fs22.readFileUtf8(file2);
111901
+ if (raw === void 0) {
111902
+ return {};
111903
+ }
111904
+ let parsed;
111905
+ try {
111906
+ parsed = JSON.parse(raw);
111907
+ } catch {
111908
+ parsed = void 0;
111909
+ }
111910
+ const result = StampsFileSchema.safeParse(parsed);
111911
+ return result.success ? Object.fromEntries(Object.entries(result.data.handled).map(([identity, at2]) => [identity, Date.parse(at2)])) : {};
111912
+ }
111913
+ function writeStamps(fs22, file2, handled) {
111914
+ const next = { schemaVersion: STAMPS_SCHEMA_VERSION, handled: Object.fromEntries(Object.entries(handled).map(([identity, at2]) => [identity, new Date(at2).toISOString()])) };
111915
+ fs22.mkdirPrivate(import_node_path38.default.dirname(file2));
111916
+ fs22.writeFilePrivate(file2, `${JSON.stringify(next, null, 2)}
111917
+ `);
111918
+ }
111919
+ function reasonNotToOpen(identity, snapshot, nowMs) {
111920
+ if (snapshot === void 0) {
111921
+ return void 0;
111922
+ }
111923
+ const unified = snapshot.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified;
111924
+ if (unified !== void 0 && unified.fiveHour === void 0 && unified.sevenDay === void 0) {
111925
+ return "it reports no plan windows, so there is no five-hour window to anchor";
111926
+ }
111927
+ const five = unified?.fiveHour === void 0 ? void 0 : effectiveWindow(unified.fiveHour, nowMs);
111928
+ if (five?.resetsAtMs !== void 0) {
111929
+ return `a five-hour window is already open, resetting in ${formatAge(five.resetsAtMs - nowMs)}`;
111930
+ }
111931
+ const candidate = rankPool({ members: [{ identity, snapshot, records: [] }], nowMs, resuming: false }).candidates[0];
111932
+ return candidate?.class === "ineligible" ? `it is refused right now (${candidate.reasons[0] ?? "no reason recorded"})` : void 0;
111933
+ }
111934
+ async function runWindowKeeper(ports) {
111935
+ const nowMs = ports.nowMs();
111936
+ const anchored = ports.anchored();
111937
+ const previous = readStamps(ports.fs, ports.stampsFile);
111938
+ const handled = Object.fromEntries(anchored.flatMap(({ identity }) => previous[identity] === void 0 ? [] : [[identity, previous[identity]]]));
111939
+ const outcomes = [];
111940
+ for (const { identity, anchors } of anchored) {
111941
+ const last = handled[identity];
111942
+ if (last === void 0) {
111943
+ handled[identity] = nowMs;
111944
+ outcomes.push({ identity, status: "armed", detail: "anchors noted; the next anchor to fall is the first acted on" });
111945
+ continue;
111946
+ }
111947
+ const due2 = dueAnchor(anchors, nowMs, last, ports.timeZone);
111948
+ if (due2 === void 0) {
111949
+ outcomes.push({ identity, status: "waiting", detail: "no anchor has fallen since the last handled" });
111950
+ continue;
111951
+ }
111952
+ handled[identity] = nowMs;
111953
+ const reason = reasonNotToOpen(identity, ports.snapshot(identity), nowMs);
111954
+ if (reason !== void 0) {
111955
+ outcomes.push({ identity, status: "skipped", detail: `anchor ${new Date(due2).toISOString()}: ${reason}` });
111956
+ continue;
111957
+ }
111958
+ try {
111959
+ await ports.open(identity);
111960
+ outcomes.push({ identity, status: "opened", detail: `anchor ${new Date(due2).toISOString()}: opened a five-hour window` });
111961
+ } catch (error63) {
111962
+ outcomes.push({ identity, status: "failed", detail: `anchor ${new Date(due2).toISOString()}: could not open a window: ${error63 instanceof Error ? error63.message : String(error63)}` });
111963
+ }
111964
+ }
111965
+ writeStamps(ports.fs, ports.stampsFile, handled);
111966
+ for (const outcome of outcomes) {
111967
+ if (outcome.status === "opened" || outcome.status === "skipped" || outcome.status === "failed") {
111968
+ ports.log(`window keeper: ${outcome.identity}: ${outcome.detail}`);
111969
+ }
111970
+ }
111971
+ return outcomes;
111972
+ }
111973
+
111974
+ // src/frontdoor/commands.ts
111689
111975
  init_realCredentialCache();
111690
111976
 
111691
111977
  // src/frontdoor/custody.ts
@@ -111794,7 +112080,7 @@ init_capability();
111794
112080
 
111795
112081
  // src/frontdoor/capture.ts
111796
112082
  var fs15 = __toESM(require("node:fs"), 1);
111797
- var path37 = __toESM(require("node:path"), 1);
112083
+ var path38 = __toESM(require("node:path"), 1);
111798
112084
  var SECRET_HEADER_NAME = /authorization|cookie|token|secret|credential|api[-_]key/i;
111799
112085
  var SECRET_JSON_KEY = /token|secret|password|credential|authorization|api[-_]key/i;
111800
112086
  var SECRET_BODY_PATTERNS = [
@@ -111838,10 +112124,10 @@ function redactBody(chunk) {
111838
112124
  }
111839
112125
  var CAPTURE_ENV = "AGENT_SHIM_FRONTDOOR_CAPTURE";
111840
112126
  function captureFromEnv(env, logsDir) {
111841
- return env[CAPTURE_ENV] === "1" ? createFileCapture(path37.join(logsDir, "frontdoor-capture.jsonl")) : void 0;
112127
+ return env[CAPTURE_ENV] === "1" ? createFileCapture(path38.join(logsDir, "frontdoor-capture.jsonl")) : void 0;
111842
112128
  }
111843
112129
  function createFileCapture(file2, now = () => /* @__PURE__ */ new Date()) {
111844
- fs15.mkdirSync(path37.dirname(file2), { recursive: true });
112130
+ fs15.mkdirSync(path38.dirname(file2), { recursive: true });
111845
112131
  let nextId = 0;
111846
112132
  const append = (record2) => {
111847
112133
  fs15.appendFileSync(file2, `${JSON.stringify({ ts: now().toISOString(), ...record2 })}
@@ -111970,7 +112256,7 @@ var HIGH_BIT = 128;
111970
112256
  var BASE_128_PAYLOAD_MASK = 127;
111971
112257
  var FIRST_ARC_WEIGHT = 40;
111972
112258
  var SHORT_FORM_MAX_LENGTH = 127;
111973
- var MS_PER_SECOND6 = 1e3;
112259
+ var MS_PER_SECOND7 = 1e3;
111974
112260
  var UTC_TIME_LAST_YEAR = 2049;
111975
112261
  var YEAR_DIGITS = 4;
111976
112262
  var TWO_DIGIT_YEAR_DIGITS = 2;
@@ -112029,7 +112315,7 @@ function wholeBitString(content) {
112029
112315
  return tlv(TAG_BIT_STRING, Buffer.concat([Buffer.from([0]), content]));
112030
112316
  }
112031
112317
  function time3(instant) {
112032
- const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND6) * MS_PER_SECOND6).toISOString();
112318
+ const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND7) * MS_PER_SECOND7).toISOString();
112033
112319
  const compact = `${iso.replace(/[-:T]/g, "").slice(0, COMPACT_TIME_DIGITS)}Z`;
112034
112320
  if (instant.getUTCFullYear() > UTC_TIME_LAST_YEAR) {
112035
112321
  return tlv(TAG_GENERALIZED_TIME, Buffer.from(compact, "ascii"));
@@ -112260,19 +112546,19 @@ init_capability();
112260
112546
  init_route();
112261
112547
 
112262
112548
  // src/frontdoor/supervisor.ts
112263
- var import_node_path38 = __toESM(require("node:path"), 1);
112549
+ var import_node_path39 = __toESM(require("node:path"), 1);
112264
112550
  init_state2();
112265
112551
  function watchedInstallEntry(resolvedOwnExecutablePath, siblingExists) {
112266
- const parsed = import_node_path38.default.parse(resolvedOwnExecutablePath);
112552
+ const parsed = import_node_path39.default.parse(resolvedOwnExecutablePath);
112267
112553
  if (parsed.name === "agent-shim") {
112268
112554
  return resolvedOwnExecutablePath;
112269
112555
  }
112270
- const sibling = import_node_path38.default.join(parsed.dir, `agent-shim${parsed.ext}`);
112556
+ const sibling = import_node_path39.default.join(parsed.dir, `agent-shim${parsed.ext}`);
112271
112557
  return siblingExists(sibling) ? sibling : resolvedOwnExecutablePath;
112272
112558
  }
112273
112559
  var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
112274
112560
  var FRONTDOOR_POLL_MS = 1e3;
112275
- var MS_PER_MINUTE2 = 6e4;
112561
+ var MS_PER_MINUTE3 = 6e4;
112276
112562
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
112277
112563
  const { fs: fs22, paths } = ports;
112278
112564
  const servingBinary = ports.statOwnExecutable();
@@ -112399,7 +112685,7 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
112399
112685
  return await shutdown();
112400
112686
  }
112401
112687
  idleSince ??= ports.now();
112402
- if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE2) {
112688
+ if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE3) {
112403
112689
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
112404
112690
  ports.doorHealth.idleShutdown();
112405
112691
  return await shutdown();
@@ -112440,7 +112726,7 @@ var CONNECT_LIMITS = {
112440
112726
  var CA_VALIDITY_DAYS = 3650;
112441
112727
  var LEAF_VALIDITY_DAYS = 397;
112442
112728
  var CA_SUBJECT_COMMON_NAME = "agent-shim front door CA";
112443
- var MS_PER_DAY2 = 864e5;
112729
+ var MS_PER_DAY3 = 864e5;
112444
112730
  function parseConnectTarget(authority) {
112445
112731
  const colon = authority.lastIndexOf(":");
112446
112732
  if (colon === -1) {
@@ -112454,8 +112740,8 @@ function parseConnectTarget(authority) {
112454
112740
  }
112455
112741
  return { host, port };
112456
112742
  }
112457
- function servedByPipeline(path51) {
112458
- return path51?.startsWith(ROUTED_PATH_PREFIX) === true;
112743
+ function servedByPipeline(path52) {
112744
+ return path52?.startsWith(ROUTED_PATH_PREFIX) === true;
112459
112745
  }
112460
112746
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
112461
112747
  "connection",
@@ -112486,11 +112772,11 @@ function forwardableHeaders(headers) {
112486
112772
  return result;
112487
112773
  }
112488
112774
  function generateCa(now) {
112489
- return issueCaCertificate(CA_SUBJECT_COMMON_NAME, new Date(now.getTime() - MS_PER_DAY2), new Date(now.getTime() + CA_VALIDITY_DAYS * MS_PER_DAY2));
112775
+ return issueCaCertificate(CA_SUBJECT_COMMON_NAME, new Date(now.getTime() - MS_PER_DAY3), new Date(now.getTime() + CA_VALIDITY_DAYS * MS_PER_DAY3));
112490
112776
  }
112491
112777
  var LOOPBACK_LEAF_NAMES = ["127.0.0.1", "localhost"];
112492
112778
  function mintLeaf(ca2, names, now) {
112493
- return issueLeafCertificate(ca2, names, new Date(now.getTime() - MS_PER_DAY2), new Date(now.getTime() + LEAF_VALIDITY_DAYS * MS_PER_DAY2));
112779
+ return issueLeafCertificate(ca2, names, new Date(now.getTime() - MS_PER_DAY3), new Date(now.getTime() + LEAF_VALIDITY_DAYS * MS_PER_DAY3));
112494
112780
  }
112495
112781
  function createLeafCache(ca2, now) {
112496
112782
  const cache = /* @__PURE__ */ new Map();
@@ -112974,11 +113260,11 @@ function createRcSessionTracker(deps) {
112974
113260
  };
112975
113261
  const observeExchange = (request7) => {
112976
113262
  const method = (request7.method ?? "").toUpperCase();
112977
- const path51 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
112978
- if (!path51.startsWith(RC_SESSIONS_PATH_PREFIX)) {
113263
+ const path52 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
113264
+ if (!path52.startsWith(RC_SESSIONS_PATH_PREFIX)) {
112979
113265
  return void 0;
112980
113266
  }
112981
- const tail = path51.slice(RC_SESSIONS_PATH_PREFIX.length);
113267
+ const tail = path52.slice(RC_SESSIONS_PATH_PREFIX.length);
112982
113268
  const facts = {
112983
113269
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
112984
113270
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -113339,8 +113625,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
113339
113625
  function isRcReadFileEncoding(value2) {
113340
113626
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value2);
113341
113627
  }
113342
- function buildRcReadFilePayload(requestId, path51, options) {
113343
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path51, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
113628
+ function buildRcReadFilePayload(requestId, path52, options) {
113629
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path52, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
113344
113630
  }
113345
113631
  function buildRcFileSuggestionsPayload(requestId, query) {
113346
113632
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -113442,15 +113728,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
113442
113728
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
113443
113729
  return result.ok ? { ...result, requestId } : result;
113444
113730
  }
113445
- async function readRcSessionFile(deps, sessionId, path51, options) {
113446
- if (path51 === "") {
113731
+ async function readRcSessionFile(deps, sessionId, path52, options) {
113732
+ if (path52 === "") {
113447
113733
  return { ok: false, message: "a read-file write needs a non-empty path: the SDK's own field names the file the worker resolves against the session's cwd, and an empty string names none" };
113448
113734
  }
113449
113735
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
113450
113736
  return { ok: false, message: "a read-file write's max-bytes is a positive whole number of bytes: the SDK's own field caps the read, and a zero or negative cap reads nothing" };
113451
113737
  }
113452
113738
  const requestId = deps.newUuid();
113453
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path51, options), `read ${path51} from session ${sessionId}`);
113739
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path52, options), `read ${path52} from session ${sessionId}`);
113454
113740
  return result.ok ? { ...result, requestId } : result;
113455
113741
  }
113456
113742
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -113621,11 +113907,11 @@ function createRcControlHandler(deps) {
113621
113907
  path: "read-file",
113622
113908
  read: (body) => {
113623
113909
  const session = bodyString(body, "session");
113624
- const path51 = bodyString(body, "path");
113910
+ const path52 = bodyString(body, "path");
113625
113911
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
113626
113912
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
113627
- const refused2 = session === void 0 || path51 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
113628
- return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path51, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
113913
+ const refused2 = session === void 0 || path52 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
113914
+ return refused2 ? { error: `the read-file body must be JSON naming a non-empty session id and path, maxBytes only as a positive whole number or absent, and an encoding the SDK's own type permits (${RC_READ_FILE_ENCODINGS.join(", ")}) or none` } : { session, run: async () => await deps.readFile(session, path52, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
113629
113915
  }
113630
113916
  },
113631
113917
  {
@@ -113935,9 +114221,9 @@ function requestIdOfBody(body) {
113935
114221
  }
113936
114222
  function frontDoorRcControl(transport, token) {
113937
114223
  const headers = { authorization: `Bearer ${token}` };
113938
- const listAnswerOf = async (path51, what) => {
114224
+ const listAnswerOf = async (path52, what) => {
113939
114225
  try {
113940
- return await transport.request({ method: "GET", path: path51, headers });
114226
+ return await transport.request({ method: "GET", path: path52, headers });
113941
114227
  } catch (error63) {
113942
114228
  throw new Error(`${what}: could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}`, { cause: error63 });
113943
114229
  }
@@ -114009,10 +114295,10 @@ function frontDoorRcControl(transport, token) {
114009
114295
  }
114010
114296
  return pending;
114011
114297
  };
114012
- const writeOf = async (path51, body, describeFailure) => {
114298
+ const writeOf = async (path52, body, describeFailure) => {
114013
114299
  let answer;
114014
114300
  try {
114015
- answer = await transport.request({ method: "POST", path: path51, headers: { ...headers, "content-type": "application/json" }, body });
114301
+ answer = await transport.request({ method: "POST", path: path52, headers: { ...headers, "content-type": "application/json" }, body });
114016
114302
  } catch (error63) {
114017
114303
  return { ok: false, message: `could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}` };
114018
114304
  }
@@ -114043,10 +114329,10 @@ function frontDoorRcControl(transport, token) {
114043
114329
  endSession: async (sessionId, reason) => await writeOf(`${CONTROL_PATH_PREFIX}/end-session`, JSON.stringify({ session: sessionId, ...reason === void 0 ? {} : { reason } }), (status, message) => `ending ${sessionId} failed (HTTP ${String(status)}): ${message}`),
114044
114330
  getUsage: async (sessionId, skipBehaviors) => await writeOf(`${CONTROL_PATH_PREFIX}/get-usage`, JSON.stringify({ session: sessionId, ...skipBehaviors === void 0 ? {} : { skipBehaviors } }), (status, message) => `requesting the usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
114045
114331
  getContextUsage: async (sessionId, detail) => await writeOf(`${CONTROL_PATH_PREFIX}/get-context-usage`, JSON.stringify({ session: sessionId, ...detail === void 0 ? {} : { detail } }), (status, message) => `requesting the context usage of ${sessionId} failed (HTTP ${String(status)}): ${message}`),
114046
- readFile: async (sessionId, path51, options) => await writeOf(
114332
+ readFile: async (sessionId, path52, options) => await writeOf(
114047
114333
  `${CONTROL_PATH_PREFIX}/read-file`,
114048
- JSON.stringify({ session: sessionId, path: path51, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
114049
- (status, message) => `reading ${path51} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
114334
+ JSON.stringify({ session: sessionId, path: path52, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
114335
+ (status, message) => `reading ${path52} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
114050
114336
  ),
114051
114337
  fileSuggestions: async (sessionId, query) => await writeOf(`${CONTROL_PATH_PREFIX}/file-suggestions`, JSON.stringify({ session: sessionId, query }), (status, message) => `requesting file suggestions from ${sessionId} failed (HTTP ${String(status)}): ${message}`),
114052
114338
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -114340,12 +114626,12 @@ function tlsFacts(options) {
114340
114626
  }
114341
114627
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
114342
114628
  const agent = new ExemptTlsAgent();
114343
- const post = async (path51, headers, body) => await new Promise((resolve2, reject) => {
114629
+ const post = async (path52, headers, body) => await new Promise((resolve2, reject) => {
114344
114630
  const options = {
114345
114631
  host: target.host,
114346
114632
  port: target.port,
114347
114633
  method: "POST",
114348
- path: path51,
114634
+ path: path52,
114349
114635
  // 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.
114350
114636
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
114351
114637
  agent
@@ -114410,12 +114696,12 @@ function lateRcStreamDial(resolve2) {
114410
114696
  }
114411
114697
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
114412
114698
  const agent = new ExemptTlsAgent();
114413
- const request7 = async (method, path51, headers, body, signal) => await new Promise((resolve2, reject) => {
114699
+ const request7 = async (method, path52, headers, body, signal) => await new Promise((resolve2, reject) => {
114414
114700
  const options = {
114415
114701
  host: target.host,
114416
114702
  port: target.port,
114417
114703
  method,
114418
- path: path51,
114704
+ path: path52,
114419
114705
  // 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.
114420
114706
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
114421
114707
  agent,
@@ -114457,9 +114743,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
114457
114743
  return { status, body: await readAll(response) };
114458
114744
  },
114459
114745
  openStream: async (sessionId, headers, resume, signal) => {
114460
- const path51 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
114746
+ const path52 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
114461
114747
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
114462
- const { status, response } = await request7("GET", path51, streamHeaders, void 0, signal);
114748
+ const { status, response } = await request7("GET", path52, streamHeaders, void 0, signal);
114463
114749
  if (!isSuccessful2(status)) {
114464
114750
  await readAll(response);
114465
114751
  return { status, chunks: NO_CHUNKS };
@@ -114675,10 +114961,10 @@ init_claudeShim();
114675
114961
  init_store();
114676
114962
  init_realPorts();
114677
114963
  var import_node_fs15 = __toESM(require("node:fs"), 1);
114678
- var import_node_path40 = __toESM(require("node:path"), 1);
114964
+ var import_node_path41 = __toESM(require("node:path"), 1);
114679
114965
 
114680
114966
  // src/usage/signIn.ts
114681
- var import_node_path39 = __toESM(require("node:path"), 1);
114967
+ var import_node_path40 = __toESM(require("node:path"), 1);
114682
114968
  var CREDENTIALS_FILE = ".credentials.json";
114683
114969
  function keychainHasItem(run, account) {
114684
114970
  return run.run("security", ["find-generic-password", "-a", account]).status === 0;
@@ -114696,7 +114982,7 @@ function decideSignIn(facts) {
114696
114982
  return { state: "signed-out", detail: facts.platform === "darwin" ? `no Keychain item and no ${CREDENTIALS_FILE}` : `no ${CREDENTIALS_FILE}` };
114697
114983
  }
114698
114984
  function credentialsFilePath(farmRoot) {
114699
- return import_node_path39.default.join(farmRoot, CREDENTIALS_FILE);
114985
+ return import_node_path40.default.join(farmRoot, CREDENTIALS_FILE);
114700
114986
  }
114701
114987
  function identitySignIn(fs22, probe, identity) {
114702
114988
  const probing = !identity.hasCredentialBlock;
@@ -114822,7 +115108,7 @@ function tcpPortEraRecord(raw) {
114822
115108
  return (has("port") || has("lastPort")) && !has("socketPath");
114823
115109
  }
114824
115110
  function pushPathResolution(push, resolution) {
114825
- const ownDir = import_node_path40.default.dirname(resolution.ownExecutablePath);
115111
+ const ownDir = import_node_path41.default.dirname(resolution.ownExecutablePath);
114826
115112
  switch (resolution.agentShim.status) {
114827
115113
  case "ok":
114828
115114
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -114921,14 +115207,14 @@ function pushProvider(push, entry, cacheEnv, signIn) {
114921
115207
  }
114922
115208
  function pushLegacyName(push, params) {
114923
115209
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
114924
- if (legacyVariables.length === 0 && import_node_path40.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
115210
+ if (legacyVariables.length === 0 && import_node_path41.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
114925
115211
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
114926
115212
  return;
114927
115213
  }
114928
115214
  for (const name of legacyVariables) {
114929
115215
  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);
114930
115216
  }
114931
- if (import_node_path40.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
115217
+ if (import_node_path41.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
114932
115218
  push(
114933
115219
  "legacy-name",
114934
115220
  "warn",
@@ -115301,18 +115587,18 @@ function collectDoctorReport(params) {
115301
115587
  const { paths } = params;
115302
115588
  const identityNames = import_node_fs15.default.existsSync(paths.identitiesDir) ? import_node_fs15.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
115303
115589
  const identities = identityNames.map((name) => {
115304
- const farmRoot = import_node_path40.default.join(paths.identitiesDir, name);
115305
- const identityPath = import_node_path40.default.join(farmRoot, "identity.json");
115590
+ const farmRoot = import_node_path41.default.join(paths.identitiesDir, name);
115591
+ const identityPath = import_node_path41.default.join(farmRoot, "identity.json");
115306
115592
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: import_node_fs15.default.existsSync(credentialsFilePath(farmRoot)) };
115307
115593
  });
115308
115594
  const profileNames = import_node_fs15.default.existsSync(paths.configProfilesDir) ? import_node_fs15.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
115309
115595
  const configProfiles = profileNames.map((name) => {
115310
- const profilePath = import_node_path40.default.join(paths.configProfilesDir, `${name}.json`);
115596
+ const profilePath = import_node_path41.default.join(paths.configProfilesDir, `${name}.json`);
115311
115597
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
115312
115598
  });
115313
115599
  const providerNames = import_node_fs15.default.existsSync(paths.providersDir) ? import_node_fs15.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
115314
115600
  const providers = providerNames.map((name) => {
115315
- const providerPath = import_node_path40.default.join(paths.providersDir, `${name}.json`);
115601
+ const providerPath = import_node_path41.default.join(paths.providersDir, `${name}.json`);
115316
115602
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
115317
115603
  });
115318
115604
  const ownExecutablePath = realOwnExecutablePath();
@@ -115324,12 +115610,12 @@ function collectDoctorReport(params) {
115324
115610
  binaryDiscovery = { ok: false, message: error63 instanceof Error ? error63.message : String(error63) };
115325
115611
  }
115326
115612
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
115327
- const pathDirs = (params.env.PATH ?? "").split(import_node_path40.default.delimiter).filter((dir) => dir !== "");
115613
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path41.default.delimiter).filter((dir) => dir !== "");
115328
115614
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
115329
115615
  findPathShadow({
115330
115616
  pathDirs,
115331
- targetDir: import_node_path40.default.dirname(shimState.targetPath),
115332
- targetFilename: import_node_path40.default.basename(shimState.targetPath),
115617
+ targetDir: import_node_path41.default.dirname(shimState.targetPath),
115618
+ targetFilename: import_node_path41.default.basename(shimState.targetPath),
115333
115619
  findExecutableInDir
115334
115620
  }),
115335
115621
  shimState.targetPath,
@@ -115358,7 +115644,7 @@ function collectDoctorReport(params) {
115358
115644
  agentShim: refinePathShadow(
115359
115645
  findPathShadow({
115360
115646
  pathDirs,
115361
- targetDir: import_node_path40.default.dirname(ownExecutablePath),
115647
+ targetDir: import_node_path41.default.dirname(ownExecutablePath),
115362
115648
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
115363
115649
  findExecutableInDir
115364
115650
  }),
@@ -115621,11 +115907,11 @@ function tryOrUndefined(fn2) {
115621
115907
  return void 0;
115622
115908
  }
115623
115909
  }
115624
- function pathToHttpPath(path51) {
115625
- return `/${path51.map(safeEncodeURIComponent).join("/")}`;
115910
+ function pathToHttpPath(path52) {
115911
+ return `/${path52.map(safeEncodeURIComponent).join("/")}`;
115626
115912
  }
115627
- function normalizeHttpPath(path51) {
115628
- const paths = path51.split("/");
115913
+ function normalizeHttpPath(path52) {
115914
+ const paths = path52.split("/");
115629
115915
  if (paths.at(0) === "") {
115630
115916
  paths.shift();
115631
115917
  }
@@ -115810,9 +116096,9 @@ function isPlainObject2(value2) {
115810
116096
  function getOwn(object3, key) {
115811
116097
  return Object.hasOwn(object3, key) ? object3[key] : void 0;
115812
116098
  }
115813
- function get(object3, path51) {
116099
+ function get(object3, path52) {
115814
116100
  let current = object3;
115815
- for (const key of path51) {
116101
+ for (const key of path52) {
115816
116102
  if (!isTypescriptObject(current)) {
115817
116103
  return void 0;
115818
116104
  }
@@ -117035,7 +117321,7 @@ function resolveClientRest(rest) {
117035
117321
  // rest[1] can be undefined if all fields of FriendlyClientOptions are optional
117036
117322
  ];
117037
117323
  }
117038
- function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117324
+ function createORPCClient(link, { path: path52 = [], ...options } = {}) {
117039
117325
  const procedureClient = (...rest) => {
117040
117326
  const [input2, callOptions] = resolveClientRest(rest);
117041
117327
  const interceptors = [
@@ -117044,7 +117330,7 @@ function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117044
117330
  ];
117045
117331
  return intercept(
117046
117332
  interceptors,
117047
- { ...callOptions, input: input2, path: path51 },
117333
+ { ...callOptions, input: input2, path: path52 },
117048
117334
  ({ path: path210, input: input22, ...callOptions2 }) => link.call(path210, input22, callOptions2)
117049
117335
  );
117050
117336
  };
@@ -117058,7 +117344,7 @@ function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117058
117344
  if (client === void 0) {
117059
117345
  client = createORPCClient(link, {
117060
117346
  ...options,
117061
- path: [...path51, key],
117347
+ path: [...path52, key],
117062
117348
  scoped: options.scoped?.[key]
117063
117349
  });
117064
117350
  cache.set(key, client);
@@ -117080,24 +117366,24 @@ var BracketNotationSerializer = class {
117080
117366
  this.internalSerialize(data, "", true, result);
117081
117367
  return result;
117082
117368
  }
117083
- internalSerialize(data, path51, isRoot, result) {
117369
+ internalSerialize(data, path52, isRoot, result) {
117084
117370
  if (Array.isArray(data)) {
117085
117371
  data.forEach((item, i10) => {
117086
- this.internalSerialize(item, isRoot ? i10.toString() : `${path51}[${i10}]`, false, result);
117372
+ this.internalSerialize(item, isRoot ? i10.toString() : `${path52}[${i10}]`, false, result);
117087
117373
  });
117088
117374
  } else if (isPlainObject2(data)) {
117089
117375
  for (const key of Object.keys(data)) {
117090
- this.internalSerialize(data[key], isRoot ? key : `${path51}[${key}]`, false, result);
117376
+ this.internalSerialize(data[key], isRoot ? key : `${path52}[${key}]`, false, result);
117091
117377
  }
117092
117378
  } else {
117093
- result.push([path51, data]);
117379
+ result.push([path52, data]);
117094
117380
  }
117095
117381
  }
117096
117382
  deserialize(serialized) {
117097
117383
  const arrayPushStyles = /* @__PURE__ */ new WeakSet();
117098
117384
  const root = new NullProtoObj();
117099
- for (const [path51, value2] of serialized) {
117100
- const segments = this.parsePath(path51);
117385
+ for (const [path52, value2] of serialized) {
117386
+ const segments = this.parsePath(path52);
117101
117387
  let currentRef = root;
117102
117388
  let nextSegment = segments[0];
117103
117389
  for (let i10 = 1; i10 < segments.length; i10++) {
@@ -117148,13 +117434,13 @@ var BracketNotationSerializer = class {
117148
117434
  }
117149
117435
  return result;
117150
117436
  }
117151
- parsePath(path51) {
117437
+ parsePath(path52) {
117152
117438
  const segments = [];
117153
117439
  let inBrackets = false;
117154
117440
  let currentSegment = "";
117155
- for (let i10 = 0; i10 < path51.length; i10++) {
117156
- const char = path51[i10];
117157
- const nextChar = path51[i10 + 1];
117441
+ for (let i10 = 0; i10 < path52.length; i10++) {
117442
+ const char = path52[i10];
117443
+ const nextChar = path52[i10 + 1];
117158
117444
  if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[")) {
117159
117445
  if (nextChar === void 0) {
117160
117446
  inBrackets = false;
@@ -117170,7 +117456,7 @@ var BracketNotationSerializer = class {
117170
117456
  currentSegment += char;
117171
117457
  }
117172
117458
  }
117173
- return inBrackets || segments.length === 0 ? [path51] : segments;
117459
+ return inBrackets || segments.length === 0 ? [path52] : segments;
117174
117460
  }
117175
117461
  };
117176
117462
  var INTEGER_PATTERN = /^0$|^[1-9]\d*$/;
@@ -117743,11 +118029,11 @@ var OpenAPISerializer = class {
117743
118029
  return json2;
117744
118030
  }
117745
118031
  const form = new FormData();
117746
- for (const [path51, value22] of this.bracketNotation.serialize(json2)) {
118032
+ for (const [path52, value22] of this.bracketNotation.serialize(json2)) {
117747
118033
  if (value22 instanceof Blob) {
117748
- form.append(path51, value22);
118034
+ form.append(path52, value22);
117749
118035
  } else if (value22 !== void 0 && value22 !== null) {
117750
- form.append(path51, String(value22));
118036
+ form.append(path52, String(value22));
117751
118037
  }
117752
118038
  }
117753
118039
  return form;
@@ -117785,30 +118071,30 @@ function isBodylessMethod(method) {
117785
118071
  return method === "GET" || method === "HEAD";
117786
118072
  }
117787
118073
  var PARAMETER_NAME_REGEX = /^[\w-]+$/;
117788
- function getDynamicPathParams(path51) {
117789
- if (!path51.includes("{")) {
118074
+ function getDynamicPathParams(path52) {
118075
+ if (!path52.includes("{")) {
117790
118076
  return void 0;
117791
118077
  }
117792
- const len = path51.length;
118078
+ const len = path52.length;
117793
118079
  let params;
117794
118080
  let index = 1;
117795
118081
  while (index < len) {
117796
118082
  const segmentStart = index;
117797
- const slashPos = path51.indexOf("/", index);
118083
+ const slashPos = path52.indexOf("/", index);
117798
118084
  const segmentEnd = slashPos === -1 ? len : slashPos;
117799
- if (segmentEnd > segmentStart && path51.charCodeAt(segmentStart) === 123 && path51.charCodeAt(segmentEnd - 1) === 125) {
118085
+ if (segmentEnd > segmentStart && path52.charCodeAt(segmentStart) === 123 && path52.charCodeAt(segmentEnd - 1) === 125) {
117800
118086
  let parameterStart = segmentStart + 1;
117801
118087
  let allowsSlash = false;
117802
- const operator = path51.charCodeAt(parameterStart);
118088
+ const operator = path52.charCodeAt(parameterStart);
117803
118089
  if (operator === 43) {
117804
118090
  allowsSlash = true;
117805
118091
  parameterStart++;
117806
118092
  }
117807
- const parameterName = path51.slice(parameterStart, segmentEnd - 1);
118093
+ const parameterName = path52.slice(parameterStart, segmentEnd - 1);
117808
118094
  if (PARAMETER_NAME_REGEX.test(parameterName)) {
117809
118095
  params ??= [];
117810
118096
  params.push({
117811
- segment: path51.slice(segmentStart, segmentEnd),
118097
+ segment: path52.slice(segmentStart, segmentEnd),
117812
118098
  startIndex: segmentStart,
117813
118099
  parameterName,
117814
118100
  allowsSlash
@@ -117851,8 +118137,8 @@ openapi.method = (method) => ({
117851
118137
  ...openapi({ method }),
117852
118138
  name: "~openapi/method"
117853
118139
  });
117854
- openapi.path = (path51) => ({
117855
- ...openapi({ path: path51 }),
118140
+ openapi.path = (path52) => ({
118141
+ ...openapi({ path: path52 }),
117856
118142
  name: "~openapi/path"
117857
118143
  });
117858
118144
  openapi.spec = (spec) => ({
@@ -118713,22 +118999,22 @@ function visitJsonSchemaRefs(value2, visit2, schemaLevel = true, seen = /* @__PU
118713
118999
  }
118714
119000
  }
118715
119001
  }
118716
- function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path51 = []) {
119002
+ function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path52 = []) {
118717
119003
  if (!value2 || typeof value2 !== "object") {
118718
119004
  return value2;
118719
119005
  }
118720
119006
  if (Array.isArray(value2)) {
118721
- return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path51, index]));
119007
+ return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path52, index]));
118722
119008
  }
118723
119009
  const result = {};
118724
119010
  for (const key of Object.keys(value2)) {
118725
119011
  const val = value2[key];
118726
119012
  if (key === "$ref" && typeof val === "string") {
118727
- setOwn(result, key, map2(val, [...path51, key]));
119013
+ setOwn(result, key, map2(val, [...path52, key]));
118728
119014
  } else if (!schemaLevel) {
118729
- setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path51, key]));
119015
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path52, key]));
118730
119016
  } else if (JSON_SCHEMA_LOGIC_KEYWORDS.has(key) || JSON_SCHEMA_RECORD_KEYWORDS.has(key)) {
118731
- setOwn(result, key, mapJsonSchemaRefs(val, map2, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path51, key]));
119017
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path52, key]));
118732
119018
  } else {
118733
119019
  setOwn(result, key, val);
118734
119020
  }
@@ -119258,7 +119544,7 @@ function unlazy(maybeLazy) {
119258
119544
  function createProcedureClient(lazyableProcedure, ...rest) {
119259
119545
  const options = resolveMaybeOptionalOptions(rest);
119260
119546
  return async (...[input2, callerOptions]) => {
119261
- const path51 = toArray(options.path);
119547
+ const path52 = toArray(options.path);
119262
119548
  const { default: procedure } = await unlazy(lazyableProcedure);
119263
119549
  const clientContext = callerOptions?.context ?? {};
119264
119550
  const context = await value(options.context, clientContext) ?? {};
@@ -119271,7 +119557,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
119271
119557
  };
119272
119558
  try {
119273
119559
  const output2 = await runWithSpan("call_procedure", (span) => {
119274
- span?.setAttribute("procedure.path", path51);
119560
+ span?.setAttribute("procedure.path", path52);
119275
119561
  return intercept(
119276
119562
  options.interceptors,
119277
119563
  {
@@ -119279,7 +119565,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
119279
119565
  // input can be optional if it is undefinable
119280
119566
  input: input2,
119281
119567
  errors,
119282
- path: path51,
119568
+ path: path52,
119283
119569
  procedure,
119284
119570
  signal: callerOptions?.signal,
119285
119571
  lastEventId: callerOptions?.lastEventId
@@ -119530,10 +119816,10 @@ function augmentRouter(router, options) {
119530
119816
  }
119531
119817
  return enhanced;
119532
119818
  }
119533
- function getRouter(router, path51) {
119819
+ function getRouter(router, path52) {
119534
119820
  let current = router;
119535
- for (let i10 = 0; i10 < path51.length; i10++) {
119536
- const segment = path51[i10];
119821
+ for (let i10 = 0; i10 < path52.length; i10++) {
119822
+ const segment = path52[i10];
119537
119823
  if (!isTypescriptObject(current)) {
119538
119824
  return void 0;
119539
119825
  }
@@ -119545,7 +119831,7 @@ function getRouter(router, path51) {
119545
119831
  continue;
119546
119832
  }
119547
119833
  const lazied = current;
119548
- const rest = path51.slice(i10);
119834
+ const rest = path52.slice(i10);
119549
119835
  return new Lazy({
119550
119836
  ...lazied["~orpc"],
119551
119837
  async loader() {
@@ -119560,40 +119846,40 @@ function getRouter(router, path51) {
119560
119846
  }
119561
119847
  return current;
119562
119848
  }
119563
- function walkProcedureContractsSync(router, callback, path51 = []) {
119849
+ function walkProcedureContractsSync(router, callback, path52 = []) {
119564
119850
  const lazyResults = [];
119565
- walkProcedureContractsSyncInternal(router, callback, path51.slice(), lazyResults);
119851
+ walkProcedureContractsSyncInternal(router, callback, path52.slice(), lazyResults);
119566
119852
  return lazyResults;
119567
119853
  }
119568
- function walkProcedureContractsSyncInternal(router, callback, path51, lazyResults) {
119854
+ function walkProcedureContractsSyncInternal(router, callback, path52, lazyResults) {
119569
119855
  const hiddenContract = getHiddenRouterContract(router);
119570
119856
  if (hiddenContract !== void 0) {
119571
119857
  router = hiddenContract;
119572
119858
  }
119573
119859
  if (router instanceof ProcedureContract) {
119574
- callback(router, path51.slice());
119860
+ callback(router, path52.slice());
119575
119861
  return;
119576
119862
  }
119577
119863
  if (!isTypescriptObject(router)) {
119578
119864
  return;
119579
119865
  }
119580
119866
  for (const [key, value2] of Object.entries(router)) {
119581
- path51.push(key);
119867
+ path52.push(key);
119582
119868
  if (value2 instanceof Lazy) {
119583
- lazyResults.push({ router: value2, path: path51.slice() });
119869
+ lazyResults.push({ router: value2, path: path52.slice() });
119584
119870
  } else {
119585
- walkProcedureContractsSyncInternal(value2, callback, path51, lazyResults);
119871
+ walkProcedureContractsSyncInternal(value2, callback, path52, lazyResults);
119586
119872
  }
119587
- path51.pop();
119873
+ path52.pop();
119588
119874
  }
119589
119875
  }
119590
- async function walkProcedureContractsAsync(router, callback, path51 = []) {
119876
+ async function walkProcedureContractsAsync(router, callback, path52 = []) {
119591
119877
  const hiddenContract = getHiddenRouterContract(router);
119592
119878
  if (hiddenContract !== void 0) {
119593
119879
  router = hiddenContract;
119594
119880
  }
119595
119881
  if (router instanceof ProcedureContract) {
119596
- await callback(router, path51);
119882
+ await callback(router, path52);
119597
119883
  return;
119598
119884
  }
119599
119885
  if (!isTypescriptObject(router)) {
@@ -119602,9 +119888,9 @@ async function walkProcedureContractsAsync(router, callback, path51 = []) {
119602
119888
  for (const [key, value2] of Object.entries(router)) {
119603
119889
  if (value2 instanceof Lazy) {
119604
119890
  const { default: router2 } = await unlazy(value2);
119605
- await walkProcedureContractsAsync(router2, callback, [...path51, key]);
119891
+ await walkProcedureContractsAsync(router2, callback, [...path52, key]);
119606
119892
  } else {
119607
- await walkProcedureContractsAsync(value2, callback, [...path51, key]);
119893
+ await walkProcedureContractsAsync(value2, callback, [...path52, key]);
119608
119894
  }
119609
119895
  }
119610
119896
  }
@@ -120090,18 +120376,18 @@ function rewriteComponentSchemaRefs(schema, renameMap) {
120090
120376
  }
120091
120377
  var OpenAPIGeneratorError = class extends TypeError {
120092
120378
  };
120093
- function toOpenAPIPath(path51, dynamicPathParams) {
120379
+ function toOpenAPIPath(path52, dynamicPathParams) {
120094
120380
  if (!dynamicPathParams?.length) {
120095
- return path51;
120381
+ return path52;
120096
120382
  }
120097
120383
  let normalized = "";
120098
120384
  let currentIndex = 0;
120099
120385
  for (const param of dynamicPathParams) {
120100
- normalized += path51.slice(currentIndex, param.startIndex);
120386
+ normalized += path52.slice(currentIndex, param.startIndex);
120101
120387
  normalized += `{${param.parameterName}}`;
120102
120388
  currentIndex = param.startIndex + param.segment.length;
120103
120389
  }
120104
- normalized += path51.slice(currentIndex);
120390
+ normalized += path52.slice(currentIndex);
120105
120391
  return normalized;
120106
120392
  }
120107
120393
  function buildRequest(ctx, operation, def, meta3, dynamicPathParams) {
@@ -120535,8 +120821,8 @@ var OpenAPIGenerator = class {
120535
120821
  customErrorResponseBodySchema: options.customErrorResponseBodySchema
120536
120822
  };
120537
120823
  const errors = [];
120538
- await walkProcedureContractsAsync(router, (contract, path51) => {
120539
- if (value(options.filter, contract, path51) === false) {
120824
+ await walkProcedureContractsAsync(router, (contract, path52) => {
120825
+ if (value(options.filter, contract, path52) === false) {
120540
120826
  return;
120541
120827
  }
120542
120828
  try {
@@ -120548,7 +120834,7 @@ var OpenAPIGenerator = class {
120548
120834
  `QUERY operations require OpenAPI 3.2, but version "${version2}" was requested.`
120549
120835
  );
120550
120836
  }
120551
- const postPath = meta3?.path ?? pathToHttpPath(path51);
120837
+ const postPath = meta3?.path ?? pathToHttpPath(path52);
120552
120838
  const httpPath = meta3?.prefix ? mergeHttpPath(meta3.prefix, postPath) : postPath;
120553
120839
  const dynamicPathParams = getDynamicPathParams(httpPath);
120554
120840
  const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
@@ -120557,7 +120843,7 @@ var OpenAPIGenerator = class {
120557
120843
  operation = meta3.spec;
120558
120844
  } else {
120559
120845
  operation = {
120560
- operationId: meta3?.operationId ?? path51.join("."),
120846
+ operationId: meta3?.operationId ?? path52.join("."),
120561
120847
  summary: meta3?.summary,
120562
120848
  description: meta3?.description,
120563
120849
  deprecated: meta3?.deprecated,
@@ -120577,7 +120863,7 @@ var OpenAPIGenerator = class {
120577
120863
  if (!(e14 instanceof OpenAPIGeneratorError)) {
120578
120864
  throw e14;
120579
120865
  }
120580
- errors.push(`Procedure at ${path51.join(".") || "(root)"}: ${e14.message}`);
120866
+ errors.push(`Procedure at ${path52.join(".") || "(root)"}: ${e14.message}`);
120581
120867
  }
120582
120868
  });
120583
120869
  if (errors.length) {
@@ -120885,7 +121171,7 @@ var ResetRowSchema = external_exports.strictObject({
120885
121171
  var ResetScheduleSchema = external_exports.strictObject({ resets: external_exports.readonly(external_exports.array(ResetRowSchema)) });
120886
121172
 
120887
121173
  // src/frontdoor/controlSchemas.ts
120888
- var import_node_path41 = __toESM(require("node:path"), 1);
121174
+ var import_node_path42 = __toESM(require("node:path"), 1);
120889
121175
  init_zod();
120890
121176
  init_schema2();
120891
121177
 
@@ -121097,11 +121383,11 @@ var FrontDoorSessionsOutputSchema = external_exports.strictObject({ sessions: ex
121097
121383
  var CheckRunInputSchema = external_exports.strictObject({
121098
121384
  path: external_exports.string().min(1),
121099
121385
  identity: external_exports.string().min(1).optional()
121100
- }).refine((input2) => import_node_path41.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
121386
+ }).refine((input2) => import_node_path42.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
121101
121387
  var PoolPickInputSchema = external_exports.strictObject({
121102
121388
  pool: external_exports.string().min(1),
121103
121389
  path: external_exports.string().min(1)
121104
- }).refine((input2) => import_node_path41.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
121390
+ }).refine((input2) => import_node_path42.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
121105
121391
  var DoctorFindingSchema = external_exports.strictObject({
121106
121392
  section: external_exports.enum(DOCTOR_SECTIONS),
121107
121393
  subject: external_exports.string().optional(),
@@ -121422,16 +121708,16 @@ var StandardLink = class {
121422
121708
  /**
121423
121709
  * @throws ORPCError, transport-level errors (network failures, timeouts, etc.)
121424
121710
  */
121425
- call(path51, input2, options) {
121426
- return runWithSpan(`${ORPC_NAME}.${path51.join("/")}`, (span) => {
121711
+ call(path52, input2, options) {
121712
+ return runWithSpan(`${ORPC_NAME}.${path52.join("/")}`, (span) => {
121427
121713
  span?.setAttribute("rpc.system", ORPC_NAME);
121428
- span?.setAttribute("rpc.method", path51.join("."));
121714
+ span?.setAttribute("rpc.method", path52.join("."));
121429
121715
  if (getTracer() && isAsyncIteratorObject(input2)) {
121430
121716
  input2 = override(input2, traceAsyncIterator("consume_async_iterator_object_input", input2));
121431
121717
  } else if (getTracer() && input2 instanceof ReadableStream) {
121432
121718
  input2 = override(input2, traceReadableStream("consume_octet_stream_input", input2));
121433
121719
  }
121434
- return intercept(this.interceptors, { ...options, path: path51, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
121720
+ return intercept(this.interceptors, { ...options, path: path52, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
121435
121721
  const tracer = getTracer();
121436
121722
  const activeSpan = tracer?.getActiveSpan() ?? span;
121437
121723
  let request7 = await runWithSpan(
@@ -121488,18 +121774,18 @@ var RPCLinkCodec = class {
121488
121774
  this.headers = options.headers ?? {};
121489
121775
  this.serializer = options.serializer ?? new RPCSerializer();
121490
121776
  }
121491
- async encodeInput(input2, path51, options) {
121492
- let headers = toResolvedStandardHeaders(await value(this.headers, options, path51, input2));
121777
+ async encodeInput(input2, path52, options) {
121778
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path52, input2));
121493
121779
  if (options.lastEventId !== void 0) {
121494
121780
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
121495
121781
  }
121496
- const expectedMethod = await value(this.expectedMethod, options, path51, input2);
121497
- const baseUrl = await value(this.baseUrl, options, path51, input2);
121782
+ const expectedMethod = await value(this.expectedMethod, options, path52, input2);
121783
+ const baseUrl = await value(this.baseUrl, options, path52, input2);
121498
121784
  const [pathname, search, hash2] = parseStandardUrl(baseUrl);
121499
- const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path51)}`;
121785
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path52)}`;
121500
121786
  const serialized = this.serializer.serialize(input2);
121501
121787
  if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
121502
- const maxUrlLength = await value(this.maxUrlLength, options, path51, input2);
121788
+ const maxUrlLength = await value(this.maxUrlLength, options, path52, input2);
121503
121789
  const mergedSearch = new URLSearchParams(search);
121504
121790
  mergedSearch.append("data", stringifyJSON(serialized) ?? "");
121505
121791
  const url22 = `${newPathname}?${mergedSearch}${hash2 ?? ""}`;
@@ -121584,8 +121870,8 @@ var FetchLinkTransport = class {
121584
121870
  this.fetch = options.fetch ?? ((url2, init) => globalThis.fetch(url2, init));
121585
121871
  this.toFetchRequestOptions = options.toFetchRequest;
121586
121872
  }
121587
- async send(standardRequest, path51, options) {
121588
- let origin = await value(this.origin, options, path51);
121873
+ async send(standardRequest, path52, options) {
121874
+ let origin = await value(this.origin, options, path52);
121589
121875
  if (origin?.endsWith("/")) {
121590
121876
  origin = origin.slice(0, -1);
121591
121877
  }
@@ -121605,7 +121891,7 @@ var FetchLinkTransport = class {
121605
121891
  }
121606
121892
  }
121607
121893
  const fetch3 = this.fetch;
121608
- const response = await fetch3(url2, init, options, path51);
121894
+ const response = await fetch3(url2, init, options, path52);
121609
121895
  const standardResponse = toStandardLazyResponse(response);
121610
121896
  return standardResponse;
121611
121897
  }
@@ -121996,14 +122282,14 @@ var StandardHandler = class {
121996
122282
  span?.setAttribute("url.path", request22.url);
121997
122283
  return { matched: false };
121998
122284
  }
121999
- const { path: path51, procedure, decodeInput } = matchedOrNot;
122000
- span?.updateName(`${ORPC_NAME}.${path51.join("/")}`);
122285
+ const { path: path52, procedure, decodeInput } = matchedOrNot;
122286
+ span?.updateName(`${ORPC_NAME}.${path52.join("/")}`);
122001
122287
  span?.setAttribute("rpc.system", ORPC_NAME);
122002
- span?.setAttribute("rpc.method", path51.join("."));
122288
+ span?.setAttribute("rpc.method", path52.join("."));
122003
122289
  try {
122004
122290
  const response = await intercept(
122005
122291
  this.interceptors,
122006
- { context: context2, prefix: prefix2, request: request22, path: path51, procedure, decodeInput },
122292
+ { context: context2, prefix: prefix2, request: request22, path: path52, procedure, decodeInput },
122007
122293
  async ({ context: context3, prefix: prefix3, request: request32, path: path210, procedure: procedure2, decodeInput: decodeInput2 }) => {
122008
122294
  step2 = "decode_input";
122009
122295
  let input2 = await runWithSpan("decode_input", decodeInput2);
@@ -122037,7 +122323,7 @@ var StandardHandler = class {
122037
122323
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
122038
122324
  cause: e14
122039
122325
  }) : toORPCError(e14);
122040
- const response = await this.codec.encodeError(error63, procedure, path51, { context: context2, prefix: prefix2 });
122326
+ const response = await this.codec.encodeError(error63, procedure, path52, { context: context2, prefix: prefix2 });
122041
122327
  return { matched: true, response };
122042
122328
  }
122043
122329
  }
@@ -122143,7 +122429,7 @@ var RPCMatcher = class {
122143
122429
  this.rootRouter = router;
122144
122430
  this.index(router);
122145
122431
  }
122146
- index(router, path51 = []) {
122432
+ index(router, path52 = []) {
122147
122433
  const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
122148
122434
  if (!value(this.filter, procedure, procedurePath)) {
122149
122435
  return;
@@ -122154,7 +122440,7 @@ var RPCMatcher = class {
122154
122440
  // contract-first entries have no implementation yet, resolveProcedure fills it in on demand
122155
122441
  procedure: procedure instanceof Procedure ? procedure : void 0
122156
122442
  });
122157
- }, path51);
122443
+ }, path52);
122158
122444
  for (const result of lazyResults) {
122159
122445
  this.pendingLazyRouters.set(pathToHttpPath(result.path), result);
122160
122446
  }
@@ -122286,10 +122572,10 @@ var RPCHandlerCodec = class {
122286
122572
  }
122287
122573
  };
122288
122574
  }
122289
- encodeOutput(output2, procedure, path51, options) {
122575
+ encodeOutput(output2, procedure, path52, options) {
122290
122576
  return {
122291
122577
  headers: {},
122292
- status: value(this.outputStatus, output2, procedure, path51, options) ?? DEFAULT_SUCCESS_STATUS,
122578
+ status: value(this.outputStatus, output2, procedure, path52, options) ?? DEFAULT_SUCCESS_STATUS,
122293
122579
  body: this.serializer.serialize(output2)
122294
122580
  };
122295
122581
  }
@@ -122343,39 +122629,39 @@ function createRouter() {
122343
122629
  static: new NullProtoObj2()
122344
122630
  };
122345
122631
  }
122346
- function scanFirstGroup(path51) {
122632
+ function scanFirstGroup(path52) {
122347
122633
  let i10 = 0;
122348
122634
  let depth = 0;
122349
- for (; i10 < path51.length; i10++) {
122350
- const c10 = path51.charCodeAt(i10);
122635
+ for (; i10 < path52.length; i10++) {
122636
+ const c10 = path52.charCodeAt(i10);
122351
122637
  if (c10 === 92) i10++;
122352
122638
  else if (c10 === 40) depth++;
122353
122639
  else if (c10 === 41 && depth > 0) depth--;
122354
122640
  else if (c10 === 123 && depth === 0) break;
122355
122641
  }
122356
- if (i10 >= path51.length) return;
122642
+ if (i10 >= path52.length) return;
122357
122643
  let j10 = i10 + 1;
122358
122644
  depth = 0;
122359
- for (; j10 < path51.length; j10++) {
122360
- const c10 = path51.charCodeAt(j10);
122645
+ for (; j10 < path52.length; j10++) {
122646
+ const c10 = path52.charCodeAt(j10);
122361
122647
  if (c10 === 92) j10++;
122362
122648
  else if (c10 === 40) depth++;
122363
122649
  else if (c10 === 41 && depth > 0) depth--;
122364
122650
  else if (c10 === 125 && depth === 0) break;
122365
122651
  }
122366
- if (j10 >= path51.length) return;
122367
- const mod = path51[j10 + 1];
122652
+ if (j10 >= path52.length) return;
122653
+ const mod = path52[j10 + 1];
122368
122654
  const hasMod = mod === "?" || mod === "+" || mod === "*";
122369
122655
  return [
122370
- path51.slice(0, i10),
122371
- path51.slice(i10 + 1, j10),
122372
- path51.slice(j10 + (hasMod ? 2 : 1)),
122656
+ path52.slice(0, i10),
122657
+ path52.slice(i10 + 1, j10),
122658
+ path52.slice(j10 + (hasMod ? 2 : 1)),
122373
122659
  hasMod ? mod : void 0
122374
122660
  ];
122375
122661
  }
122376
- function expandGroupDelimiters(path51) {
122377
- if (!path51.includes("{")) return;
122378
- const group = scanFirstGroup(path51);
122662
+ function expandGroupDelimiters(path52) {
122663
+ if (!path52.includes("{")) return;
122664
+ const group = scanFirstGroup(path52);
122379
122665
  if (!group) return;
122380
122666
  const [pre2, body, suf, mod] = group;
122381
122667
  if (!mod) return [pre2 + body + suf];
@@ -122445,9 +122731,9 @@ function replaceSegmentWildcards(segment, unnamedStart, toGroupKey = toUnnamedGr
122445
122731
  }
122446
122732
  return [replaced, nextIndex];
122447
122733
  }
122448
- function encodeEscapes(path51) {
122449
- if (!path51.includes("\\")) return path51;
122450
- return path51.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
122734
+ function encodeEscapes(path52) {
122735
+ if (!path52.includes("\\")) return path52;
122736
+ return path52.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
122451
122737
  }
122452
122738
  function segmentKey(segment) {
122453
122739
  if (segment.startsWith("**")) return 2;
@@ -122476,22 +122762,22 @@ function expandModifiers(segments) {
122476
122762
  return m10[2] === "+" ? [wc2] : [wc2, without];
122477
122763
  }
122478
122764
  }
122479
- function normalizePath(path51) {
122480
- if (!path51.includes("/.")) return path51;
122765
+ function normalizePath(path52) {
122766
+ if (!path52.includes("/.")) return path52;
122481
122767
  const r10 = [];
122482
- for (const s of path51.split("/")) if (s === ".") continue;
122768
+ for (const s of path52.split("/")) if (s === ".") continue;
122483
122769
  else if (s === ".." && r10.length > 1) r10.pop();
122484
122770
  else r10.push(s);
122485
122771
  return r10.join("/") || "/";
122486
122772
  }
122487
- function splitPath(path51) {
122488
- const s = path51.split("/");
122773
+ function splitPath(path52) {
122774
+ const s = path52.split("/");
122489
122775
  s.shift();
122490
122776
  if (s[s.length - 1] === "") s.pop();
122491
122777
  return s;
122492
122778
  }
122493
- function splitRoute(path51) {
122494
- const s = splitPath(path51);
122779
+ function splitRoute(path52) {
122780
+ const s = splitPath(path52);
122495
122781
  while (s[s.length - 1] === "") s.pop();
122496
122782
  return s;
122497
122783
  }
@@ -122507,16 +122793,16 @@ function getMatchParams(segments, paramsMap) {
122507
122793
  }
122508
122794
  return params;
122509
122795
  }
122510
- function addRoute(ctx, method = "", path51, data) {
122796
+ function addRoute(ctx, method = "", path52, data) {
122511
122797
  method = method.toUpperCase();
122512
- if (path51.charCodeAt(0) !== 47) path51 = `/${path51}`;
122513
- const groupExpanded = expandGroupDelimiters(path51);
122798
+ if (path52.charCodeAt(0) !== 47) path52 = `/${path52}`;
122799
+ const groupExpanded = expandGroupDelimiters(path52);
122514
122800
  if (groupExpanded) {
122515
122801
  for (const expandedPath of groupExpanded) addRoute(ctx, method, expandedPath, data);
122516
122802
  return;
122517
122803
  }
122518
- path51 = encodeEscapes(path51);
122519
- const segments = splitRoute(path51);
122804
+ path52 = encodeEscapes(path52);
122805
+ const segments = splitRoute(path52);
122520
122806
  const expanded = expandModifiers(segments);
122521
122807
  if (expanded) {
122522
122808
  for (const p of expanded) addRoute(ctx, method, p, data);
@@ -122607,15 +122893,15 @@ function getParamRegexp(segment, unnamedStart = 0) {
122607
122893
  const regex = _s2.replace(/:([\w-]+)(?:\(([^)]*)\))?/g, (_, id2, p) => `(?<${toGroupName(id2)}>${p || "[^/]+"})`).replace(/\((?![?<])/g, () => `(?<${toUnnamedGroupKey(_i2++)}>`).replace(/\uFFFE(.)/g, (_, c10) => /[.*+?^${}()|[\]\\]/.test(c10) ? `\\${c10}` : c10);
122608
122894
  return [new RegExp(`^${regex}$`), _i2];
122609
122895
  }
122610
- function findRoute(ctx, method = "", path51, opts) {
122611
- if (opts?.normalize) path51 = normalizePath(path51);
122612
- if (path51.charCodeAt(path51.length - 1) === 47) path51 = path51.slice(0, -1);
122613
- const staticNode = ctx.static[path51];
122896
+ function findRoute(ctx, method = "", path52, opts) {
122897
+ if (opts?.normalize) path52 = normalizePath(path52);
122898
+ if (path52.charCodeAt(path52.length - 1) === 47) path52 = path52.slice(0, -1);
122899
+ const staticNode = ctx.static[path52];
122614
122900
  if (staticNode && staticNode.methods) {
122615
122901
  const staticMatch = staticNode.methods[method] || staticNode.methods[""];
122616
122902
  if (staticMatch !== void 0) return staticMatch[0];
122617
122903
  }
122618
- const segments = splitPath(path51);
122904
+ const segments = splitPath(path52);
122619
122905
  const match = _lookupTree(ctx.root, method, segments, 0);
122620
122906
  if (match === void 0) return;
122621
122907
  if (opts?.params === false) return match;
@@ -122815,7 +123101,7 @@ var OpenAPIMatcher = class {
122815
123101
  this.rootRouter = router;
122816
123102
  this.index(router);
122817
123103
  }
122818
- index(router, path51 = []) {
123104
+ index(router, path52 = []) {
122819
123105
  const lazyResults = walkProcedureContractsSync(router, (contract, path210) => {
122820
123106
  if (!value(this.filter, contract, path210)) {
122821
123107
  return;
@@ -122830,7 +123116,7 @@ var OpenAPIMatcher = class {
122830
123116
  contract,
122831
123117
  procedure: contract instanceof Procedure ? contract : void 0
122832
123118
  });
122833
- }, path51);
123119
+ }, path52);
122834
123120
  for (const result of lazyResults) {
122835
123121
  const prefix = getOpenAPIMeta(result.router)?.prefix;
122836
123122
  this.pendingLazyRouters.add({
@@ -122917,20 +123203,20 @@ var OpenAPIMatcher = class {
122917
123203
  return entry.procedure;
122918
123204
  }
122919
123205
  };
122920
- function toRou3Pattern(path51) {
122921
- const params = getDynamicPathParams(path51);
123206
+ function toRou3Pattern(path52) {
123207
+ const params = getDynamicPathParams(path52);
122922
123208
  if (!params?.length) {
122923
- return path51;
123209
+ return path52;
122924
123210
  }
122925
123211
  for (let i10 = params.length - 1; i10 >= 0; i10--) {
122926
123212
  const param = params[i10];
122927
123213
  const pattern = param.allowsSlash ? `**:${param.parameterName}` : `:${param.parameterName}`;
122928
- path51 = path51.slice(0, param.startIndex) + pattern + path51.slice(param.startIndex + param.segment.length);
123214
+ path52 = path52.slice(0, param.startIndex) + pattern + path52.slice(param.startIndex + param.segment.length);
122929
123215
  }
122930
- return path51;
123216
+ return path52;
122931
123217
  }
122932
- function toRou3PrefixMatcher(path51) {
122933
- const pattern = toRou3Pattern(path51);
123218
+ function toRou3PrefixMatcher(path52) {
123219
+ const pattern = toRou3Pattern(path52);
122934
123220
  return routeToRegExp(pattern === "/" ? "/**" : `${pattern}/**`);
122935
123221
  }
122936
123222
  function decodeParams(params) {
@@ -123009,7 +123295,7 @@ var OpenAPIHandlerCodecCore = class {
123009
123295
  /**
123010
123296
  * @throws {TypeError} If `outputStructure` is "detailed" and the output doesn't match the expected structure.
123011
123297
  */
123012
- encodeOutput(output2, procedure, path51) {
123298
+ encodeOutput(output2, procedure, path52) {
123013
123299
  const meta3 = getOpenAPIMeta(procedure);
123014
123300
  const successStatus = meta3?.successStatus ?? DEFAULT_SUCCESS_STATUS;
123015
123301
  const outputStructure = meta3?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
@@ -123022,7 +123308,7 @@ var OpenAPIHandlerCodecCore = class {
123022
123308
  }
123023
123309
  if (!isValidDetailedOutput(output2)) {
123024
123310
  throw new TypeError(`
123025
- Invalid "detailed" output structure returned by procedure (${path51.join(".")}):
123311
+ Invalid "detailed" output structure returned by procedure (${path52.join(".")}):
123026
123312
  \u2022 Expected an object with optional properties:
123027
123313
  - status (number <400)
123028
123314
  - headers (object)
@@ -123410,7 +123696,8 @@ var IdentityValueSchema = external_exports.strictObject({
123410
123696
  name: external_exports.string(),
123411
123697
  defaultConfigProfile: external_exports.string().optional(),
123412
123698
  allowAmbientCredential: external_exports.boolean(),
123413
- credential: CredentialSummarySchema2.optional()
123699
+ credential: CredentialSummarySchema2.optional(),
123700
+ anchors: external_exports.array(AnchorSchema).optional()
123414
123701
  });
123415
123702
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
123416
123703
  var ProviderValueSchema = external_exports.strictObject({
@@ -123428,7 +123715,9 @@ var ConfigIdentitySetInputSchema = external_exports.strictObject({
123428
123715
  name: external_exports.string().min(1),
123429
123716
  defaultConfigProfile: external_exports.union([external_exports.string().min(1), external_exports.literal(false)]).optional(),
123430
123717
  allowAmbientCredential: external_exports.boolean().optional(),
123431
- credential: external_exports.union([external_exports.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional()
123718
+ credential: external_exports.union([external_exports.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
123719
+ /** `false` removes the anchors; a list replaces them. */
123720
+ anchors: external_exports.union([external_exports.literal(false), external_exports.array(AnchorSchema).min(1)]).optional()
123432
123721
  });
123433
123722
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
123434
123723
  var ConfigIdentityRemoveInputSchema = external_exports.strictObject({ name: external_exports.string().min(1), confirm: RemovalConfirmationSchema });
@@ -123549,7 +123838,8 @@ function identityValue(name, paths) {
123549
123838
  name: identity.name,
123550
123839
  ...identity.defaultConfigProfile === void 0 ? {} : { defaultConfigProfile: identity.defaultConfigProfile },
123551
123840
  allowAmbientCredential: identity.allowAmbientCredential,
123552
- ...identity.credential === void 0 ? {} : { credential: summariseCredential(identity.credential) }
123841
+ ...identity.credential === void 0 ? {} : { credential: summariseCredential(identity.credential) },
123842
+ ...identity.anchors === void 0 ? {} : { anchors: identity.anchors }
123553
123843
  };
123554
123844
  }
123555
123845
  function providerValue(name, provider) {
@@ -123570,7 +123860,7 @@ function profileValue(name, paths) {
123570
123860
  function createConfigApiRouter(deps) {
123571
123861
  const authed = doorApiAuth(deps.expectedToken);
123572
123862
  const { paths } = deps;
123573
- const route = (path51, summary) => authed.meta(openapi({ method: "POST", path: path51, summary, tags: [CONFIG_API_TAG] }));
123863
+ const route = (path52, summary) => authed.meta(openapi({ method: "POST", path: path52, summary, tags: [CONFIG_API_TAG] }));
123574
123864
  return {
123575
123865
  config: {
123576
123866
  identity: {
@@ -123580,9 +123870,9 @@ function createConfigApiRouter(deps) {
123580
123870
  return { action: "created", kind: "identity", name: input2.name, value: identityValue(input2.name, paths) };
123581
123871
  })
123582
123872
  ),
123583
- set: route("/rest/config/identity/set", "Update an identity's default profile, ambient-credential setting or credential").input(ConfigIdentitySetInputSchema).output(ConfigIdentitySetOutputSchema).handler(
123873
+ set: route("/rest/config/identity/set", "Update an identity's default profile, ambient-credential setting, credential or anchors").input(ConfigIdentitySetInputSchema).output(ConfigIdentitySetOutputSchema).handler(
123584
123874
  ({ input: input2 }) => guarded(() => {
123585
- requireChange(input2.defaultConfigProfile !== void 0 || input2.allowAmbientCredential !== void 0 || input2.credential !== void 0, "defaultConfigProfile, allowAmbientCredential or credential");
123875
+ requireChange(input2.defaultConfigProfile !== void 0 || input2.allowAmbientCredential !== void 0 || input2.credential !== void 0 || input2.anchors !== void 0, "defaultConfigProfile, allowAmbientCredential, credential or anchors");
123586
123876
  if (!identityExists(paths, input2.name)) {
123587
123877
  throw new IdentityNotFoundError(input2.name);
123588
123878
  }
@@ -123607,6 +123897,9 @@ function createConfigApiRouter(deps) {
123607
123897
  };
123608
123898
  setIdentityCredential(paths, input2.name, change);
123609
123899
  }
123900
+ if (input2.anchors !== void 0) {
123901
+ setIdentityAnchors(paths, input2.name, input2.anchors === false ? void 0 : input2.anchors);
123902
+ }
123610
123903
  return { action: "updated", kind: "identity", name: input2.name, value: identityValue(input2.name, paths) };
123611
123904
  })
123612
123905
  ),
@@ -123922,7 +124215,7 @@ function createLifecycleApiRouter(deps) {
123922
124215
  init_cliError();
123923
124216
 
123924
124217
  // src/frontdoor/launchSchemas.ts
123925
- var import_node_path42 = __toESM(require("node:path"), 1);
124218
+ var import_node_path43 = __toESM(require("node:path"), 1);
123926
124219
  init_zod();
123927
124220
  init_claudeVersion();
123928
124221
  init_identity();
@@ -123932,7 +124225,7 @@ var LaunchResolveInputSchema = external_exports.strictObject({
123932
124225
  argv: external_exports.readonly(external_exports.array(external_exports.string())).optional(),
123933
124226
  /** The launch's inherited environment. Absent means an empty one: the door's own environment is never a substitute for the caller's, so a caller that wants `AGENT_SHIM_*` switches or a `CLAUDE_CONFIG_DIR` considered names them here. Values are read, never reported. */
123934
124227
  env: external_exports.record(external_exports.string(), external_exports.string()).optional()
123935
- }).refine((input2) => import_node_path42.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
124228
+ }).refine((input2) => import_node_path43.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
123936
124229
  var LaunchPoolDecisionSchema = external_exports.strictObject({
123937
124230
  name: external_exports.string(),
123938
124231
  reasons: external_exports.readonly(external_exports.array(external_exports.string())),
@@ -124208,11 +124501,11 @@ function rcFanoutOnDoorHub(fanout, hub) {
124208
124501
  // src/frontdoor/quotaExpiringEvents.ts
124209
124502
  init_schema2();
124210
124503
  var MS_PER_HOUR4 = 36e5;
124211
- var MS_PER_DAY3 = 864e5;
124504
+ var MS_PER_DAY4 = 864e5;
124212
124505
  var FIVE_HOUR_WINDOW_HOURS = 5;
124213
124506
  var SEVEN_DAY_WINDOW_DAYS = 7;
124214
124507
  var FIVE_HOUR_WINDOW_MS2 = FIVE_HOUR_WINDOW_HOURS * MS_PER_HOUR4;
124215
- var SEVEN_DAY_WINDOW_MS2 = SEVEN_DAY_WINDOW_DAYS * MS_PER_DAY3;
124508
+ var SEVEN_DAY_WINDOW_MS2 = SEVEN_DAY_WINDOW_DAYS * MS_PER_DAY4;
124216
124509
  var FINAL_SPAN_DENOMINATOR = 30;
124217
124510
  var QUOTA_EXPIRING_WINDOW_FRACTION = 1 / FINAL_SPAN_DENOMINATOR;
124218
124511
  function createQuotaExpiringPublisher(hub, deps) {
@@ -125010,17 +125303,17 @@ function unifiedQuotaHeaders(upstream, rejected, quotaError) {
125010
125303
  }
125011
125304
  return headers;
125012
125305
  }
125013
- var MS_PER_SECOND7 = 1e3;
125306
+ var MS_PER_SECOND8 = 1e3;
125014
125307
  function buildUsageSnapshot(upstream, quotaError, nowMs) {
125015
125308
  const used7 = upstream.get("x-codex-primary-used-percent") ?? (quotaError === void 0 ? null : EXHAUSTED_PERCENT);
125016
125309
  const reset7 = upstream.get("x-codex-primary-reset-at") ?? (quotaError?.resets_at === void 0 ? null : String(quotaError.resets_at));
125017
- const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND7).toISOString() } : void 0;
125310
+ const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND8).toISOString() } : void 0;
125018
125311
  let fiveHour;
125019
125312
  if (Number(upstream.get("x-codex-secondary-window-minutes")) > 0) {
125020
125313
  const used5 = upstream.get("x-codex-secondary-used-percent");
125021
125314
  const reset5 = upstream.get("x-codex-secondary-reset-at");
125022
125315
  if (used5 !== null && reset5 !== null) {
125023
- fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND7).toISOString() };
125316
+ fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND8).toISOString() };
125024
125317
  }
125025
125318
  }
125026
125319
  if (sevenDay === void 0 && fiveHour === void 0) {
@@ -125429,8 +125722,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
125429
125722
  request7.body.resume();
125430
125723
  return;
125431
125724
  }
125432
- const path51 = new URL(request7.url, "http://127.0.0.1").pathname;
125433
- const translated = { method: request7.method, path: path51, body, signal: request7.signal };
125725
+ const path52 = new URL(request7.url, "http://127.0.0.1").pathname;
125726
+ const translated = { method: request7.method, path: path52, body, signal: request7.signal };
125434
125727
  const routed = await route(translated);
125435
125728
  if (request7.signal.aborted) {
125436
125729
  return;
@@ -125464,7 +125757,7 @@ function createPassthroughRoute(name, target) {
125464
125757
  headroomUpstream: target.headroomUpstream,
125465
125758
  serve: async (request7, response) => {
125466
125759
  const incoming = new URL(request7.url, "http://127.0.0.1");
125467
- const path51 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
125760
+ const path52 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
125468
125761
  const headers = forwardableHeaders(request7.headers);
125469
125762
  delete headers.host;
125470
125763
  await new Promise((resolve2) => {
@@ -125472,7 +125765,7 @@ function createPassthroughRoute(name, target) {
125472
125765
  host: base.hostname,
125473
125766
  port: base.port === "" ? void 0 : Number(base.port),
125474
125767
  method: request7.method,
125475
- path: `${basePath}${path51}${incoming.search}`,
125768
+ path: `${basePath}${path52}${incoming.search}`,
125476
125769
  headers,
125477
125770
  agent
125478
125771
  };
@@ -125605,7 +125898,7 @@ async function scanRequestHead(request7, wholeBody = false) {
125605
125898
 
125606
125899
  // src/frontdoor/providerRoute.ts
125607
125900
  function createProviderRouteResolver(deps) {
125608
- const isRcSelfHostPath = (path51) => path51 === "/v1/code/sessions" || path51.startsWith("/v1/code/sessions/") || path51 === "/v1/sessions" || path51.startsWith("/v1/sessions/");
125901
+ const isRcSelfHostPath = (path52) => path52 === "/v1/code/sessions" || path52.startsWith("/v1/code/sessions/") || path52 === "/v1/sessions" || path52.startsWith("/v1/sessions/");
125609
125902
  const oauthRoute = createPassthroughRoute("anthropic", { baseUrl: `https://${CONNECT_INTERCEPT_HOST}:${String(HTTPS_PORT)}`, stripPrefix: void 0, headroomUpstream: void 0 });
125610
125903
  const passthroughByTarget = /* @__PURE__ */ new Map();
125611
125904
  const passthroughFor = (name, target) => {
@@ -125619,16 +125912,16 @@ function createProviderRouteResolver(deps) {
125619
125912
  return route;
125620
125913
  };
125621
125914
  const resolve2 = (request7) => {
125622
- const path51 = new URL(request7.url, "http://127.0.0.1").pathname;
125623
- const scoped = parseProviderPath(path51);
125915
+ const path52 = new URL(request7.url, "http://127.0.0.1").pathname;
125916
+ const scoped = parseProviderPath(path52);
125624
125917
  if (scoped === void 0) {
125625
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path51)) {
125918
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path52)) {
125626
125919
  return { ok: true, route: deps.rcSelfHostRoute };
125627
125920
  }
125628
- if (request7.session.provider !== void 0 && path51.startsWith("/v1/") && !isRcSelfHostPath(path51)) {
125921
+ if (request7.session.provider !== void 0 && path52.startsWith("/v1/") && !isRcSelfHostPath(path52)) {
125629
125922
  return resolve2({ ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` });
125630
125923
  }
125631
- return path51.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path51}` };
125924
+ return path52.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path52}` };
125632
125925
  }
125633
125926
  const { provider } = scoped;
125634
125927
  let definition;
@@ -125681,8 +125974,8 @@ function createProviderRouteResolver(deps) {
125681
125974
  let replay;
125682
125975
  const visited = /* @__PURE__ */ new Set();
125683
125976
  for (; ; ) {
125684
- const path51 = new URL(current.url, "http://127.0.0.1").pathname;
125685
- const scoped = parseProviderPath(path51);
125977
+ const path52 = new URL(current.url, "http://127.0.0.1").pathname;
125978
+ const scoped = parseProviderPath(path52);
125686
125979
  const providerName = scoped?.provider ?? current.session.provider;
125687
125980
  if (providerName !== void 0 && visited.has(providerName)) {
125688
125981
  return { ok: false, status: HTTP_STATUS.internalServerError, message: `provider routing cycle: ${[...visited, providerName].join(" -> ")}` };
@@ -125740,7 +126033,7 @@ function createProviderRouteResolver(deps) {
125740
126033
  const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
125741
126034
  replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
125742
126035
  }
125743
- const rest = scoped === void 0 ? path51 : path51.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
126036
+ const rest = scoped === void 0 ? path52 : path52.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
125744
126037
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
125745
126038
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
125746
126039
  }
@@ -125847,14 +126140,14 @@ function createRcLiveUsage(deps) {
125847
126140
  }
125848
126141
 
125849
126142
  // src/frontdoor/rcSelfHostMint.ts
125850
- var import_node_path43 = __toESM(require("node:path"), 1);
126143
+ var import_node_path44 = __toESM(require("node:path"), 1);
125851
126144
  init_account();
125852
126145
 
125853
126146
  // src/frontdoor/rcSelfHostLocal.ts
125854
126147
  var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
125855
126148
  var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
125856
126149
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
125857
- var MS_PER_SECOND8 = 1e3;
126150
+ var MS_PER_SECOND9 = 1e3;
125858
126151
  var HTTP_SERVICE_UNAVAILABLE = 503;
125859
126152
  function isRecord6(value2) {
125860
126153
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
@@ -125910,7 +126203,7 @@ function createRcSelfHostLocal(deps) {
125910
126203
  }
125911
126204
  if (method === "POST" && pathname.startsWith("/api/eval/")) {
125912
126205
  await deps.readBody(request7, CONTROL_BODY_CAP_BYTES);
125913
- answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND8) });
126206
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND9) });
125914
126207
  return true;
125915
126208
  }
125916
126209
  if (method === "GET" && pathname === "/api/oauth/profile") {
@@ -125977,7 +126270,7 @@ function readJsonObject(fs22, file2) {
125977
126270
  return isRecord7(parsed) ? parsed : void 0;
125978
126271
  }
125979
126272
  function readRcSelfHostRecord(fs22, frontdoorDir) {
125980
- const parsed = readJsonObject(fs22, import_node_path43.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
126273
+ const parsed = readJsonObject(fs22, import_node_path44.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
125981
126274
  if (parsed === void 0) {
125982
126275
  return void 0;
125983
126276
  }
@@ -125991,11 +126284,11 @@ function mintRcSelfHostCredential(deps) {
125991
126284
  if (!isIdentityName(deps.identity)) {
125992
126285
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
125993
126286
  }
125994
- const identityDir = import_node_path43.default.join(deps.identitiesDir, deps.identity);
125995
- const credentialsFile = import_node_path43.default.join(identityDir, CREDENTIALS_FILE2);
125996
- const claudeJsonFile = import_node_path43.default.join(identityDir, CLAUDE_JSON2);
125997
- const recordDir = import_node_path43.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
125998
- const recordFile = import_node_path43.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
126287
+ const identityDir = import_node_path44.default.join(deps.identitiesDir, deps.identity);
126288
+ const credentialsFile = import_node_path44.default.join(identityDir, CREDENTIALS_FILE2);
126289
+ const claudeJsonFile = import_node_path44.default.join(identityDir, CLAUDE_JSON2);
126290
+ const recordDir = import_node_path44.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
126291
+ const recordFile = import_node_path44.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
125999
126292
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
126000
126293
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
126001
126294
  const existingOauth = isRecord7(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -126011,7 +126304,7 @@ function mintRcSelfHostCredential(deps) {
126011
126304
  const organizationUuid = deps.newUuid();
126012
126305
  const accountUuid = deps.newUuid();
126013
126306
  const mintedAt = new Date(deps.now()).toISOString();
126014
- deps.fs.mkdirPrivate(import_node_path43.default.dirname(credentialsFile));
126307
+ deps.fs.mkdirPrivate(import_node_path44.default.dirname(credentialsFile));
126015
126308
  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)}
126016
126309
  `);
126017
126310
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -126094,12 +126387,12 @@ function eventExcerpt(text2) {
126094
126387
  return text2.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS ? text2 : `${text2.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS)}...`;
126095
126388
  }
126096
126389
  var PERCENT_SCALE = 100;
126097
- var MS_PER_SECOND9 = 1e3;
126390
+ var MS_PER_SECOND10 = 1e3;
126098
126391
  function percentOf(fraction) {
126099
126392
  return `${String(Math.round(fraction * PERCENT_SCALE))}%`;
126100
126393
  }
126101
126394
  function resetInstantOf(epochSeconds) {
126102
- return new Date(epochSeconds * MS_PER_SECOND9).toISOString();
126395
+ return new Date(epochSeconds * MS_PER_SECOND10).toISOString();
126103
126396
  }
126104
126397
  function formatRcRateLimitInfo(info) {
126105
126398
  const parts = [info.status];
@@ -126398,7 +126691,7 @@ function registerRcCommand(frontdoor, paths) {
126398
126691
  }
126399
126692
 
126400
126693
  // src/frontdoor/rcCredentialStore.ts
126401
- var import_node_path44 = __toESM(require("node:path"), 1);
126694
+ var import_node_path45 = __toESM(require("node:path"), 1);
126402
126695
  function isSafeSessionId(sessionId) {
126403
126696
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
126404
126697
  }
@@ -126424,7 +126717,7 @@ function sequenceNumOfJson(value2) {
126424
126717
  }
126425
126718
  function createRcCredentialStore(fs22, dir) {
126426
126719
  fs22.mkdirPrivate(dir);
126427
- const fileFor = (sessionId) => import_node_path44.default.join(dir, `${sessionId}.json`);
126720
+ const fileFor = (sessionId) => import_node_path45.default.join(dir, `${sessionId}.json`);
126428
126721
  const readParsed = (sessionId) => {
126429
126722
  const raw = fs22.readFileUtf8(fileFor(sessionId));
126430
126723
  if (raw === void 0) {
@@ -127534,7 +127827,7 @@ var RC_COMPAT_SESSIONS_PATH = "/v1/sessions";
127534
127827
  var RC_SESSION_ID_PREFIX2 = "cse_";
127535
127828
  var RC_SELF_HOST_API_BASE_URL = "https://api.anthropic.com";
127536
127829
  var HTTP_CONFLICT = 409;
127537
- var MS_PER_SECOND10 = 1e3;
127830
+ var MS_PER_SECOND11 = 1e3;
127538
127831
  var HTTP_SERVICE_UNAVAILABLE2 = 503;
127539
127832
  var RC_SELF_HOST_WORKER_JWT_TTL_SECONDS = 46800;
127540
127833
  var RC_SELF_HOST_KEEPALIVE_MS = 15e3;
@@ -127634,7 +127927,7 @@ function parseJsonObject5(body) {
127634
127927
  function mintWorkerJwt(randomToken, issuedAt) {
127635
127928
  const encode3 = (value2) => Buffer.from(JSON.stringify(value2), "utf8").toString("base64url");
127636
127929
  const header = encode3({ alg: "HS256", typ: "JWT" });
127637
- const payload = encode3({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND10) / MS_PER_SECOND10), iat: Math.floor(issuedAt / MS_PER_SECOND10) });
127930
+ const payload = encode3({ exp: Math.floor((issuedAt + RC_SELF_HOST_WORKER_JWT_TTL_SECONDS * MS_PER_SECOND11) / MS_PER_SECOND11), iat: Math.floor(issuedAt / MS_PER_SECOND11) });
127638
127931
  return `${header}.${payload}.${Buffer.from(randomToken(), "utf8").toString("base64url")}`;
127639
127932
  }
127640
127933
  function createRcSelfHostSurface(deps) {
@@ -128705,6 +128998,28 @@ function realFrontDoorSupervisorPorts(paths) {
128705
128998
  const pools = readPools(paths);
128706
128999
  void refreshStalePoolMembers({ poolNames: Object.keys(pools), pools, loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now()), refresher: anthropicRefresher });
128707
129000
  }, ANTHROPIC_USAGE_FRESHNESS_MS).unref();
129001
+ const windowOpener = createRealWindowOpener({ paths, cwd: process.cwd(), spawnDaemon: spawnDetachedSupervisor });
129002
+ let keeperRunning = false;
129003
+ setInterval(() => {
129004
+ if (keeperRunning) {
129005
+ return;
129006
+ }
129007
+ keeperRunning = true;
129008
+ void runWindowKeeper({
129009
+ fs: realFarmFs,
129010
+ stampsFile: paths.usageAnchorsFile,
129011
+ nowMs: () => Date.now(),
129012
+ timeZone: machineTimeZone(),
129013
+ anchored: () => listAnchoredIdentities(paths),
129014
+ snapshot: (identity) => readUsageSnapshot(realFarmFs, paths.usageSnapshotsDir, identity),
129015
+ open: windowOpener,
129016
+ log
129017
+ }).catch((error63) => {
129018
+ log(`window keeper failed: ${error63 instanceof Error ? error63.message : String(error63)}`);
129019
+ }).finally(() => {
129020
+ keeperRunning = false;
129021
+ });
129022
+ }, ANTHROPIC_USAGE_FRESHNESS_MS).unref();
128708
129023
  const usageMiddleware = createUsageMiddleware({
128709
129024
  record: withQuotaRefresh(usageStore.record, quotaRefresher),
128710
129025
  defer: (task) => {
@@ -128848,7 +129163,7 @@ function realFrontDoorSupervisorPorts(paths) {
128848
129163
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
128849
129164
  const capture = captureFromEnv(process.env, paths.logsDir);
128850
129165
  if (capture !== void 0) {
128851
- log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path45.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
129166
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path46.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
128852
129167
  }
128853
129168
  if (rcSelfHostSurface !== void 0) {
128854
129169
  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");
@@ -130985,8 +131300,8 @@ function getErrorMap2() {
130985
131300
 
130986
131301
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/helpers/parseUtil.js
130987
131302
  var makeIssue = (params) => {
130988
- const { data, path: path51, errorMaps, issueData } = params;
130989
- const fullPath = [...path51, ...issueData.path || []];
131303
+ const { data, path: path52, errorMaps, issueData } = params;
131304
+ const fullPath = [...path52, ...issueData.path || []];
130990
131305
  const fullIssue = {
130991
131306
  ...issueData,
130992
131307
  path: fullPath
@@ -131101,11 +131416,11 @@ var errorUtil;
131101
131416
 
131102
131417
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/types.js
131103
131418
  var ParseInputLazyPath = class {
131104
- constructor(parent, value2, path51, key) {
131419
+ constructor(parent, value2, path52, key) {
131105
131420
  this._cachedPath = [];
131106
131421
  this.parent = parent;
131107
131422
  this.data = value2;
131108
- this._path = path51;
131423
+ this._path = path52;
131109
131424
  this._key = key;
131110
131425
  }
131111
131426
  get path() {
@@ -134668,11 +134983,11 @@ function normalizeObjectSchema(schema) {
134668
134983
  }
134669
134984
  return void 0;
134670
134985
  }
134671
- function getDotPath(path51) {
134672
- if (path51.length === 0) {
134986
+ function getDotPath(path52) {
134987
+ if (path52.length === 0) {
134673
134988
  return "object root";
134674
134989
  }
134675
- return path51.reduce((acc, seg, index) => {
134990
+ return path52.reduce((acc, seg, index) => {
134676
134991
  if (index === 0) {
134677
134992
  return String(seg);
134678
134993
  }
@@ -138715,7 +139030,7 @@ async function serveMcp(mcp, transport, options = {}) {
138715
139030
 
138716
139031
  // src/mcp/permissions.ts
138717
139032
  var import_node_fs17 = __toESM(require("node:fs"), 1);
138718
- var import_node_path46 = __toESM(require("node:path"), 1);
139033
+ var import_node_path47 = __toESM(require("node:path"), 1);
138719
139034
  init_zod();
138720
139035
  init_store();
138721
139036
  var StoredMcpPermissionsSchema = external_exports.strictObject({
@@ -138735,10 +139050,10 @@ function effectiveMcpPermissions(flags, stored) {
138735
139050
  return { writes: flags.writes || stored.writes, remoteControl: flags.remoteControl || stored.remoteControl };
138736
139051
  }
138737
139052
  function watchMcpPermissions(paths, onChange) {
138738
- const directory = import_node_path46.default.dirname(paths.mcpPermissionsFile);
139053
+ const directory = import_node_path47.default.dirname(paths.mcpPermissionsFile);
138739
139054
  import_node_fs17.default.mkdirSync(directory, { recursive: true });
138740
139055
  const watcher = import_node_fs17.default.watch(directory, (_event, filename) => {
138741
- if (filename === null || filename === import_node_path46.default.basename(paths.mcpPermissionsFile)) {
139056
+ if (filename === null || filename === import_node_path47.default.basename(paths.mcpPermissionsFile)) {
138742
139057
  onChange();
138743
139058
  }
138744
139059
  });
@@ -139047,16 +139362,16 @@ init_credentialCache();
139047
139362
 
139048
139363
  // src/identityToken.ts
139049
139364
  var import_node_fs18 = __toESM(require("node:fs"), 1);
139050
- var import_node_path47 = __toESM(require("node:path"), 1);
139365
+ var import_node_path48 = __toESM(require("node:path"), 1);
139051
139366
  init_cliError();
139052
139367
  var TOKEN_FILE_MODE = 384;
139053
139368
  var TOKEN_DIR_MODE = 448;
139054
139369
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
139055
139370
  function identityTokenDir(paths) {
139056
- return import_node_path47.default.join(paths.root, "credentials");
139371
+ return import_node_path48.default.join(paths.root, "credentials");
139057
139372
  }
139058
139373
  function identityTokenPath(paths, identityName) {
139059
- return import_node_path47.default.join(identityTokenDir(paths), `${identityName}.token`);
139374
+ return import_node_path48.default.join(identityTokenDir(paths), `${identityName}.token`);
139060
139375
  }
139061
139376
  function storeIdentityToken(paths, identityName, raw) {
139062
139377
  const token = raw.trim();
@@ -139067,7 +139382,7 @@ function storeIdentityToken(paths, identityName, raw) {
139067
139382
  import_node_fs18.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
139068
139383
  import_node_fs18.default.chmodSync(dir, TOKEN_DIR_MODE);
139069
139384
  const target = identityTokenPath(paths, identityName);
139070
- const temp = import_node_path47.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
139385
+ const temp = import_node_path48.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
139071
139386
  import_node_fs18.default.writeFileSync(temp, `${token}
139072
139387
  `, { mode: TOKEN_FILE_MODE });
139073
139388
  import_node_fs18.default.renameSync(temp, target);
@@ -139235,7 +139550,7 @@ function registerDoctorCommand(program2, deps) {
139235
139550
  // src/headroom/commands.ts
139236
139551
  var import_node_fs19 = __toESM(require("node:fs"), 1);
139237
139552
  var import_node_http4 = __toESM(require("node:http"), 1);
139238
- var import_node_path48 = __toESM(require("node:path"), 1);
139553
+ var import_node_path49 = __toESM(require("node:path"), 1);
139239
139554
  var import_node_child_process6 = require("node:child_process");
139240
139555
  init_commandDeps();
139241
139556
  init_realFrontDoorPort();
@@ -139365,12 +139680,12 @@ function readInstalledHeadroomCommit() {
139365
139680
  if (toolDir.status !== 0) {
139366
139681
  return void 0;
139367
139682
  }
139368
- const libDir = import_node_path48.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
139683
+ const libDir = import_node_path49.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
139369
139684
  for (const python of realFarmFs.readdir(libDir)) {
139370
- const sitePackages = import_node_path48.default.join(libDir, python, "site-packages");
139685
+ const sitePackages = import_node_path49.default.join(libDir, python, "site-packages");
139371
139686
  for (const entry of realFarmFs.readdir(sitePackages)) {
139372
139687
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
139373
- const directUrl = realFarmFs.readFileUtf8(import_node_path48.default.join(sitePackages, entry, "direct_url.json"));
139688
+ const directUrl = realFarmFs.readFileUtf8(import_node_path49.default.join(sitePackages, entry, "direct_url.json"));
139374
139689
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
139375
139690
  }
139376
139691
  }
@@ -139910,7 +140225,7 @@ function registerRunCommand(program2, handler) {
139910
140225
  }
139911
140226
 
139912
140227
  // src/usage/commands.ts
139913
- var import_node_path49 = __toESM(require("node:path"), 1);
140228
+ var import_node_path50 = __toESM(require("node:path"), 1);
139914
140229
  init_commandDeps();
139915
140230
  init_realPorts();
139916
140231
  init_account();
@@ -140048,7 +140363,7 @@ function collectAccounts(fs22, paths, identity, probe) {
140048
140363
  return names.map((name) => ({
140049
140364
  identity: name,
140050
140365
  account: readAccountMetadata(fs22, paths.identitiesDir, name),
140051
- signIn: identitySignIn(fs22, probe, { farmRoot: import_node_path49.default.join(paths.identitiesDir, name), hasCredentialBlock: readIdentity(paths, name)?.credential !== void 0 }),
140366
+ signIn: identitySignIn(fs22, probe, { farmRoot: import_node_path50.default.join(paths.identitiesDir, name), hasCredentialBlock: readIdentity(paths, name)?.credential !== void 0 }),
140052
140367
  usage: readUsageSnapshot(fs22, paths.usageSnapshotsDir, name)
140053
140368
  }));
140054
140369
  }
@@ -140393,7 +140708,7 @@ async function runClaude(argvOverride) {
140393
140708
  // src/cli.ts
140394
140709
  async function main() {
140395
140710
  aliasLegacyEnv(process.env);
140396
- const invokedName = import_node_path50.default.basename(process.argv[1] ?? "agent-shim");
140711
+ const invokedName = import_node_path51.default.basename(process.argv[1] ?? "agent-shim");
140397
140712
  if (isInvokedAsClaude(invokedName)) {
140398
140713
  await runClaude();
140399
140714
  return;