claude-use 9.13.0 → 9.15.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, path54) {
322
+ if (!path54)
323
323
  return obj;
324
- return path51.reduce((acc, key) => acc?.[key], obj);
324
+ return path54.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(path54, 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(path54);
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, path54 = []) => {
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 }, [...path54, ...issue2.path]));
1112
1112
  } else if (issue2.code === "invalid_key") {
1113
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1113
+ processError({ issues: issue2.issues }, [...path54, ...issue2.path]);
1114
1114
  } else if (issue2.code === "invalid_element") {
1115
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1115
+ processError({ issues: issue2.issues }, [...path54, ...issue2.path]);
1116
1116
  } else {
1117
- const fullpath = [...path51, ...issue2.path];
1117
+ const fullpath = [...path54, ...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, path54 = []) => {
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 }, [...path54, ...issue2.path]));
1161
1161
  } else if (issue2.code === "invalid_key") {
1162
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1162
+ processError({ issues: issue2.issues }, [...path54, ...issue2.path]);
1163
1163
  } else if (issue2.code === "invalid_element") {
1164
- processError({ issues: issue2.issues }, [...path51, ...issue2.path]);
1164
+ processError({ issues: issue2.issues }, [...path54, ...issue2.path]);
1165
1165
  } else {
1166
- const fullpath = [...path51, ...issue2.path];
1166
+ const fullpath = [...path54, ...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 path54 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
+ for (const seg of path54) {
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 path54 = ref.slice(1).split("/").filter(Boolean);
19203
+ if (path54.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 (path54[0] === defsKey) {
19208
+ const key = path54[1] === void 0 ? void 0 : decodeJSONPointerSegment(path54[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 path54 = 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 = path54.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: path54.join(library, "Application Support", name),
23724
+ config: path54.join(library, "Preferences", name),
23725
+ cache: path54.join(library, "Caches", name),
23726
+ log: path54.join(library, "Logs", name),
23727
+ temp: path54.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 || path54.join(homedir, "AppData", "Roaming");
23732
+ const localAppData = env.LOCALAPPDATA || path54.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: path54.join(localAppData, name, "Data"),
23736
+ config: path54.join(appData, name, "Config"),
23737
+ cache: path54.join(localAppData, name, "Cache"),
23738
+ log: path54.join(localAppData, name, "Log"),
23739
+ temp: path54.join(tmpdir, name)
23740
23740
  };
23741
23741
  };
23742
23742
  var linux = (name) => {
23743
- const username = path51.basename(homedir);
23743
+ const username = path54.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: path54.join(env.XDG_DATA_HOME || path54.join(homedir, ".local", "share"), name),
23746
+ config: path54.join(env.XDG_CONFIG_HOME || path54.join(homedir, ".config"), name),
23747
+ cache: path54.join(env.XDG_CACHE_HOME || path54.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: path54.join(env.XDG_STATE_HOME || path54.join(homedir, ".local", "state"), name),
23750
+ temp: path54.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, path54) {
23819
+ if (typeof path54 === "string" && Object.prototype.hasOwnProperty.call(source, path54)) {
23820
+ return source[path54];
23821
23821
  }
23822
- const parsedPath = typeof path51 === "string" ? path51.split(".") : path51;
23822
+ const parsedPath = typeof path54 === "string" ? path54.split(".") : path54;
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(path54) {
23846
23846
  try {
23847
- const stat = await fs_1.promises.stat(path51);
23847
+ const stat = await fs_1.promises.stat(path54);
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(path54) {
23858
23858
  try {
23859
- const stat = fs_1.default.statSync(path51);
23859
+ const stat = fs_1.default.statSync(path54);
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((path54, i10) => `${i10 + 1}. ${path54}`).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(path54) {
24146
24146
  try {
24147
- await promises_1.default.stat(path51);
24147
+ await promises_1.default.stat(path54);
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(path54) {
24308
24308
  try {
24309
- fs_1.default.statSync(path51);
24309
+ fs_1.default.statSync(path54);
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((path54) => path54.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, WEEKDAYS, AnchorSchema, JOB_WINDOWS, JobTriggerSchema, JobTargetSchema, JobSchema, 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;
26803
26811
  var init_schema = __esm({
26804
26812
  "src/config/schema.ts"() {
26805
26813
  "use strict";
@@ -26974,6 +26982,25 @@ var init_schema = __esm({
26974
26982
  identities: external_exports.array(PoolMemberSchema).min(1).refine((members2) => new Set(members2.map(poolMemberIdentity)).size === members2.length, { message: "pool members must be unique" }),
26975
26983
  preference: PoolPreferenceSchema.optional()
26976
26984
  });
26985
+ WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
26986
+ AnchorSchema = external_exports.strictObject({
26987
+ 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"),
26988
+ time: external_exports.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "a 24-hour time such as 06:00"),
26989
+ timeZone: external_exports.string().refine(isTimeZone, "an IANA time zone such as Europe/London").optional()
26990
+ });
26991
+ JOB_WINDOWS = ["fiveHour", "sevenDay"];
26992
+ JobTriggerSchema = external_exports.union([external_exports.strictObject({ at: external_exports.array(AnchorSchema).min(1) }), external_exports.strictObject({ beforeReset: external_exports.enum(JOB_WINDOWS), lead: external_exports.string().regex(DURATION_RE) })]);
26993
+ JobTargetSchema = external_exports.union([external_exports.strictObject({ identity: IdentitySelectorSchema }), external_exports.strictObject({ pool: PoolNameSchema })]);
26994
+ JobSchema = external_exports.strictObject({
26995
+ target: JobTargetSchema,
26996
+ trigger: JobTriggerSchema,
26997
+ prompt: external_exports.string().min(1),
26998
+ /** The absolute directory the run works in. */
26999
+ cwd: external_exports.string().min(1),
27000
+ timeout: external_exports.string().regex(DURATION_RE),
27001
+ model: external_exports.string().min(1).optional(),
27002
+ allowedTools: external_exports.array(external_exports.string().min(1)).min(1).optional()
27003
+ });
26977
27004
  DirectoryRuleSchema = ConfigProfileSchema.omit({ description: true }).extend({
26978
27005
  path: external_exports.string().min(1),
26979
27006
  configProfile: external_exports.string().min(1).optional(),
@@ -27042,14 +27069,17 @@ var init_schema = __esm({
27042
27069
  headroom: HeadroomGlobalConfigSchema.optional(),
27043
27070
  frontdoor: FrontDoorGlobalConfigSchema.optional(),
27044
27071
  update: UpdateGlobalConfigSchema.optional(),
27045
- pools: external_exports.record(PoolNameSchema, PoolSchema).optional()
27072
+ pools: external_exports.record(PoolNameSchema, PoolSchema).optional(),
27073
+ jobs: external_exports.record(PoolNameSchema, JobSchema).optional()
27046
27074
  });
27047
27075
  IdentitySchema = external_exports.strictObject({
27048
27076
  $schema: external_exports.string().optional(),
27049
27077
  name: external_exports.string().min(1).regex(/^[A-Za-z0-9][A-Za-z0-9._@-]*$/),
27050
27078
  defaultConfigProfile: external_exports.string().min(1).optional(),
27051
27079
  allowAmbientCredential: external_exports.boolean().default(false),
27052
- credential: CredentialSchema.optional()
27080
+ credential: CredentialSchema.optional(),
27081
+ /** 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. */
27082
+ anchors: external_exports.array(AnchorSchema).min(1).optional()
27053
27083
  });
27054
27084
  CategoryClassificationSchema = external_exports.strictObject({
27055
27085
  $schema: external_exports.string().optional(),
@@ -28911,8 +28941,8 @@ var require_utils = __commonJS({
28911
28941
  }
28912
28942
  return output2;
28913
28943
  };
28914
- exports2.basename = (path51, { windows } = {}) => {
28915
- const segs = path51.split(windows ? /[\\/]/ : "/");
28944
+ exports2.basename = (path54, { windows } = {}) => {
28945
+ const segs = path54.split(windows ? /[\\/]/ : "/");
28916
28946
  const last = segs[segs.length - 1];
28917
28947
  if (last === "") {
28918
28948
  return segs[segs.length - 2];
@@ -32578,6 +32608,9 @@ function buildLayoutPaths(root) {
32578
32608
  usageLogDir: import_node_path19.default.join(root, "usage", "log"),
32579
32609
  usageSnapshotsDir: import_node_path19.default.join(root, "usage", "snapshots"),
32580
32610
  usagePicksFile: import_node_path19.default.join(root, "usage", "picks.json"),
32611
+ usageAnchorsFile: import_node_path19.default.join(root, "usage", "anchors.json"),
32612
+ usageJobsFile: import_node_path19.default.join(root, "usage", "jobs.json"),
32613
+ jobLogsDir: import_node_path19.default.join(root, "logs", "jobs"),
32581
32614
  mcpPermissionsFile: import_node_path19.default.join(root, "mcp", "permissions.json")
32582
32615
  };
32583
32616
  }
@@ -32595,6 +32628,47 @@ var init_paths = __esm({
32595
32628
  }
32596
32629
  });
32597
32630
 
32631
+ // src/cli/pairs.ts
32632
+ function splitCommas(input2) {
32633
+ if (input2 === "") {
32634
+ return [];
32635
+ }
32636
+ return input2.split(",");
32637
+ }
32638
+ function parsePair(input2) {
32639
+ const eqIndex = input2.indexOf("=");
32640
+ if (eqIndex === -1) {
32641
+ throw new Error(`Expected "<key>=<value>", got "${input2}" (no "=" found)`);
32642
+ }
32643
+ const key = input2.slice(0, eqIndex);
32644
+ const value2 = input2.slice(eqIndex + 1);
32645
+ if (key === "") {
32646
+ throw new Error(`Expected a non-empty key before "=" in "${input2}"`);
32647
+ }
32648
+ return { key, value: value2 };
32649
+ }
32650
+ function parseBool(input2) {
32651
+ const parsed = parseBoolWord(input2);
32652
+ if (parsed === void 0) {
32653
+ throw new Error(`Expected "true", "false", "1" or "0", got "${input2}"`);
32654
+ }
32655
+ return parsed;
32656
+ }
32657
+ function parseBoolPairList(input2) {
32658
+ const result = {};
32659
+ for (const piece of splitCommas(input2)) {
32660
+ const { key, value: value2 } = parsePair(piece);
32661
+ result[key] = parseBool(value2);
32662
+ }
32663
+ return result;
32664
+ }
32665
+ var init_pairs = __esm({
32666
+ "src/cli/pairs.ts"() {
32667
+ "use strict";
32668
+ init_bool();
32669
+ }
32670
+ });
32671
+
32598
32672
  // src/usage/schema.ts
32599
32673
  function isRateLimitHeader(name) {
32600
32674
  const lower = name.toLowerCase();
@@ -32794,7 +32868,7 @@ function epochSecondsToIso(value2) {
32794
32868
  return void 0;
32795
32869
  }
32796
32870
  const seconds = Number(value2);
32797
- return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * MS_PER_SECOND).toISOString() : void 0;
32871
+ return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * MS_PER_SECOND2).toISOString() : void 0;
32798
32872
  }
32799
32873
  function nonNegativeNumber(value2) {
32800
32874
  if (value2 === void 0 || value2.trim() === "") {
@@ -32878,7 +32952,7 @@ function retryAfterSeconds(value2, nowMs) {
32878
32952
  return seconds;
32879
32953
  }
32880
32954
  const date5 = Date.parse(value2);
32881
- return Number.isNaN(date5) ? void 0 : Math.max(0, Math.ceil((date5 - nowMs) / MS_PER_SECOND));
32955
+ return Number.isNaN(date5) ? void 0 : Math.max(0, Math.ceil((date5 - nowMs) / MS_PER_SECOND2));
32882
32956
  }
32883
32957
  function classifyLimit(params) {
32884
32958
  const { status, headers, error: error63 } = params;
@@ -32917,14 +32991,14 @@ function classifyLimit(params) {
32917
32991
  evidence
32918
32992
  };
32919
32993
  }
32920
- var TOO_MANY_REQUESTS, PAYMENT_REQUIRED, MS_PER_SECOND, UNIFIED_PREFIX, QUOTA_EXHAUSTED_ERRORS, QUOTA_EXHAUSTED_MESSAGE, EVIDENCE_TOKEN;
32994
+ var TOO_MANY_REQUESTS, PAYMENT_REQUIRED, MS_PER_SECOND2, UNIFIED_PREFIX, QUOTA_EXHAUSTED_ERRORS, QUOTA_EXHAUSTED_MESSAGE, EVIDENCE_TOKEN;
32921
32995
  var init_rateLimit = __esm({
32922
32996
  "src/usage/rateLimit.ts"() {
32923
32997
  "use strict";
32924
32998
  init_schema2();
32925
32999
  TOO_MANY_REQUESTS = 429;
32926
33000
  PAYMENT_REQUIRED = 402;
32927
- MS_PER_SECOND = 1e3;
33001
+ MS_PER_SECOND2 = 1e3;
32928
33002
  UNIFIED_PREFIX = "anthropic-ratelimit-unified-";
32929
33003
  QUOTA_EXHAUSTED_ERRORS = /* @__PURE__ */ new Set(["usage_limit_reached", "insufficient_quota", "1308", "1309", "1310", "1316", "1317", "1318", "1319", "1320", "1321"]);
32930
33004
  QUOTA_EXHAUSTED_MESSAGE = /usage limit|quota (?:exceeded|exhausted)|limit exhausted|insufficient (?:balance|credits|quota)/i;
@@ -32934,11 +33008,11 @@ var init_rateLimit = __esm({
32934
33008
 
32935
33009
  // src/usage/preflight.ts
32936
33010
  function formatAge(ms2) {
32937
- const minutes = Math.floor(ms2 / (MS_PER_SECOND2 * SECONDS_PER_MINUTE));
32938
- if (minutes < MINUTES_PER_HOUR) {
33011
+ const minutes = Math.floor(ms2 / (MS_PER_SECOND3 * SECONDS_PER_MINUTE));
33012
+ if (minutes < MINUTES_PER_HOUR2) {
32939
33013
  return `${String(Math.max(minutes, 0))}m`;
32940
33014
  }
32941
- const hours = Math.floor(minutes / MINUTES_PER_HOUR);
33015
+ const hours = Math.floor(minutes / MINUTES_PER_HOUR2);
32942
33016
  return hours < HOURS_PER_DAY ? `${String(hours)}h` : `${String(Math.floor(hours / HOURS_PER_DAY))}d`;
32943
33017
  }
32944
33018
  function effectiveWindow(window, nowMs) {
@@ -32975,14 +33049,14 @@ function quotaWarnings(snapshot, provider, nowMs) {
32975
33049
  return [`agent-shim: identity ${snapshot.identity}: the ${name} quota is ${verdict}${reset} (last seen ${age2} ago)`];
32976
33050
  });
32977
33051
  }
32978
- var MS_PER_SECOND2, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, WARNING_STATUSES;
33052
+ var MS_PER_SECOND3, SECONDS_PER_MINUTE, MINUTES_PER_HOUR2, HOURS_PER_DAY, WARNING_STATUSES;
32979
33053
  var init_preflight = __esm({
32980
33054
  "src/usage/preflight.ts"() {
32981
33055
  "use strict";
32982
33056
  init_rateLimit();
32983
- MS_PER_SECOND2 = 1e3;
33057
+ MS_PER_SECOND3 = 1e3;
32984
33058
  SECONDS_PER_MINUTE = 60;
32985
- MINUTES_PER_HOUR = 60;
33059
+ MINUTES_PER_HOUR2 = 60;
32986
33060
  HOURS_PER_DAY = 24;
32987
33061
  WARNING_STATUSES = /* @__PURE__ */ new Set(["allowed_warning", "rejected"]);
32988
33062
  }
@@ -33237,54 +33311,13 @@ var init_credential = __esm({
33237
33311
  }
33238
33312
  });
33239
33313
 
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
33314
  // package.json
33282
33315
  var package_default;
33283
33316
  var init_package = __esm({
33284
33317
  "package.json"() {
33285
33318
  package_default = {
33286
33319
  name: "claude-use",
33287
- version: "9.13.0",
33320
+ version: "9.15.0",
33288
33321
  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
33322
  license: "MIT",
33290
33323
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -33555,11 +33588,11 @@ function identifyRequest(headers) {
33555
33588
  function directOrigin(port) {
33556
33589
  return `http://127.0.0.1:${String(port)}`;
33557
33590
  }
33558
- function parseProviderPath(path51) {
33559
- if (!path51.startsWith(PROVIDER_PATH_PREFIX)) {
33591
+ function parseProviderPath(path54) {
33592
+ if (!path54.startsWith(PROVIDER_PATH_PREFIX)) {
33560
33593
  return void 0;
33561
33594
  }
33562
- const tail = path51.slice(PROVIDER_PATH_PREFIX.length);
33595
+ const tail = path54.slice(PROVIDER_PATH_PREFIX.length);
33563
33596
  const slash = tail.indexOf("/");
33564
33597
  if (slash <= 0) {
33565
33598
  return void 0;
@@ -33885,9 +33918,9 @@ function decoderFor(encoding) {
33885
33918
  return void 0;
33886
33919
  }
33887
33920
  }
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 };
33921
+ function destinationOf(path54) {
33922
+ const scoped = parseProviderPath(path54);
33923
+ return scoped === void 0 ? { provider: ANTHROPIC_PROVIDER, endpoint: path54 } : { provider: scoped.provider, endpoint: scoped.rest };
33891
33924
  }
33892
33925
  function buildRecord(event, context) {
33893
33926
  const { scan } = context;
@@ -34044,7 +34077,7 @@ function limitBlockedUntil(state, nowMs) {
34044
34077
  if (state.lastRequestAt !== void 0 && Date.parse(state.lastRequestAt) > Date.parse(limit.observedAt)) {
34045
34078
  return void 0;
34046
34079
  }
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);
34080
+ 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
34081
  return until !== void 0 && until > nowMs ? until : void 0;
34049
34082
  }
34050
34083
  function windowBlockedUntil(windows) {
@@ -34167,10 +34200,10 @@ function assessIdentity(member, nowMs) {
34167
34200
  return { candidate: { ...base, class: "unknown", reasons: ["quota windows reported no utilisation", ...windowReasons, ...planReasons] } };
34168
34201
  }
34169
34202
  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);
34203
+ const untilResetMs = basis.window.resetsAtMs === void 0 ? basis.windowMs : Math.max(basis.window.resetsAtMs - nowMs, MS_PER_SECOND4);
34171
34204
  const weeklyScore = remaining * plan.capacity / (untilResetMs / MS_PER_HOUR2);
34172
34205
  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);
34206
+ const fiveUntil = five?.resetsAtMs === void 0 ? FIVE_HOUR_WINDOW_MS : Math.max(five.resetsAtMs - nowMs, MS_PER_SECOND4);
34174
34207
  const ratio = windowRatio(member.records);
34175
34208
  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
34209
  const fiveHourLeads = fiveHourScore !== void 0 && fiveHourScore > weeklyScore;
@@ -34179,7 +34212,7 @@ function assessIdentity(member, nowMs) {
34179
34212
  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
34213
  const burn = windowBurn(member.records, "fiveHour");
34181
34214
  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);
34215
+ const sevenUntil = seven?.resetsAtMs === void 0 ? SEVEN_DAY_WINDOW_MS : Math.max(seven.resetsAtMs - nowMs, MS_PER_SECOND4);
34183
34216
  const sevenDayBurn = windowBurn(member.records, "sevenDay");
34184
34217
  return {
34185
34218
  candidate: { ...base, class: "scored", score, scoreWindow, reasons: [...fiveHourTermReasons, ...windowReasons.map((reason, index) => index === windowReasons.length - 1 ? `${reason}${observedAgo}` : reason), ...planReasons] },
@@ -34273,7 +34306,7 @@ function rankPool(input2) {
34273
34306
  ...pick2?.planReturnsAtMs === void 0 ? {} : { planReturn: { identity: pick2.identity, atMs: pick2.planReturnsAtMs } }
34274
34307
  };
34275
34308
  }
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;
34309
+ 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
34310
  var init_pick = __esm({
34278
34311
  "src/usage/pick.ts"() {
34279
34312
  "use strict";
@@ -34283,7 +34316,7 @@ var init_pick = __esm({
34283
34316
  init_preflight();
34284
34317
  init_quotaFacts();
34285
34318
  init_rateLimit();
34286
- MS_PER_SECOND3 = 1e3;
34319
+ MS_PER_SECOND4 = 1e3;
34287
34320
  MS_PER_HOUR2 = 36e5;
34288
34321
  HOURS_PER_DAY2 = 24;
34289
34322
  FIVE_HOURS = 5;
@@ -34568,7 +34601,7 @@ function createUsageStore(deps) {
34568
34601
  })
34569
34602
  };
34570
34603
  }
34571
- var import_node_path25, DAY_MS2, DAYS_IN_WEEK, USAGE_RETENTION_MS;
34604
+ var import_node_path25, DAY_MS2, DAYS_IN_WEEK2, USAGE_RETENTION_MS;
34572
34605
  var init_store2 = __esm({
34573
34606
  "src/usage/store.ts"() {
34574
34607
  "use strict";
@@ -34578,8 +34611,8 @@ var init_store2 = __esm({
34578
34611
  init_read();
34579
34612
  init_schema2();
34580
34613
  DAY_MS2 = 864e5;
34581
- DAYS_IN_WEEK = 7;
34582
- USAGE_RETENTION_MS = DAYS_IN_WEEK * DAY_MS2;
34614
+ DAYS_IN_WEEK2 = 7;
34615
+ USAGE_RETENTION_MS = DAYS_IN_WEEK2 * DAY_MS2;
34583
34616
  }
34584
34617
  });
34585
34618
 
@@ -36323,14 +36356,14 @@ var require_util2 = __commonJS({
36323
36356
  }
36324
36357
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
36325
36358
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
36326
- let path51 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36359
+ let path54 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
36327
36360
  if (origin[origin.length - 1] === "/") {
36328
36361
  origin = origin.slice(0, origin.length - 1);
36329
36362
  }
36330
- if (path51 && path51[0] !== "/") {
36331
- path51 = `/${path51}`;
36363
+ if (path54 && path54[0] !== "/") {
36364
+ path54 = `/${path54}`;
36332
36365
  }
36333
- return new URL(`${origin}${path51}`);
36366
+ return new URL(`${origin}${path54}`);
36334
36367
  }
36335
36368
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
36336
36369
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -37151,9 +37184,9 @@ var require_diagnostics = __commonJS({
37151
37184
  "undici:client:sendHeaders",
37152
37185
  (evt) => {
37153
37186
  const {
37154
- request: { method, path: path51, origin }
37187
+ request: { method, path: path54, origin }
37155
37188
  } = evt;
37156
- debugLog("sending request to %s %s%s", method, origin, path51);
37189
+ debugLog("sending request to %s %s%s", method, origin, path54);
37157
37190
  }
37158
37191
  );
37159
37192
  }
@@ -37171,14 +37204,14 @@ var require_diagnostics = __commonJS({
37171
37204
  "undici:request:headers",
37172
37205
  (evt) => {
37173
37206
  const {
37174
- request: { method, path: path51, origin },
37207
+ request: { method, path: path54, origin },
37175
37208
  response: { statusCode }
37176
37209
  } = evt;
37177
37210
  debugLog(
37178
37211
  "received response to %s %s%s - HTTP %d",
37179
37212
  method,
37180
37213
  origin,
37181
- path51,
37214
+ path54,
37182
37215
  statusCode
37183
37216
  );
37184
37217
  }
@@ -37187,23 +37220,23 @@ var require_diagnostics = __commonJS({
37187
37220
  "undici:request:trailers",
37188
37221
  (evt) => {
37189
37222
  const {
37190
- request: { method, path: path51, origin }
37223
+ request: { method, path: path54, origin }
37191
37224
  } = evt;
37192
- debugLog("trailers received from %s %s%s", method, origin, path51);
37225
+ debugLog("trailers received from %s %s%s", method, origin, path54);
37193
37226
  }
37194
37227
  );
37195
37228
  diagnosticsChannel.subscribe(
37196
37229
  "undici:request:error",
37197
37230
  (evt) => {
37198
37231
  const {
37199
- request: { method, path: path51, origin },
37232
+ request: { method, path: path54, origin },
37200
37233
  error: error63
37201
37234
  } = evt;
37202
37235
  debugLog(
37203
37236
  "request to %s %s%s errored - %s",
37204
37237
  method,
37205
37238
  origin,
37206
- path51,
37239
+ path54,
37207
37240
  error63.message
37208
37241
  );
37209
37242
  }
@@ -37318,7 +37351,7 @@ var require_request = __commonJS({
37318
37351
  var kHandler = /* @__PURE__ */ Symbol("handler");
37319
37352
  var Request2 = class {
37320
37353
  constructor(origin, {
37321
- path: path51,
37354
+ path: path54,
37322
37355
  method,
37323
37356
  body,
37324
37357
  headers,
@@ -37335,11 +37368,11 @@ var require_request = __commonJS({
37335
37368
  maxRedirections,
37336
37369
  typeOfService
37337
37370
  }, handler) {
37338
- if (typeof path51 !== "string") {
37371
+ if (typeof path54 !== "string") {
37339
37372
  throw new InvalidArgumentError2("path must be a string");
37340
- } else if (path51[0] !== "/" && !(path51.startsWith("http://") || path51.startsWith("https://")) && method !== "CONNECT") {
37373
+ } else if (path54[0] !== "/" && !(path54.startsWith("http://") || path54.startsWith("https://")) && method !== "CONNECT") {
37341
37374
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
37342
- } else if (invalidPathRegex.test(path51)) {
37375
+ } else if (invalidPathRegex.test(path54)) {
37343
37376
  throw new InvalidArgumentError2("invalid request path");
37344
37377
  }
37345
37378
  if (typeof method !== "string") {
@@ -37414,7 +37447,7 @@ var require_request = __commonJS({
37414
37447
  this.completed = false;
37415
37448
  this.aborted = false;
37416
37449
  this.upgrade = upgrade || null;
37417
- this.path = query ? serializePathWithQuery(path51, query) : path51;
37450
+ this.path = query ? serializePathWithQuery(path54, query) : path54;
37418
37451
  this.origin = origin;
37419
37452
  this.protocol = getProtocolFromUrlString(origin);
37420
37453
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -42596,7 +42629,7 @@ var require_client_h1 = __commonJS({
42596
42629
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
42597
42630
  }
42598
42631
  function writeH1(client, request7) {
42599
- const { method, path: path51, host, upgrade, blocking, reset } = request7;
42632
+ const { method, path: path54, host, upgrade, blocking, reset } = request7;
42600
42633
  let { body, headers, contentLength } = request7;
42601
42634
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
42602
42635
  if (util2.isFormDataLike(body)) {
@@ -42674,7 +42707,7 @@ var require_client_h1 = __commonJS({
42674
42707
  if (socket.setTypeOfService) {
42675
42708
  socket.setTypeOfService(request7.typeOfService);
42676
42709
  }
42677
- let header = `${method} ${path51} HTTP/1.1\r
42710
+ let header = `${method} ${path54} HTTP/1.1\r
42678
42711
  `;
42679
42712
  if (typeof host === "string") {
42680
42713
  header += `host: ${host}\r
@@ -43353,7 +43386,7 @@ var require_client_h2 = __commonJS({
43353
43386
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
43354
43387
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
43355
43388
  const session = client[kHTTP2Session];
43356
- const { method, path: path51, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43389
+ const { method, path: path54, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
43357
43390
  let { body } = request7;
43358
43391
  if (upgrade != null && upgrade !== "websocket") {
43359
43392
  util2.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -43422,7 +43455,7 @@ var require_client_h2 = __commonJS({
43422
43455
  }
43423
43456
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
43424
43457
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
43425
- headers[HTTP2_HEADER_PATH] = path51;
43458
+ headers[HTTP2_HEADER_PATH] = path54;
43426
43459
  if (protocol === "ws:" || protocol === "wss:") {
43427
43460
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
43428
43461
  } else {
@@ -43464,7 +43497,7 @@ var require_client_h2 = __commonJS({
43464
43497
  stream.setTimeout(headersTimeout);
43465
43498
  return true;
43466
43499
  }
43467
- headers[HTTP2_HEADER_PATH] = path51;
43500
+ headers[HTTP2_HEADER_PATH] = path54;
43468
43501
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
43469
43502
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
43470
43503
  if (body && typeof body.read === "function") {
@@ -45816,10 +45849,10 @@ var require_proxy_agent = __commonJS({
45816
45849
  };
45817
45850
  const {
45818
45851
  origin,
45819
- path: path51 = "/",
45852
+ path: path54 = "/",
45820
45853
  headers = {}
45821
45854
  } = opts;
45822
- opts.path = origin + path51;
45855
+ opts.path = origin + path54;
45823
45856
  if (!("host" in headers) && !("Host" in headers)) {
45824
45857
  const { host } = new URL(origin);
45825
45858
  headers.host = host;
@@ -47928,20 +47961,20 @@ var require_mock_utils = __commonJS({
47928
47961
  }
47929
47962
  return normalizedQp;
47930
47963
  }
47931
- function safeUrl(path51) {
47932
- if (typeof path51 !== "string") {
47933
- return path51;
47964
+ function safeUrl(path54) {
47965
+ if (typeof path54 !== "string") {
47966
+ return path54;
47934
47967
  }
47935
- const pathSegments = path51.split("?", 3);
47968
+ const pathSegments = path54.split("?", 3);
47936
47969
  if (pathSegments.length !== 2) {
47937
- return path51;
47970
+ return path54;
47938
47971
  }
47939
47972
  const qp2 = new URLSearchParams(pathSegments.pop());
47940
47973
  qp2.sort();
47941
47974
  return [...pathSegments, qp2.toString()].join("?");
47942
47975
  }
47943
- function matchKey(mockDispatch2, { path: path51, method, body, headers }) {
47944
- const pathMatch = matchValue(mockDispatch2.path, path51);
47976
+ function matchKey(mockDispatch2, { path: path54, method, body, headers }) {
47977
+ const pathMatch = matchValue(mockDispatch2.path, path54);
47945
47978
  const methodMatch = matchValue(mockDispatch2.method, method);
47946
47979
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
47947
47980
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -47966,8 +47999,8 @@ var require_mock_utils = __commonJS({
47966
47999
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
47967
48000
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
47968
48001
  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);
48002
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path54, ignoreTrailingSlash }) => {
48003
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path54)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path54), resolvedPath);
47971
48004
  });
47972
48005
  if (matchedMockDispatches.length === 0) {
47973
48006
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -48006,19 +48039,19 @@ var require_mock_utils = __commonJS({
48006
48039
  mockDispatches.splice(index, 1);
48007
48040
  }
48008
48041
  }
48009
- function removeTrailingSlash(path51) {
48010
- while (path51.endsWith("/")) {
48011
- path51 = path51.slice(0, -1);
48042
+ function removeTrailingSlash(path54) {
48043
+ while (path54.endsWith("/")) {
48044
+ path54 = path54.slice(0, -1);
48012
48045
  }
48013
- if (path51.length === 0) {
48014
- path51 = "/";
48046
+ if (path54.length === 0) {
48047
+ path54 = "/";
48015
48048
  }
48016
- return path51;
48049
+ return path54;
48017
48050
  }
48018
48051
  function buildKey(opts) {
48019
- const { path: path51, method, body, headers, query } = opts;
48052
+ const { path: path54, method, body, headers, query } = opts;
48020
48053
  return {
48021
- path: path51,
48054
+ path: path54,
48022
48055
  method,
48023
48056
  body,
48024
48057
  headers,
@@ -48708,10 +48741,10 @@ var require_pending_interceptors_formatter = __commonJS({
48708
48741
  }
48709
48742
  format(pendingInterceptors) {
48710
48743
  const withPrettyHeaders = pendingInterceptors.map(
48711
- ({ method, path: path51, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48744
+ ({ method, path: path54, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
48712
48745
  Method: method,
48713
48746
  Origin: origin,
48714
- Path: path51,
48747
+ Path: path54,
48715
48748
  "Status code": statusCode,
48716
48749
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
48717
48750
  Invocations: timesInvoked,
@@ -48793,9 +48826,9 @@ var require_mock_agent = __commonJS({
48793
48826
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
48794
48827
  const dispatchOpts = { ...opts };
48795
48828
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
48796
- const [path51, searchParams] = dispatchOpts.path.split("?");
48829
+ const [path54, searchParams] = dispatchOpts.path.split("?");
48797
48830
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
48798
- dispatchOpts.path = `${path51}?${normalizedSearchParams}`;
48831
+ dispatchOpts.path = `${path54}?${normalizedSearchParams}`;
48799
48832
  }
48800
48833
  return this[kAgent].dispatch(dispatchOpts, handler);
48801
48834
  }
@@ -49196,12 +49229,12 @@ var require_snapshot_recorder = __commonJS({
49196
49229
  * @return {Promise<void>} - Resolves when snapshots are loaded
49197
49230
  */
49198
49231
  async loadSnapshots(filePath) {
49199
- const path51 = filePath || this.#snapshotPath;
49200
- if (!path51) {
49232
+ const path54 = filePath || this.#snapshotPath;
49233
+ if (!path54) {
49201
49234
  throw new InvalidArgumentError2("Snapshot path is required");
49202
49235
  }
49203
49236
  try {
49204
- const data = await readFile(resolve2(path51), "utf8");
49237
+ const data = await readFile(resolve2(path54), "utf8");
49205
49238
  const parsed = JSON.parse(data);
49206
49239
  if (Array.isArray(parsed)) {
49207
49240
  this.#snapshots.clear();
@@ -49215,7 +49248,7 @@ var require_snapshot_recorder = __commonJS({
49215
49248
  if (error63.code === "ENOENT") {
49216
49249
  this.#snapshots.clear();
49217
49250
  } else {
49218
- throw new UndiciError(`Failed to load snapshots from ${path51}`, { cause: error63 });
49251
+ throw new UndiciError(`Failed to load snapshots from ${path54}`, { cause: error63 });
49219
49252
  }
49220
49253
  }
49221
49254
  }
@@ -49226,11 +49259,11 @@ var require_snapshot_recorder = __commonJS({
49226
49259
  * @returns {Promise<void>} - Resolves when snapshots are saved
49227
49260
  */
49228
49261
  async saveSnapshots(filePath) {
49229
- const path51 = filePath || this.#snapshotPath;
49230
- if (!path51) {
49262
+ const path54 = filePath || this.#snapshotPath;
49263
+ if (!path54) {
49231
49264
  throw new InvalidArgumentError2("Snapshot path is required");
49232
49265
  }
49233
- const resolvedPath = resolve2(path51);
49266
+ const resolvedPath = resolve2(path54);
49234
49267
  await mkdir(dirname3(resolvedPath), { recursive: true });
49235
49268
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
49236
49269
  hash: hash2,
@@ -49862,15 +49895,15 @@ var require_redirect_handler = __commonJS({
49862
49895
  return;
49863
49896
  }
49864
49897
  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}`;
49898
+ const path54 = search ? `${pathname}${search}` : pathname;
49899
+ const redirectUrlString = `${origin}${path54}`;
49867
49900
  for (const historyUrl of this.history) {
49868
49901
  if (historyUrl.toString() === redirectUrlString) {
49869
49902
  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
49903
  }
49871
49904
  }
49872
49905
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
49873
- this.opts.path = path51;
49906
+ this.opts.path = path54;
49874
49907
  this.opts.origin = origin;
49875
49908
  this.opts.query = null;
49876
49909
  }
@@ -51630,10 +51663,10 @@ var require_cache_handler = __commonJS({
51630
51663
  }
51631
51664
  return locationUrl.pathname + locationUrl.search;
51632
51665
  }
51633
- function deleteCachedUri(store, cacheKey, path51) {
51666
+ function deleteCachedUri(store, cacheKey, path54) {
51634
51667
  deleteCachedValue(store, {
51635
51668
  ...cacheKey,
51636
- path: path51
51669
+ path: path54
51637
51670
  });
51638
51671
  for (let i10 = 0; i10 < util2.safeHTTPMethods.length; i10++) {
51639
51672
  const method = util2.safeHTTPMethods[i10];
@@ -51641,7 +51674,7 @@ var require_cache_handler = __commonJS({
51641
51674
  deleteCachedValue(store, {
51642
51675
  ...cacheKey,
51643
51676
  method,
51644
- path: path51
51677
+ path: path54
51645
51678
  });
51646
51679
  }
51647
51680
  }
@@ -51652,9 +51685,9 @@ var require_cache_handler = __commonJS({
51652
51685
  }
51653
51686
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
51654
51687
  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);
51688
+ const path54 = getSameOriginPath(cacheKey, values[i10]);
51689
+ if (path54 !== void 0) {
51690
+ deleteCachedUri(store, cacheKey, path54);
51658
51691
  }
51659
51692
  }
51660
51693
  }
@@ -56654,11 +56687,11 @@ var require_fetch = __commonJS({
56654
56687
  function dispatch({ body }) {
56655
56688
  const url2 = requestCurrentURL(request7);
56656
56689
  const agent = fetchParams.controller.dispatcher;
56657
- const path51 = url2.pathname + url2.search;
56690
+ const path54 = url2.pathname + url2.search;
56658
56691
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
56659
56692
  return new Promise((resolve2, reject) => agent.dispatch(
56660
56693
  {
56661
- path: hasTrailingQuestionMark ? `${path51}?` : path51,
56694
+ path: hasTrailingQuestionMark ? `${path54}?` : path54,
56662
56695
  origin: url2.origin,
56663
56696
  method: request7.method,
56664
56697
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -57605,9 +57638,9 @@ var require_util5 = __commonJS({
57605
57638
  }
57606
57639
  }
57607
57640
  }
57608
- function validateCookiePath(path51) {
57609
- for (let i10 = 0; i10 < path51.length; ++i10) {
57610
- const code = path51.charCodeAt(i10);
57641
+ function validateCookiePath(path54) {
57642
+ for (let i10 = 0; i10 < path54.length; ++i10) {
57643
+ const code = path54.charCodeAt(i10);
57611
57644
  if (code < 32 || // exclude CTLs (0-31)
57612
57645
  code > 126 || // exclude DEL and non-ascii
57613
57646
  code === 59) {
@@ -60955,11 +60988,11 @@ var require_undici = __commonJS({
60955
60988
  if (typeof opts.path !== "string") {
60956
60989
  throw new InvalidArgumentError2("invalid opts.path");
60957
60990
  }
60958
- let path51 = opts.path;
60991
+ let path54 = opts.path;
60959
60992
  if (!opts.path.startsWith("/")) {
60960
- path51 = `/${path51}`;
60993
+ path54 = `/${path54}`;
60961
60994
  }
60962
- url2 = new URL(util2.parseOrigin(url2).origin + path51);
60995
+ url2 = new URL(util2.parseOrigin(url2).origin + path54);
60963
60996
  } else {
60964
60997
  if (!opts) {
60965
60998
  opts = typeof url2 === "object" ? url2 : {};
@@ -62874,6 +62907,57 @@ var init_launchWiring = __esm({
62874
62907
  }
62875
62908
  });
62876
62909
 
62910
+ // src/usage/identityClaude.ts
62911
+ function definedEnvironment(env) {
62912
+ return Object.fromEntries(Object.entries(env).flatMap(([name, value2]) => value2 === void 0 ? [] : [[name, value2]]));
62913
+ }
62914
+ function identityLaunchArgv(identity, flags) {
62915
+ return [`@${identity}`, IDENTITY_ONLY_FLAG, ...flags];
62916
+ }
62917
+ async function withIdentityClaude(params, identity, flags, use2) {
62918
+ const refusals = [];
62919
+ const plan = prepareLaunch(
62920
+ realPrepareLaunchParams(params.paths, {
62921
+ proc: {
62922
+ env: Object.fromEntries(Object.entries(process.env).filter(([name]) => name !== CONFIG_DIR_VARIABLE)),
62923
+ argv: [...identityLaunchArgv(identity, flags)],
62924
+ exit: (code) => {
62925
+ throw new LaunchRefusedError(refusals.join("\n") || `the launch was refused (exit ${String(code)})`, code);
62926
+ }
62927
+ },
62928
+ log: {
62929
+ info: () => void 0,
62930
+ warn: () => void 0,
62931
+ error: (message) => {
62932
+ refusals.push(message);
62933
+ }
62934
+ },
62935
+ spawnDaemon: params.spawnDaemon,
62936
+ farm: buildFarmRuntime(params.paths, params.cwd)
62937
+ })
62938
+ );
62939
+ const abort = new AbortController();
62940
+ const timer = setTimeout(() => {
62941
+ abort.abort();
62942
+ }, params.timeoutMs);
62943
+ try {
62944
+ return await use2({ bin: plan.bin, env: definedEnvironment(plan.env), cwd: params.cwd, abort });
62945
+ } finally {
62946
+ clearTimeout(timer);
62947
+ plan.release();
62948
+ }
62949
+ }
62950
+ var CONFIG_DIR_VARIABLE, IDENTITY_ONLY_FLAG;
62951
+ var init_identityClaude = __esm({
62952
+ "src/usage/identityClaude.ts"() {
62953
+ "use strict";
62954
+ init_launchWiring();
62955
+ init_launcher();
62956
+ CONFIG_DIR_VARIABLE = "CLAUDE_CONFIG_DIR";
62957
+ IDENTITY_ONLY_FLAG = "--no-provider";
62958
+ }
62959
+ });
62960
+
62877
62961
  // src/usage/providerQuota.ts
62878
62962
  function zaiWindow(limit) {
62879
62963
  const unitMs = ZAI_UNIT_MS.get(limit.unit);
@@ -62908,7 +62992,7 @@ async function openRouterGet(url2, schema, apiKey, http8, signal) {
62908
62992
  return parsed.data;
62909
62993
  }
62910
62994
  function nextUtcMidnight(nowMs) {
62911
- return new Date((Math.floor(nowMs / MS_PER_DAY) + 1) * MS_PER_DAY).toISOString();
62995
+ return new Date((Math.floor(nowMs / MS_PER_DAY2) + 1) * MS_PER_DAY2).toISOString();
62912
62996
  }
62913
62997
  function adapterFor(baseUrl) {
62914
62998
  return PROVIDER_QUOTA_ADAPTERS.find((adapter) => adapter.matches(baseUrl));
@@ -62917,7 +63001,7 @@ function quotaFreshnessMs(quota) {
62917
63001
  const lengths = quota.windows.flatMap((window) => window.periodMs === void 0 ? [] : [window.periodMs]);
62918
63002
  return lengths.length === 0 ? Number.POSITIVE_INFINITY : Math.min(...lengths) / PERCENT3;
62919
63003
  }
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;
63004
+ 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
63005
  var init_providerQuota = __esm({
62922
63006
  "src/usage/providerQuota.ts"() {
62923
63007
  "use strict";
@@ -62929,7 +63013,7 @@ var init_providerQuota = __esm({
62929
63013
  this.name = "ProviderQuotaError";
62930
63014
  }
62931
63015
  };
62932
- MS_PER_SECOND5 = 1e3;
63016
+ MS_PER_SECOND6 = 1e3;
62933
63017
  SECONDS_PER_HOUR = 3600;
62934
63018
  HOURS_PER_DAY3 = 24;
62935
63019
  DAYS_PER_MONTH = 30;
@@ -62941,8 +63025,8 @@ var init_providerQuota = __esm({
62941
63025
  ZAI_UNIT_HOURS = 3;
62942
63026
  ZAI_UNIT_MONTHS = 5;
62943
63027
  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]
63028
+ [ZAI_UNIT_HOURS, SECONDS_PER_HOUR * MS_PER_SECOND6],
63029
+ [ZAI_UNIT_MONTHS, DAYS_PER_MONTH * HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND6]
62946
63030
  ]);
62947
63031
  ZAI_MEASURES = { TOKENS_LIMIT: "tokens", TIME_LIMIT: "tool-calls" };
62948
63032
  ZaiLimitSchema = external_exports.object({
@@ -62994,7 +63078,7 @@ var init_providerQuota = __esm({
62994
63078
  OPENROUTER_KEY_URL = `https://${OPENROUTER_HOST}/api/v1/key`;
62995
63079
  OPENROUTER_CREDITS_URL = `https://${OPENROUTER_HOST}/api/v1/credits`;
62996
63080
  HTTP_FORBIDDEN = 403;
62997
- MS_PER_DAY = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND5;
63081
+ MS_PER_DAY2 = HOURS_PER_DAY3 * SECONDS_PER_HOUR * MS_PER_SECOND6;
62998
63082
  OpenRouterKeySchema = external_exports.object({
62999
63083
  data: external_exports.object({
63000
63084
  limit: external_exports.number().nonnegative().nullable(),
@@ -63025,7 +63109,7 @@ var init_providerQuota = __esm({
63025
63109
  windows.push({ measures: "account-credits", period: "prepaid", utilization: used / total, limit: total, used, remaining: Math.max(total - used, 0) });
63026
63110
  }
63027
63111
  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) });
63112
+ 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
63113
  }
63030
63114
  return ProviderQuotaSchema.parse({
63031
63115
  observedAt: new Date(nowMs).toISOString(),
@@ -96617,9 +96701,6 @@ var realAnthropicUsageProbe_exports = {};
96617
96701
  __export(realAnthropicUsageProbe_exports, {
96618
96702
  createRealAnthropicUsageRefresher: () => createRealAnthropicUsageRefresher
96619
96703
  });
96620
- function definedEnvironment(env) {
96621
- return Object.fromEntries(Object.entries(env).flatMap(([name, value2]) => value2 === void 0 ? [] : [[name, value2]]));
96622
- }
96623
96704
  function idlePrompt(signal) {
96624
96705
  return {
96625
96706
  [Symbol.asyncIterator]: () => ({
@@ -96632,58 +96713,28 @@ function idlePrompt(signal) {
96632
96713
  };
96633
96714
  }
96634
96715
  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
- );
96716
+ return async (identity) => await withIdentityClaude(params, identity, PROBE_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
96657
96717
  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();
96718
+ const session = query({
96719
+ prompt: idlePrompt(abort.signal),
96720
+ options: {
96721
+ pathToClaudeCodeExecutable: bin,
96722
+ env,
96723
+ cwd,
96724
+ abortController: abort,
96725
+ settingSources: [],
96726
+ mcpServers: {},
96727
+ strictMcpConfig: true,
96728
+ persistSession: false
96681
96729
  }
96730
+ });
96731
+ try {
96732
+ const report = await session.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
96733
+ return unifiedFromReportedLimits(report.rate_limits_available ? report.rate_limits : null);
96682
96734
  } finally {
96683
- clearTimeout(timer);
96684
- plan.release();
96735
+ session.close();
96685
96736
  }
96686
- };
96737
+ });
96687
96738
  }
96688
96739
  function createRealAnthropicUsageRefresher(params) {
96689
96740
  return createAnthropicUsageRefresher({
@@ -96696,18 +96747,16 @@ function createRealAnthropicUsageRefresher(params) {
96696
96747
  concurrency: (0, import_node_os11.availableParallelism)()
96697
96748
  });
96698
96749
  }
96699
- var import_node_os11, PROBE_LAUNCH_FLAGS, CONFIG_DIR_VARIABLE;
96750
+ var import_node_os11, PROBE_LAUNCH_FLAGS;
96700
96751
  var init_realAnthropicUsageProbe = __esm({
96701
96752
  "src/usage/realAnthropicUsageProbe.ts"() {
96702
96753
  "use strict";
96703
96754
  import_node_os11 = require("node:os");
96704
- init_launchWiring();
96705
- init_launcher();
96706
96755
  init_anthropicUsageRefresh();
96756
+ init_identityClaude();
96707
96757
  init_middleware();
96708
96758
  init_quotaRefresh();
96709
96759
  PROBE_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control"];
96710
- CONFIG_DIR_VARIABLE = "CLAUDE_CONFIG_DIR";
96711
96760
  }
96712
96761
  });
96713
96762
 
@@ -99940,8 +99989,8 @@ var require_utils3 = __commonJS({
99940
99989
  }
99941
99990
  return ind;
99942
99991
  }
99943
- function removeDotSegments(path51) {
99944
- let input2 = path51;
99992
+ function removeDotSegments(path54) {
99993
+ let input2 = path54;
99945
99994
  const output2 = [];
99946
99995
  let nextSlash = -1;
99947
99996
  let len = 0;
@@ -100350,8 +100399,8 @@ var require_schemes = __commonJS({
100350
100399
  }
100351
100400
  if (wsComponent.resourceName) {
100352
100401
  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;
100402
+ const path54 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
100403
+ wsComponent.path = path54 && path54 !== "/" ? path54 : void 0;
100355
100404
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
100356
100405
  wsComponent.resourceName = void 0;
100357
100406
  }
@@ -103878,7 +103927,7 @@ var require_dist2 = __commonJS({
103878
103927
  });
103879
103928
 
103880
103929
  // src/cli.ts
103881
- var import_node_path50 = __toESM(require("node:path"), 1);
103930
+ var import_node_path53 = __toESM(require("node:path"), 1);
103882
103931
 
103883
103932
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
103884
103933
  var CommanderError = class extends Error {
@@ -106991,9 +107040,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
106991
107040
  * @param {string} [path]
106992
107041
  * @return {(string|null|Command)}
106993
107042
  */
106994
- executableDir(path51) {
106995
- if (path51 === void 0) return this._executableDir;
106996
- this._executableDir = path51;
107043
+ executableDir(path54) {
107044
+ if (path54 === void 0) return this._executableDir;
107045
+ this._executableDir = path54;
106997
107046
  return this;
106998
107047
  }
106999
107048
  /**
@@ -108642,19 +108691,19 @@ function writePools(paths, pools) {
108642
108691
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
108643
108692
  }
108644
108693
  function poolCycleOf(pools, name) {
108645
- const walk = (current, path51) => {
108694
+ const walk = (current, path54) => {
108646
108695
  for (const entry of pools[current]?.identities ?? []) {
108647
108696
  const nested = poolNameOf(poolMemberIdentity(entry));
108648
108697
  if (nested === void 0) {
108649
108698
  continue;
108650
108699
  }
108651
108700
  if (nested === name) {
108652
- return [...path51, nested];
108701
+ return [...path54, nested];
108653
108702
  }
108654
- if (path51.includes(nested)) {
108703
+ if (path54.includes(nested)) {
108655
108704
  continue;
108656
108705
  }
108657
- const found = walk(nested, [...path51, nested]);
108706
+ const found = walk(nested, [...path54, nested]);
108658
108707
  if (found !== void 0) {
108659
108708
  return found;
108660
108709
  }
@@ -108805,6 +108854,18 @@ function listIdentities(paths) {
108805
108854
  }
108806
108855
  return result;
108807
108856
  }
108857
+ function listAnchoredIdentities(paths) {
108858
+ return listIdentities(paths).flatMap(({ name }) => {
108859
+ const anchors = readIdentity(paths, name)?.anchors;
108860
+ return anchors === void 0 ? [] : [{ identity: name, anchors }];
108861
+ });
108862
+ }
108863
+ function setIdentityAnchors(paths, identityName, anchors) {
108864
+ if (!identityExists(paths, identityName)) {
108865
+ throw new IdentityNotFoundError(identityName);
108866
+ }
108867
+ return applyPatch(identityJsonPath(paths, identityName), IdentitySchema, { anchors: anchors === void 0 ? void 0 : [...anchors] });
108868
+ }
108808
108869
  function setDefaultConfigProfile(paths, identityName, profileName) {
108809
108870
  if (!identityExists(paths, identityName)) {
108810
108871
  throw new IdentityNotFoundError(identityName);
@@ -109583,6 +109644,141 @@ function cacheChange(options, existing) {
109583
109644
  }
109584
109645
  }
109585
109646
 
109647
+ // src/usage/anchor.ts
109648
+ init_schema();
109649
+ var MS_PER_SECOND = 1e3;
109650
+ var MS_PER_MINUTE2 = 6e4;
109651
+ var MINUTES_PER_HOUR = 60;
109652
+ var DAYS_IN_WEEK = 7;
109653
+ var MS_PER_DAY = 864e5;
109654
+ var SEARCH_MARGIN_DAYS = 1;
109655
+ var WORKING_DAYS = 5;
109656
+ var WEEKDAY_SHORTHANDS = { daily: WEEKDAYS, weekdays: WEEKDAYS.slice(0, WORKING_DAYS) };
109657
+ function zoneOffsetMs(utcMs, timeZone) {
109658
+ const wholeSecondMs = Math.floor(utcMs / MS_PER_SECOND) * MS_PER_SECOND;
109659
+ 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));
109660
+ const field = (type2) => Number(parts.find((part) => part.type === type2)?.value);
109661
+ return Date.UTC(field("year"), field("month") - 1, field("day"), field("hour"), field("minute"), field("second")) - wholeSecondMs;
109662
+ }
109663
+ function wallTimeToUtcMs(date5, minutesOfDay, timeZone) {
109664
+ const asUtc = Date.UTC(date5.year, date5.month - 1, date5.day) + minutesOfDay * MS_PER_MINUTE2;
109665
+ const candidates = [zoneOffsetMs(asUtc - MS_PER_DAY, timeZone), zoneOffsetMs(asUtc + MS_PER_DAY, timeZone)].map((offset) => ({ offset, instant: asUtc - offset }));
109666
+ const valid = candidates.filter(({ offset, instant }) => zoneOffsetMs(instant, timeZone) === offset).map(({ instant }) => instant);
109667
+ return valid.length === 0 ? asUtc - (candidates[0]?.offset ?? 0) : Math.min(...valid);
109668
+ }
109669
+ function localDate(utcMs, timeZone) {
109670
+ const local = new Date(utcMs + zoneOffsetMs(utcMs, timeZone));
109671
+ return { year: local.getUTCFullYear(), month: local.getUTCMonth() + 1, day: local.getUTCDate() };
109672
+ }
109673
+ function weekdayOf(date5) {
109674
+ const sundayFirst = new Date(Date.UTC(date5.year, date5.month - 1, date5.day)).getUTCDay();
109675
+ const day = WEEKDAYS[(sundayFirst + DAYS_IN_WEEK - 1) % DAYS_IN_WEEK];
109676
+ if (day === void 0) {
109677
+ throw new RangeError(`no weekday for day number ${String(sundayFirst)}`);
109678
+ }
109679
+ return day;
109680
+ }
109681
+ function minutesOfDayOf(time4) {
109682
+ const [hours, minutes] = time4.split(":").map(Number);
109683
+ return (hours ?? 0) * MINUTES_PER_HOUR + (minutes ?? 0);
109684
+ }
109685
+ function anchorInstants(anchors, afterMs, uptoMs, defaultTimeZone) {
109686
+ const instants = anchors.flatMap((anchor2) => {
109687
+ const timeZone = anchor2.timeZone ?? defaultTimeZone;
109688
+ const minutesOfDay = minutesOfDayOf(anchor2.time);
109689
+ const first = localDate(afterMs - SEARCH_MARGIN_DAYS * MS_PER_DAY, timeZone);
109690
+ const found = [];
109691
+ for (let offset = 0; ; offset += 1) {
109692
+ const date5 = localDate(Date.UTC(first.year, first.month - 1, first.day + offset) + MS_PER_DAY / 2, "UTC");
109693
+ const instant = wallTimeToUtcMs(date5, minutesOfDay, timeZone);
109694
+ if (instant > uptoMs + SEARCH_MARGIN_DAYS * MS_PER_DAY) {
109695
+ return found;
109696
+ }
109697
+ if (instant > afterMs && instant <= uptoMs && anchor2.days.includes(weekdayOf(date5))) {
109698
+ found.push(instant);
109699
+ }
109700
+ }
109701
+ });
109702
+ return instants.sort((left, right) => left - right);
109703
+ }
109704
+ function dueAnchor(anchors, nowMs, handledMs, defaultTimeZone) {
109705
+ const since = Math.max(handledMs, nowMs - DAYS_IN_WEEK * MS_PER_DAY);
109706
+ return anchorInstants(anchors, since, nowMs, defaultTimeZone).at(-1);
109707
+ }
109708
+ function parseDayItem(item) {
109709
+ const [from, to2, ...extra] = item.split("-");
109710
+ const index = (name) => WEEKDAYS.findIndex((day) => day === name);
109711
+ if (from === void 0 || extra.length > 0 || index(from) === -1 || to2 !== void 0 && index(to2) === -1) {
109712
+ throw new Error(`"${item}" is not a weekday (${WEEKDAYS.join(", ")}) or a range such as mon-fri`);
109713
+ }
109714
+ if (to2 === void 0) {
109715
+ return [WEEKDAYS[index(from)] ?? "mon"];
109716
+ }
109717
+ const length = (index(to2) - index(from) + DAYS_IN_WEEK) % DAYS_IN_WEEK + 1;
109718
+ return Array.from({ length }, (_, step2) => WEEKDAYS[(index(from) + step2) % DAYS_IN_WEEK] ?? "mon");
109719
+ }
109720
+ function parseAnchor(spec) {
109721
+ const match = /^(?<days>[^@]+)@(?<time>[^/]+)(?:\/(?<zone>.+))?$/.exec(spec);
109722
+ const { days, time: time4, zone } = match?.groups ?? {};
109723
+ if (days === void 0 || time4 === void 0) {
109724
+ 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`);
109725
+ }
109726
+ const named = WEEKDAY_SHORTHANDS[days] ?? days.split(",").flatMap(parseDayItem);
109727
+ const parsed = AnchorSchema.safeParse({ days: [...new Set(named)], time: time4, ...zone === void 0 ? {} : { timeZone: zone } });
109728
+ if (!parsed.success) {
109729
+ throw new Error(`"${spec}" is not an anchor: ${parsed.error.issues.map((issue2) => issue2.message).join("; ")}`);
109730
+ }
109731
+ return parsed.data;
109732
+ }
109733
+ 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";
109734
+ function formatAnchor(anchor2) {
109735
+ return `${anchor2.days.join(",")}@${anchor2.time}${anchor2.timeZone === void 0 ? "" : `/${anchor2.timeZone}`}`;
109736
+ }
109737
+ function machineTimeZone() {
109738
+ return new Intl.DateTimeFormat().resolvedOptions().timeZone;
109739
+ }
109740
+
109741
+ // src/cli/parsers.ts
109742
+ init_conditions();
109743
+ init_pairs();
109744
+ function asInvalidArgument(parse4) {
109745
+ try {
109746
+ return parse4();
109747
+ } catch (error63) {
109748
+ if (error63 instanceof Error && !(error63 instanceof InvalidArgumentError)) {
109749
+ throw new InvalidArgumentError(error63.message);
109750
+ }
109751
+ throw error63;
109752
+ }
109753
+ }
109754
+ function collectBoolPair(value2, previous = {}) {
109755
+ return asInvalidArgument(() => {
109756
+ const { key, value: raw } = parsePair(value2);
109757
+ return { ...previous, [key]: parseBool(raw) };
109758
+ });
109759
+ }
109760
+ function collectStringPair(value2, previous = {}) {
109761
+ return asInvalidArgument(() => {
109762
+ const { key, value: raw } = parsePair(value2);
109763
+ return { ...previous, [key]: raw };
109764
+ });
109765
+ }
109766
+ function collectRepeated(value2, previous = []) {
109767
+ return [...previous, value2];
109768
+ }
109769
+ function collectAnchor(value2, previous = []) {
109770
+ return [...previous, asInvalidArgument(() => parseAnchor(value2))];
109771
+ }
109772
+ function parseDurationLiteral(value2) {
109773
+ return asInvalidArgument(() => {
109774
+ parseDuration(value2);
109775
+ return value2;
109776
+ });
109777
+ }
109778
+ function parseDurationOption(value2) {
109779
+ return asInvalidArgument(() => parseDuration(value2));
109780
+ }
109781
+
109586
109782
  // src/identityManager.ts
109587
109783
  init_classify();
109588
109784
  init_schema();
@@ -109636,40 +109832,6 @@ async function resolveFarmConflicts(params) {
109636
109832
 
109637
109833
  // src/configProfiles.ts
109638
109834
  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
109835
  init_cliError();
109674
109836
  async function ensureProfileExists(deps, name) {
109675
109837
  if (profileExists(deps.paths, name)) {
@@ -109899,7 +110061,8 @@ function toIdentityView(paths, entry) {
109899
110061
  ...entry.problem === void 0 ? {
109900
110062
  ...entry.identity.defaultConfigProfile === void 0 ? {} : { defaultConfigProfile: entry.identity.defaultConfigProfile },
109901
110063
  allowAmbientCredential: entry.identity.allowAmbientCredential,
109902
- ...entry.identity.credential === void 0 ? {} : { credential: summariseCredential(entry.identity.credential) }
110064
+ ...entry.identity.credential === void 0 ? {} : { credential: summariseCredential(entry.identity.credential) },
110065
+ ...entry.identity.anchors === void 0 ? {} : { anchors: entry.identity.anchors }
109903
110066
  } : { problem: entry.problem }
109904
110067
  };
109905
110068
  }
@@ -109968,6 +110131,7 @@ function registerIdentityCommand(program2, deps) {
109968
110131
  console.log(`Default configuration profile: ${view.defaultConfigProfile ?? "(none)"}`);
109969
110132
  console.log(`Allows ambient credential: ${view.allowAmbientCredential === true ? "yes" : "no"}`);
109970
110133
  console.log(`Credential: ${entry.identity?.credential === void 0 ? "(none; uses its stored login)" : describeCredential(entry.identity.credential)}`);
110134
+ console.log(`Anchors: ${view.anchors === void 0 ? "(none)" : view.anchors.map(formatAnchor).join(" ")}`);
109971
110135
  }),
109972
110136
  ["agent-shim identity show work", "agent-shim identity show work --json"]
109973
110137
  );
@@ -109975,7 +110139,11 @@ function registerIdentityCommand(program2, deps) {
109975
110139
  "--credential <source>",
109976
110140
  `Authenticate this identity from a token instead of its stored login, replacing any existing sources (repeatable, in the order tried): ${CREDENTIAL_SOURCE_SYNTAX}.`,
109977
110141
  collectCredentialSource
109978
- ).option("--no-credential", "Remove this identity's credential, returning it to its stored login.").addOption(
110142
+ ).option("--no-credential", "Remove this identity's credential, returning it to its stored login.").option(
110143
+ "--anchor <spec>",
110144
+ `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}.`,
110145
+ collectAnchor
110146
+ ).option("--no-anchor", "Remove this identity's anchors.").addOption(
109979
110147
  new Option(
109980
110148
  "--credential-target <target>",
109981
110149
  "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 +110155,7 @@ function registerIdentityCommand(program2, deps) {
109987
110155
  const { json: json2, ...options } = allOptions;
109988
110156
  if (Object.entries(allOptions).every(([key, value2]) => key === "json" || value2 === void 0)) {
109989
110157
  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."
110158
+ "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
110159
  );
109992
110160
  }
109993
110161
  if (!identityExists(paths, name)) {
@@ -110022,6 +110190,10 @@ function registerIdentityCommand(program2, deps) {
110022
110190
  messages.push(`Identity "${name}" now authenticates with credential ${describeCredential(updated.credential)}.`);
110023
110191
  }
110024
110192
  }
110193
+ if (options.anchor !== void 0) {
110194
+ const updated = setIdentityAnchors(paths, name, options.anchor === false ? void 0 : options.anchor);
110195
+ messages.push(updated.anchors === void 0 ? `Identity "${name}" no longer has anchors.` : `Identity "${name}" now has anchors ${updated.anchors.map(formatAnchor).join(" ")}.`);
110196
+ }
110025
110197
  reportMutation(json2, { action: "updated", kind: "identity", name, value: readIdentity(paths, name) }, () => {
110026
110198
  for (const message of messages) {
110027
110199
  console.log(message);
@@ -110032,7 +110204,9 @@ function registerIdentityCommand(program2, deps) {
110032
110204
  "agent-shim identity set work --default-profile client-acme",
110033
110205
  "agent-shim identity set work --allow-ambient-credential",
110034
110206
  "agent-shim identity set work --credential-target oauthToken --credential op:op://vault/claude-work/token",
110035
- "agent-shim identity set work --no-credential"
110207
+ "agent-shim identity set work --no-credential",
110208
+ "agent-shim identity set work --anchor mon-fri@06:00",
110209
+ "agent-shim identity set work --no-anchor"
110036
110210
  ]
110037
110211
  );
110038
110212
  withExamples(
@@ -110782,7 +110956,7 @@ var SIWC_PLAN_SCOPE = "chatgpt.tokens.use.direct";
110782
110956
  var SIWC_CALLBACK_PORT = 1455;
110783
110957
  var SIWC_CALLBACK_PATH = "/auth/callback";
110784
110958
  var SIWC_RANDOM_BYTES = 32;
110785
- var MS_PER_SECOND4 = 1e3;
110959
+ var MS_PER_SECOND5 = 1e3;
110786
110960
  var ID_TOKEN_ALGORITHM = "RS256";
110787
110961
  var SiwcError = class extends Error {
110788
110962
  constructor(message) {
@@ -110878,7 +111052,7 @@ function grantTokens(ports, answer) {
110878
111052
  refreshToken: answer.refresh_token,
110879
111053
  idToken: answer.id_token,
110880
111054
  scopes: answer.scope === void 0 ? void 0 : answer.scope.split(" ").filter((part) => part !== ""),
110881
- expiresAt: ports.now().getTime() + answer.expires_in * MS_PER_SECOND4
111055
+ expiresAt: ports.now().getTime() + answer.expires_in * MS_PER_SECOND5
110882
111056
  };
110883
111057
  }
110884
111058
  async function exchangeCode(ports, request7) {
@@ -110939,7 +111113,7 @@ async function verifyIdToken(ports, idToken, expected) {
110939
111113
  if (!(Array.isArray(claims.aud) ? claims.aud : [claims.aud]).includes(expected.clientId)) {
110940
111114
  throw new SiwcError("the ID token was issued for a different client");
110941
111115
  }
110942
- if (claims.exp * MS_PER_SECOND4 <= ports.now().getTime()) {
111116
+ if (claims.exp * MS_PER_SECOND5 <= ports.now().getTime()) {
110943
111117
  throw new SiwcError("the ID token has already expired");
110944
111118
  }
110945
111119
  if (expected.nonce !== void 0 && claims.nonce !== expected.nonce) {
@@ -111471,7 +111645,7 @@ function registerCodexCommand(program2, deps) {
111471
111645
 
111472
111646
  // src/frontdoor/commands.ts
111473
111647
  var import_node_crypto20 = require("node:crypto");
111474
- var import_node_path45 = __toESM(require("node:path"), 1);
111648
+ var import_node_path47 = __toESM(require("node:path"), 1);
111475
111649
  var import_node_fs16 = __toESM(require("node:fs"), 1);
111476
111650
  init_commandDeps();
111477
111651
  init_schema();
@@ -111672,6 +111846,63 @@ function registerUpdateCommand(program2, deps, ports = realUpdatePorts) {
111672
111846
  );
111673
111847
  }
111674
111848
 
111849
+ // src/jobStore.ts
111850
+ init_cliError();
111851
+ init_store();
111852
+ init_schema();
111853
+ var JobNotFoundError = class extends CliError {
111854
+ constructor(jobName) {
111855
+ super(`No job named "${jobName}". Run \`agent-shim job add ${jobName} ...\` first.`);
111856
+ this.jobName = jobName;
111857
+ this.name = "JobNotFoundError";
111858
+ }
111859
+ jobName;
111860
+ };
111861
+ var JobAlreadyExistsError = class extends CliError {
111862
+ constructor(jobName) {
111863
+ super(`A job named "${jobName}" already exists. Remove it with \`agent-shim job remove ${jobName}\` to define it again.`);
111864
+ this.jobName = jobName;
111865
+ this.name = "JobAlreadyExistsError";
111866
+ }
111867
+ jobName;
111868
+ };
111869
+ var InvalidJobNameError = class extends CliError {
111870
+ constructor(attemptedName) {
111871
+ super(`"${attemptedName}" is not a valid job name: it must start with a letter or number and may then contain letters, numbers, dots, hyphens and underscores.`);
111872
+ this.attemptedName = attemptedName;
111873
+ this.name = "InvalidJobNameError";
111874
+ }
111875
+ attemptedName;
111876
+ };
111877
+ function readJobs(paths) {
111878
+ return readGlobalConfig(paths)?.jobs ?? {};
111879
+ }
111880
+ function requireJob(paths, name) {
111881
+ const job = readJobs(paths)[name];
111882
+ if (job === void 0) {
111883
+ throw new JobNotFoundError(name);
111884
+ }
111885
+ return job;
111886
+ }
111887
+ function writeJobs(paths, jobs) {
111888
+ applyPatch(paths.globalConfigFile, GlobalConfigSchema, { jobs }, { defaults: {} });
111889
+ }
111890
+ function addJob(paths, name, job) {
111891
+ if (!PoolNameSchema.safeParse(name).success) {
111892
+ throw new InvalidJobNameError(name);
111893
+ }
111894
+ const jobs = readJobs(paths);
111895
+ if (jobs[name] !== void 0) {
111896
+ throw new JobAlreadyExistsError(name);
111897
+ }
111898
+ writeJobs(paths, { ...jobs, [name]: job });
111899
+ return job;
111900
+ }
111901
+ function removeJob(paths, name) {
111902
+ requireJob(paths, name);
111903
+ writeJobs(paths, Object.fromEntries(Object.entries(readJobs(paths)).filter(([existing]) => existing !== name)));
111904
+ }
111905
+
111675
111906
  // src/launcher/poolRefresh.ts
111676
111907
  init_anthropicUsageRefresh();
111677
111908
  async function refreshStalePoolMembers(params) {
@@ -111686,6 +111917,317 @@ async function refreshStalePoolMembers(params) {
111686
111917
  init_anthropicUsageRefresh();
111687
111918
  init_poolPick();
111688
111919
  init_realAnthropicUsageProbe();
111920
+
111921
+ // src/usage/realJobRunner.ts
111922
+ var import_node_path38 = __toESM(require("node:path"), 1);
111923
+ init_conditions();
111924
+ init_identityClaude();
111925
+ var JOB_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
111926
+ var JOB_ISOLATION_OPTIONS = { settingSources: ["user"], mcpServers: {}, strictMcpConfig: true };
111927
+ function logEntry(name, identity, endedAt, outcome) {
111928
+ return `${endedAt.toISOString()} job ${name} as ${identity}
111929
+ ${outcome.trimEnd()}
111930
+
111931
+ `;
111932
+ }
111933
+ function createRealJobRunner(params) {
111934
+ return async (name, identity, job) => {
111935
+ const logFile = import_node_path38.default.join(params.paths.jobLogsDir, `${name}.log`);
111936
+ const append = (outcome) => {
111937
+ params.fs.mkdirPrivate(params.paths.jobLogsDir);
111938
+ params.fs.appendFilePrivate(logFile, logEntry(name, identity, params.now(), outcome));
111939
+ };
111940
+ try {
111941
+ const result = await withIdentityClaude({ paths: params.paths, spawnDaemon: params.spawnDaemon, cwd: job.cwd, timeoutMs: parseDuration(job.timeout) }, identity, JOB_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
111942
+ const { query } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
111943
+ const session = query({
111944
+ prompt: job.prompt,
111945
+ options: {
111946
+ pathToClaudeCodeExecutable: bin,
111947
+ env,
111948
+ cwd,
111949
+ abortController: abort,
111950
+ settingSources: [...JOB_ISOLATION_OPTIONS.settingSources],
111951
+ mcpServers: JOB_ISOLATION_OPTIONS.mcpServers,
111952
+ strictMcpConfig: JOB_ISOLATION_OPTIONS.strictMcpConfig,
111953
+ permissionMode: "dontAsk",
111954
+ ...job.model === void 0 ? {} : { model: job.model },
111955
+ ...job.allowedTools === void 0 ? {} : { allowedTools: [...job.allowedTools] }
111956
+ }
111957
+ });
111958
+ try {
111959
+ for await (const message of session) {
111960
+ if (message.type === "result") {
111961
+ if (message.subtype !== "success") {
111962
+ throw new Error(`the run ended as ${message.subtype}`);
111963
+ }
111964
+ return message.result;
111965
+ }
111966
+ }
111967
+ throw new Error("the run ended without a result");
111968
+ } finally {
111969
+ session.close();
111970
+ }
111971
+ });
111972
+ append(result);
111973
+ } catch (error63) {
111974
+ append(`FAILED: ${error63 instanceof Error ? error63.message : String(error63)}`);
111975
+ throw error63;
111976
+ }
111977
+ };
111978
+ }
111979
+
111980
+ // src/usage/realWindowOpener.ts
111981
+ init_identityClaude();
111982
+ var OPENER_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
111983
+ var WINDOW_OPENING_MODEL = "haiku";
111984
+ var WINDOW_OPENING_PROMPT = "ok";
111985
+ var WINDOW_OPENING_SYSTEM_PROMPT = "Reply with one word.";
111986
+ var WINDOW_OPEN_TIMEOUT_MS = 6e4;
111987
+ function createRealWindowOpener(params) {
111988
+ return async (identity) => {
111989
+ await withIdentityClaude({ ...params, timeoutMs: WINDOW_OPEN_TIMEOUT_MS }, identity, OPENER_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
111990
+ const { query } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
111991
+ const session = query({
111992
+ prompt: WINDOW_OPENING_PROMPT,
111993
+ options: {
111994
+ pathToClaudeCodeExecutable: bin,
111995
+ env,
111996
+ cwd,
111997
+ abortController: abort,
111998
+ settingSources: [],
111999
+ mcpServers: {},
112000
+ strictMcpConfig: true,
112001
+ persistSession: false,
112002
+ model: WINDOW_OPENING_MODEL,
112003
+ maxTurns: 1,
112004
+ tools: [],
112005
+ systemPrompt: WINDOW_OPENING_SYSTEM_PROMPT,
112006
+ thinking: { type: "disabled" }
112007
+ }
112008
+ });
112009
+ try {
112010
+ for await (const message of session) {
112011
+ if (message.type === "result") {
112012
+ if (message.subtype !== "success") {
112013
+ throw new Error(`the opening request ended as ${message.subtype}`);
112014
+ }
112015
+ return;
112016
+ }
112017
+ }
112018
+ throw new Error("the opening request ended without a result");
112019
+ } finally {
112020
+ session.close();
112021
+ }
112022
+ });
112023
+ };
112024
+ }
112025
+
112026
+ // src/usage/jobKeeper.ts
112027
+ init_conditions();
112028
+
112029
+ // src/usage/handledStamps.ts
112030
+ var import_node_path39 = __toESM(require("node:path"), 1);
112031
+ init_zod();
112032
+ var STAMPS_SCHEMA_VERSION = 1;
112033
+ var StampsFileSchema = external_exports.strictObject({
112034
+ schemaVersion: external_exports.literal(STAMPS_SCHEMA_VERSION),
112035
+ handled: external_exports.record(external_exports.string().min(1), external_exports.iso.datetime())
112036
+ });
112037
+ function readHandled(fs22, file2) {
112038
+ const raw = fs22.readFileUtf8(file2);
112039
+ if (raw === void 0) {
112040
+ return {};
112041
+ }
112042
+ let parsed;
112043
+ try {
112044
+ parsed = JSON.parse(raw);
112045
+ } catch {
112046
+ parsed = void 0;
112047
+ }
112048
+ const result = StampsFileSchema.safeParse(parsed);
112049
+ return result.success ? Object.fromEntries(Object.entries(result.data.handled).map(([key, at2]) => [key, Date.parse(at2)])) : {};
112050
+ }
112051
+ function writeHandled(fs22, file2, handled) {
112052
+ const next = { schemaVersion: STAMPS_SCHEMA_VERSION, handled: Object.fromEntries(Object.entries(handled).map(([key, at2]) => [key, new Date(at2).toISOString()])) };
112053
+ fs22.mkdirPrivate(import_node_path39.default.dirname(file2));
112054
+ fs22.writeFilePrivate(file2, `${JSON.stringify(next, null, 2)}
112055
+ `);
112056
+ }
112057
+
112058
+ // src/usage/jobKeeper.ts
112059
+ init_middleware();
112060
+ init_preflight();
112061
+
112062
+ // src/usage/windowKeeper.ts
112063
+ init_preflight();
112064
+ init_pick();
112065
+ init_middleware();
112066
+ function refusalReason(identity, snapshot, nowMs) {
112067
+ if (snapshot === void 0) {
112068
+ return void 0;
112069
+ }
112070
+ const candidate = rankPool({ members: [{ identity, snapshot, records: [] }], nowMs, resuming: false }).candidates[0];
112071
+ return candidate?.class === "ineligible" ? `it is refused right now (${candidate.reasons[0] ?? "no reason recorded"})` : void 0;
112072
+ }
112073
+ function reasonNotToOpen(identity, snapshot, nowMs) {
112074
+ if (snapshot === void 0) {
112075
+ return void 0;
112076
+ }
112077
+ const unified = snapshot.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified;
112078
+ if (unified !== void 0 && unified.fiveHour === void 0 && unified.sevenDay === void 0) {
112079
+ return "it reports no plan windows, so there is no five-hour window to anchor";
112080
+ }
112081
+ const five = unified?.fiveHour === void 0 ? void 0 : effectiveWindow(unified.fiveHour, nowMs);
112082
+ if (five?.resetsAtMs !== void 0) {
112083
+ return `a five-hour window is already open, resetting in ${formatAge(five.resetsAtMs - nowMs)}`;
112084
+ }
112085
+ return refusalReason(identity, snapshot, nowMs);
112086
+ }
112087
+ async function runWindowKeeper(ports) {
112088
+ const nowMs = ports.nowMs();
112089
+ const anchored = ports.anchored();
112090
+ const previous = readHandled(ports.fs, ports.stampsFile);
112091
+ const handled = Object.fromEntries(anchored.flatMap(({ identity }) => previous[identity] === void 0 ? [] : [[identity, previous[identity]]]));
112092
+ const outcomes = [];
112093
+ for (const { identity, anchors } of anchored) {
112094
+ const last = handled[identity];
112095
+ if (last === void 0) {
112096
+ handled[identity] = nowMs;
112097
+ outcomes.push({ identity, status: "armed", detail: "anchors noted; the next anchor to fall is the first acted on" });
112098
+ continue;
112099
+ }
112100
+ const due2 = dueAnchor(anchors, nowMs, last, ports.timeZone);
112101
+ if (due2 === void 0) {
112102
+ outcomes.push({ identity, status: "waiting", detail: "no anchor has fallen since the last handled" });
112103
+ continue;
112104
+ }
112105
+ handled[identity] = nowMs;
112106
+ const reason = reasonNotToOpen(identity, ports.snapshot(identity), nowMs);
112107
+ if (reason !== void 0) {
112108
+ outcomes.push({ identity, status: "skipped", detail: `anchor ${new Date(due2).toISOString()}: ${reason}` });
112109
+ continue;
112110
+ }
112111
+ try {
112112
+ await ports.open(identity);
112113
+ outcomes.push({ identity, status: "opened", detail: `anchor ${new Date(due2).toISOString()}: opened a five-hour window` });
112114
+ } catch (error63) {
112115
+ outcomes.push({ identity, status: "failed", detail: `anchor ${new Date(due2).toISOString()}: could not open a window: ${error63 instanceof Error ? error63.message : String(error63)}` });
112116
+ }
112117
+ }
112118
+ writeHandled(ports.fs, ports.stampsFile, handled);
112119
+ for (const outcome of outcomes) {
112120
+ if (outcome.status === "opened" || outcome.status === "skipped" || outcome.status === "failed") {
112121
+ ports.log(`window keeper: ${outcome.identity}: ${outcome.detail}`);
112122
+ }
112123
+ }
112124
+ return outcomes;
112125
+ }
112126
+
112127
+ // src/usage/jobKeeper.ts
112128
+ function pendingReset(snapshot, window, nowMs) {
112129
+ const recorded = snapshot?.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified?.[window];
112130
+ return recorded === void 0 ? void 0 : effectiveWindow(recorded, nowMs).resetsAtMs;
112131
+ }
112132
+ function runJobs(ports) {
112133
+ const nowMs = ports.nowMs();
112134
+ const jobs = ports.jobs();
112135
+ const previous = readHandled(ports.fs, ports.stampsFile);
112136
+ const handled = Object.fromEntries(jobs.flatMap(({ name }) => previous[name] === void 0 ? [] : [[name, previous[name]]]));
112137
+ const outcomes = [];
112138
+ const runs = [];
112139
+ const start = (name, identity, job, stamp, detail) => {
112140
+ handled[name] = stamp;
112141
+ ports.running.add(name);
112142
+ outcomes.push({ name, status: "started", detail });
112143
+ runs.push(
112144
+ ports.run(name, identity, job).catch((error63) => {
112145
+ ports.log(`job ${name}: failed as ${identity}: ${error63 instanceof Error ? error63.message : String(error63)}`);
112146
+ }).finally(() => {
112147
+ ports.running.delete(name);
112148
+ })
112149
+ );
112150
+ };
112151
+ const resolve2 = (target) => {
112152
+ try {
112153
+ const identity = ports.resolveIdentity(target);
112154
+ return identity === void 0 ? { problem: "no member of its pool can be picked" } : { identity };
112155
+ } catch (error63) {
112156
+ return { problem: error63 instanceof Error ? error63.message : String(error63) };
112157
+ }
112158
+ };
112159
+ const startIfServable = (name, identity, job, stamp, firedFor) => {
112160
+ const refusal2 = refusalReason(identity, ports.snapshot(identity), nowMs);
112161
+ if (refusal2 === void 0) {
112162
+ start(name, identity, job, stamp, `${firedFor}: running as ${identity}`);
112163
+ return;
112164
+ }
112165
+ handled[name] = stamp;
112166
+ outcomes.push({ name, status: "skipped", detail: `${firedFor}: ${identity}: ${refusal2}` });
112167
+ };
112168
+ for (const { name, job } of jobs) {
112169
+ if (ports.running.has(name)) {
112170
+ outcomes.push({ name, status: "running", detail: "a previous run is still going" });
112171
+ continue;
112172
+ }
112173
+ const { trigger } = job;
112174
+ if ("at" in trigger) {
112175
+ const last = handled[name];
112176
+ if (last === void 0) {
112177
+ handled[name] = nowMs;
112178
+ outcomes.push({ name, status: "armed", detail: "schedule noted; the next anchor to fall is the first acted on" });
112179
+ continue;
112180
+ }
112181
+ const due2 = dueAnchor(trigger.at, nowMs, last, ports.timeZone);
112182
+ if (due2 === void 0) {
112183
+ outcomes.push({ name, status: "waiting", detail: "no anchor has fallen since the last handled" });
112184
+ continue;
112185
+ }
112186
+ const firedFor = `anchor ${new Date(due2).toISOString()}`;
112187
+ const { identity: identity2, problem: problem2 } = resolve2(job.target);
112188
+ if (identity2 === void 0) {
112189
+ handled[name] = nowMs;
112190
+ outcomes.push({ name, status: "skipped", detail: `${firedFor}: ${problem2 ?? "no identity"}` });
112191
+ continue;
112192
+ }
112193
+ startIfServable(name, identity2, job, nowMs, firedFor);
112194
+ continue;
112195
+ }
112196
+ const { identity, problem } = resolve2(job.target);
112197
+ if (identity === void 0) {
112198
+ outcomes.push({ name, status: "skipped", detail: problem ?? "no identity" });
112199
+ continue;
112200
+ }
112201
+ const resetsAtMs = pendingReset(ports.snapshot(identity), trigger.beforeReset, nowMs);
112202
+ if (resetsAtMs === void 0) {
112203
+ outcomes.push({ name, status: "skipped", detail: `${identity} has no ${trigger.beforeReset} window to run before` });
112204
+ continue;
112205
+ }
112206
+ if (resetsAtMs - parseDuration(trigger.lead) > nowMs || handled[name] === resetsAtMs) {
112207
+ outcomes.push({ name, status: "waiting", detail: `${trigger.beforeReset} window resets in ${formatAge(resetsAtMs - nowMs)}` });
112208
+ continue;
112209
+ }
112210
+ startIfServable(name, identity, job, resetsAtMs, `${trigger.beforeReset} window resetting in ${formatAge(resetsAtMs - nowMs)}`);
112211
+ }
112212
+ writeHandled(ports.fs, ports.stampsFile, handled);
112213
+ for (const outcome of outcomes) {
112214
+ if ((outcome.status === "started" || outcome.status === "skipped") && handled[outcome.name] !== previous[outcome.name]) {
112215
+ ports.log(`job ${outcome.name}: ${outcome.detail}`);
112216
+ }
112217
+ }
112218
+ return { outcomes, settled: Promise.all(runs).then(() => void 0) };
112219
+ }
112220
+
112221
+ // src/usage/jobTarget.ts
112222
+ init_poolPick();
112223
+ function resolveJobIdentity(deps, target) {
112224
+ if ("identity" in target) {
112225
+ return target.identity;
112226
+ }
112227
+ return rankPoolGraph({ fs: deps.fs, paths: deps.paths, pools: deps.pools, poolName: target.pool, nowMs: deps.nowMs, resuming: false, identityExists: deps.identityExists }).ranking.pick?.identity;
112228
+ }
112229
+
112230
+ // src/frontdoor/commands.ts
111689
112231
  init_realCredentialCache();
111690
112232
 
111691
112233
  // src/frontdoor/custody.ts
@@ -111794,7 +112336,7 @@ init_capability();
111794
112336
 
111795
112337
  // src/frontdoor/capture.ts
111796
112338
  var fs15 = __toESM(require("node:fs"), 1);
111797
- var path37 = __toESM(require("node:path"), 1);
112339
+ var path39 = __toESM(require("node:path"), 1);
111798
112340
  var SECRET_HEADER_NAME = /authorization|cookie|token|secret|credential|api[-_]key/i;
111799
112341
  var SECRET_JSON_KEY = /token|secret|password|credential|authorization|api[-_]key/i;
111800
112342
  var SECRET_BODY_PATTERNS = [
@@ -111838,10 +112380,10 @@ function redactBody(chunk) {
111838
112380
  }
111839
112381
  var CAPTURE_ENV = "AGENT_SHIM_FRONTDOOR_CAPTURE";
111840
112382
  function captureFromEnv(env, logsDir) {
111841
- return env[CAPTURE_ENV] === "1" ? createFileCapture(path37.join(logsDir, "frontdoor-capture.jsonl")) : void 0;
112383
+ return env[CAPTURE_ENV] === "1" ? createFileCapture(path39.join(logsDir, "frontdoor-capture.jsonl")) : void 0;
111842
112384
  }
111843
112385
  function createFileCapture(file2, now = () => /* @__PURE__ */ new Date()) {
111844
- fs15.mkdirSync(path37.dirname(file2), { recursive: true });
112386
+ fs15.mkdirSync(path39.dirname(file2), { recursive: true });
111845
112387
  let nextId = 0;
111846
112388
  const append = (record2) => {
111847
112389
  fs15.appendFileSync(file2, `${JSON.stringify({ ts: now().toISOString(), ...record2 })}
@@ -111970,7 +112512,7 @@ var HIGH_BIT = 128;
111970
112512
  var BASE_128_PAYLOAD_MASK = 127;
111971
112513
  var FIRST_ARC_WEIGHT = 40;
111972
112514
  var SHORT_FORM_MAX_LENGTH = 127;
111973
- var MS_PER_SECOND6 = 1e3;
112515
+ var MS_PER_SECOND7 = 1e3;
111974
112516
  var UTC_TIME_LAST_YEAR = 2049;
111975
112517
  var YEAR_DIGITS = 4;
111976
112518
  var TWO_DIGIT_YEAR_DIGITS = 2;
@@ -112029,7 +112571,7 @@ function wholeBitString(content) {
112029
112571
  return tlv(TAG_BIT_STRING, Buffer.concat([Buffer.from([0]), content]));
112030
112572
  }
112031
112573
  function time3(instant) {
112032
- const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND6) * MS_PER_SECOND6).toISOString();
112574
+ const iso = new Date(Math.floor(instant.getTime() / MS_PER_SECOND7) * MS_PER_SECOND7).toISOString();
112033
112575
  const compact = `${iso.replace(/[-:T]/g, "").slice(0, COMPACT_TIME_DIGITS)}Z`;
112034
112576
  if (instant.getUTCFullYear() > UTC_TIME_LAST_YEAR) {
112035
112577
  return tlv(TAG_GENERALIZED_TIME, Buffer.from(compact, "ascii"));
@@ -112260,19 +112802,19 @@ init_capability();
112260
112802
  init_route();
112261
112803
 
112262
112804
  // src/frontdoor/supervisor.ts
112263
- var import_node_path38 = __toESM(require("node:path"), 1);
112805
+ var import_node_path40 = __toESM(require("node:path"), 1);
112264
112806
  init_state2();
112265
112807
  function watchedInstallEntry(resolvedOwnExecutablePath, siblingExists) {
112266
- const parsed = import_node_path38.default.parse(resolvedOwnExecutablePath);
112808
+ const parsed = import_node_path40.default.parse(resolvedOwnExecutablePath);
112267
112809
  if (parsed.name === "agent-shim") {
112268
112810
  return resolvedOwnExecutablePath;
112269
112811
  }
112270
- const sibling = import_node_path38.default.join(parsed.dir, `agent-shim${parsed.ext}`);
112812
+ const sibling = import_node_path40.default.join(parsed.dir, `agent-shim${parsed.ext}`);
112271
112813
  return siblingExists(sibling) ? sibling : resolvedOwnExecutablePath;
112272
112814
  }
112273
112815
  var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
112274
112816
  var FRONTDOOR_POLL_MS = 1e3;
112275
- var MS_PER_MINUTE2 = 6e4;
112817
+ var MS_PER_MINUTE3 = 6e4;
112276
112818
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
112277
112819
  const { fs: fs22, paths } = ports;
112278
112820
  const servingBinary = ports.statOwnExecutable();
@@ -112399,7 +112941,7 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
112399
112941
  return await shutdown();
112400
112942
  }
112401
112943
  idleSince ??= ports.now();
112402
- if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE2) {
112944
+ if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE3) {
112403
112945
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
112404
112946
  ports.doorHealth.idleShutdown();
112405
112947
  return await shutdown();
@@ -112440,7 +112982,7 @@ var CONNECT_LIMITS = {
112440
112982
  var CA_VALIDITY_DAYS = 3650;
112441
112983
  var LEAF_VALIDITY_DAYS = 397;
112442
112984
  var CA_SUBJECT_COMMON_NAME = "agent-shim front door CA";
112443
- var MS_PER_DAY2 = 864e5;
112985
+ var MS_PER_DAY3 = 864e5;
112444
112986
  function parseConnectTarget(authority) {
112445
112987
  const colon = authority.lastIndexOf(":");
112446
112988
  if (colon === -1) {
@@ -112454,8 +112996,8 @@ function parseConnectTarget(authority) {
112454
112996
  }
112455
112997
  return { host, port };
112456
112998
  }
112457
- function servedByPipeline(path51) {
112458
- return path51?.startsWith(ROUTED_PATH_PREFIX) === true;
112999
+ function servedByPipeline(path54) {
113000
+ return path54?.startsWith(ROUTED_PATH_PREFIX) === true;
112459
113001
  }
112460
113002
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
112461
113003
  "connection",
@@ -112486,11 +113028,11 @@ function forwardableHeaders(headers) {
112486
113028
  return result;
112487
113029
  }
112488
113030
  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));
113031
+ return issueCaCertificate(CA_SUBJECT_COMMON_NAME, new Date(now.getTime() - MS_PER_DAY3), new Date(now.getTime() + CA_VALIDITY_DAYS * MS_PER_DAY3));
112490
113032
  }
112491
113033
  var LOOPBACK_LEAF_NAMES = ["127.0.0.1", "localhost"];
112492
113034
  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));
113035
+ return issueLeafCertificate(ca2, names, new Date(now.getTime() - MS_PER_DAY3), new Date(now.getTime() + LEAF_VALIDITY_DAYS * MS_PER_DAY3));
112494
113036
  }
112495
113037
  function createLeafCache(ca2, now) {
112496
113038
  const cache = /* @__PURE__ */ new Map();
@@ -112974,11 +113516,11 @@ function createRcSessionTracker(deps) {
112974
113516
  };
112975
113517
  const observeExchange = (request7) => {
112976
113518
  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)) {
113519
+ const path54 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
113520
+ if (!path54.startsWith(RC_SESSIONS_PATH_PREFIX)) {
112979
113521
  return void 0;
112980
113522
  }
112981
- const tail = path51.slice(RC_SESSIONS_PATH_PREFIX.length);
113523
+ const tail = path54.slice(RC_SESSIONS_PATH_PREFIX.length);
112982
113524
  const facts = {
112983
113525
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
112984
113526
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -113339,8 +113881,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
113339
113881
  function isRcReadFileEncoding(value2) {
113340
113882
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value2);
113341
113883
  }
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 } });
113884
+ function buildRcReadFilePayload(requestId, path54, options) {
113885
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path54, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
113344
113886
  }
113345
113887
  function buildRcFileSuggestionsPayload(requestId, query) {
113346
113888
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -113442,15 +113984,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
113442
113984
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
113443
113985
  return result.ok ? { ...result, requestId } : result;
113444
113986
  }
113445
- async function readRcSessionFile(deps, sessionId, path51, options) {
113446
- if (path51 === "") {
113987
+ async function readRcSessionFile(deps, sessionId, path54, options) {
113988
+ if (path54 === "") {
113447
113989
  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
113990
  }
113449
113991
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
113450
113992
  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
113993
  }
113452
113994
  const requestId = deps.newUuid();
113453
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path51, options), `read ${path51} from session ${sessionId}`);
113995
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path54, options), `read ${path54} from session ${sessionId}`);
113454
113996
  return result.ok ? { ...result, requestId } : result;
113455
113997
  }
113456
113998
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -113621,11 +114163,11 @@ function createRcControlHandler(deps) {
113621
114163
  path: "read-file",
113622
114164
  read: (body) => {
113623
114165
  const session = bodyString(body, "session");
113624
- const path51 = bodyString(body, "path");
114166
+ const path54 = bodyString(body, "path");
113625
114167
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
113626
114168
  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 } }) };
114169
+ const refused2 = session === void 0 || path54 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
114170
+ 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, path54, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
113629
114171
  }
113630
114172
  },
113631
114173
  {
@@ -113935,9 +114477,9 @@ function requestIdOfBody(body) {
113935
114477
  }
113936
114478
  function frontDoorRcControl(transport, token) {
113937
114479
  const headers = { authorization: `Bearer ${token}` };
113938
- const listAnswerOf = async (path51, what) => {
114480
+ const listAnswerOf = async (path54, what) => {
113939
114481
  try {
113940
- return await transport.request({ method: "GET", path: path51, headers });
114482
+ return await transport.request({ method: "GET", path: path54, headers });
113941
114483
  } catch (error63) {
113942
114484
  throw new Error(`${what}: could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}`, { cause: error63 });
113943
114485
  }
@@ -114009,10 +114551,10 @@ function frontDoorRcControl(transport, token) {
114009
114551
  }
114010
114552
  return pending;
114011
114553
  };
114012
- const writeOf = async (path51, body, describeFailure) => {
114554
+ const writeOf = async (path54, body, describeFailure) => {
114013
114555
  let answer;
114014
114556
  try {
114015
- answer = await transport.request({ method: "POST", path: path51, headers: { ...headers, "content-type": "application/json" }, body });
114557
+ answer = await transport.request({ method: "POST", path: path54, headers: { ...headers, "content-type": "application/json" }, body });
114016
114558
  } catch (error63) {
114017
114559
  return { ok: false, message: `could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}` };
114018
114560
  }
@@ -114043,10 +114585,10 @@ function frontDoorRcControl(transport, token) {
114043
114585
  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
114586
  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
114587
  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(
114588
+ readFile: async (sessionId, path54, options) => await writeOf(
114047
114589
  `${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}`
114590
+ JSON.stringify({ session: sessionId, path: path54, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
114591
+ (status, message) => `reading ${path54} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
114050
114592
  ),
114051
114593
  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
114594
  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 +114882,12 @@ function tlsFacts(options) {
114340
114882
  }
114341
114883
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
114342
114884
  const agent = new ExemptTlsAgent();
114343
- const post = async (path51, headers, body) => await new Promise((resolve2, reject) => {
114885
+ const post = async (path54, headers, body) => await new Promise((resolve2, reject) => {
114344
114886
  const options = {
114345
114887
  host: target.host,
114346
114888
  port: target.port,
114347
114889
  method: "POST",
114348
- path: path51,
114890
+ path: path54,
114349
114891
  // 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
114892
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
114351
114893
  agent
@@ -114410,12 +114952,12 @@ function lateRcStreamDial(resolve2) {
114410
114952
  }
114411
114953
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
114412
114954
  const agent = new ExemptTlsAgent();
114413
- const request7 = async (method, path51, headers, body, signal) => await new Promise((resolve2, reject) => {
114955
+ const request7 = async (method, path54, headers, body, signal) => await new Promise((resolve2, reject) => {
114414
114956
  const options = {
114415
114957
  host: target.host,
114416
114958
  port: target.port,
114417
114959
  method,
114418
- path: path51,
114960
+ path: path54,
114419
114961
  // 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
114962
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
114421
114963
  agent,
@@ -114457,9 +114999,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
114457
114999
  return { status, body: await readAll(response) };
114458
115000
  },
114459
115001
  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)}`;
115002
+ const path54 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
114461
115003
  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);
115004
+ const { status, response } = await request7("GET", path54, streamHeaders, void 0, signal);
114463
115005
  if (!isSuccessful2(status)) {
114464
115006
  await readAll(response);
114465
115007
  return { status, chunks: NO_CHUNKS };
@@ -114675,10 +115217,10 @@ init_claudeShim();
114675
115217
  init_store();
114676
115218
  init_realPorts();
114677
115219
  var import_node_fs15 = __toESM(require("node:fs"), 1);
114678
- var import_node_path40 = __toESM(require("node:path"), 1);
115220
+ var import_node_path42 = __toESM(require("node:path"), 1);
114679
115221
 
114680
115222
  // src/usage/signIn.ts
114681
- var import_node_path39 = __toESM(require("node:path"), 1);
115223
+ var import_node_path41 = __toESM(require("node:path"), 1);
114682
115224
  var CREDENTIALS_FILE = ".credentials.json";
114683
115225
  function keychainHasItem(run, account) {
114684
115226
  return run.run("security", ["find-generic-password", "-a", account]).status === 0;
@@ -114696,7 +115238,7 @@ function decideSignIn(facts) {
114696
115238
  return { state: "signed-out", detail: facts.platform === "darwin" ? `no Keychain item and no ${CREDENTIALS_FILE}` : `no ${CREDENTIALS_FILE}` };
114697
115239
  }
114698
115240
  function credentialsFilePath(farmRoot) {
114699
- return import_node_path39.default.join(farmRoot, CREDENTIALS_FILE);
115241
+ return import_node_path41.default.join(farmRoot, CREDENTIALS_FILE);
114700
115242
  }
114701
115243
  function identitySignIn(fs22, probe, identity) {
114702
115244
  const probing = !identity.hasCredentialBlock;
@@ -114822,7 +115364,7 @@ function tcpPortEraRecord(raw) {
114822
115364
  return (has("port") || has("lastPort")) && !has("socketPath");
114823
115365
  }
114824
115366
  function pushPathResolution(push, resolution) {
114825
- const ownDir = import_node_path40.default.dirname(resolution.ownExecutablePath);
115367
+ const ownDir = import_node_path42.default.dirname(resolution.ownExecutablePath);
114826
115368
  switch (resolution.agentShim.status) {
114827
115369
  case "ok":
114828
115370
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -114921,14 +115463,14 @@ function pushProvider(push, entry, cacheEnv, signIn) {
114921
115463
  }
114922
115464
  function pushLegacyName(push, params) {
114923
115465
  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) {
115466
+ if (legacyVariables.length === 0 && import_node_path42.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
114925
115467
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
114926
115468
  return;
114927
115469
  }
114928
115470
  for (const name of legacyVariables) {
114929
115471
  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
115472
  }
114931
- if (import_node_path40.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
115473
+ if (import_node_path42.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
114932
115474
  push(
114933
115475
  "legacy-name",
114934
115476
  "warn",
@@ -115301,18 +115843,18 @@ function collectDoctorReport(params) {
115301
115843
  const { paths } = params;
115302
115844
  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
115845
  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");
115846
+ const farmRoot = import_node_path42.default.join(paths.identitiesDir, name);
115847
+ const identityPath = import_node_path42.default.join(farmRoot, "identity.json");
115306
115848
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: import_node_fs15.default.existsSync(credentialsFilePath(farmRoot)) };
115307
115849
  });
115308
115850
  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
115851
  const configProfiles = profileNames.map((name) => {
115310
- const profilePath = import_node_path40.default.join(paths.configProfilesDir, `${name}.json`);
115852
+ const profilePath = import_node_path42.default.join(paths.configProfilesDir, `${name}.json`);
115311
115853
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
115312
115854
  });
115313
115855
  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
115856
  const providers = providerNames.map((name) => {
115315
- const providerPath = import_node_path40.default.join(paths.providersDir, `${name}.json`);
115857
+ const providerPath = import_node_path42.default.join(paths.providersDir, `${name}.json`);
115316
115858
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
115317
115859
  });
115318
115860
  const ownExecutablePath = realOwnExecutablePath();
@@ -115324,12 +115866,12 @@ function collectDoctorReport(params) {
115324
115866
  binaryDiscovery = { ok: false, message: error63 instanceof Error ? error63.message : String(error63) };
115325
115867
  }
115326
115868
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
115327
- const pathDirs = (params.env.PATH ?? "").split(import_node_path40.default.delimiter).filter((dir) => dir !== "");
115869
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path42.default.delimiter).filter((dir) => dir !== "");
115328
115870
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
115329
115871
  findPathShadow({
115330
115872
  pathDirs,
115331
- targetDir: import_node_path40.default.dirname(shimState.targetPath),
115332
- targetFilename: import_node_path40.default.basename(shimState.targetPath),
115873
+ targetDir: import_node_path42.default.dirname(shimState.targetPath),
115874
+ targetFilename: import_node_path42.default.basename(shimState.targetPath),
115333
115875
  findExecutableInDir
115334
115876
  }),
115335
115877
  shimState.targetPath,
@@ -115358,7 +115900,7 @@ function collectDoctorReport(params) {
115358
115900
  agentShim: refinePathShadow(
115359
115901
  findPathShadow({
115360
115902
  pathDirs,
115361
- targetDir: import_node_path40.default.dirname(ownExecutablePath),
115903
+ targetDir: import_node_path42.default.dirname(ownExecutablePath),
115362
115904
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
115363
115905
  findExecutableInDir
115364
115906
  }),
@@ -115621,11 +116163,11 @@ function tryOrUndefined(fn2) {
115621
116163
  return void 0;
115622
116164
  }
115623
116165
  }
115624
- function pathToHttpPath(path51) {
115625
- return `/${path51.map(safeEncodeURIComponent).join("/")}`;
116166
+ function pathToHttpPath(path54) {
116167
+ return `/${path54.map(safeEncodeURIComponent).join("/")}`;
115626
116168
  }
115627
- function normalizeHttpPath(path51) {
115628
- const paths = path51.split("/");
116169
+ function normalizeHttpPath(path54) {
116170
+ const paths = path54.split("/");
115629
116171
  if (paths.at(0) === "") {
115630
116172
  paths.shift();
115631
116173
  }
@@ -115810,9 +116352,9 @@ function isPlainObject2(value2) {
115810
116352
  function getOwn(object3, key) {
115811
116353
  return Object.hasOwn(object3, key) ? object3[key] : void 0;
115812
116354
  }
115813
- function get(object3, path51) {
116355
+ function get(object3, path54) {
115814
116356
  let current = object3;
115815
- for (const key of path51) {
116357
+ for (const key of path54) {
115816
116358
  if (!isTypescriptObject(current)) {
115817
116359
  return void 0;
115818
116360
  }
@@ -117035,7 +117577,7 @@ function resolveClientRest(rest) {
117035
117577
  // rest[1] can be undefined if all fields of FriendlyClientOptions are optional
117036
117578
  ];
117037
117579
  }
117038
- function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117580
+ function createORPCClient(link, { path: path54 = [], ...options } = {}) {
117039
117581
  const procedureClient = (...rest) => {
117040
117582
  const [input2, callOptions] = resolveClientRest(rest);
117041
117583
  const interceptors = [
@@ -117044,7 +117586,7 @@ function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117044
117586
  ];
117045
117587
  return intercept(
117046
117588
  interceptors,
117047
- { ...callOptions, input: input2, path: path51 },
117589
+ { ...callOptions, input: input2, path: path54 },
117048
117590
  ({ path: path210, input: input22, ...callOptions2 }) => link.call(path210, input22, callOptions2)
117049
117591
  );
117050
117592
  };
@@ -117058,7 +117600,7 @@ function createORPCClient(link, { path: path51 = [], ...options } = {}) {
117058
117600
  if (client === void 0) {
117059
117601
  client = createORPCClient(link, {
117060
117602
  ...options,
117061
- path: [...path51, key],
117603
+ path: [...path54, key],
117062
117604
  scoped: options.scoped?.[key]
117063
117605
  });
117064
117606
  cache.set(key, client);
@@ -117080,24 +117622,24 @@ var BracketNotationSerializer = class {
117080
117622
  this.internalSerialize(data, "", true, result);
117081
117623
  return result;
117082
117624
  }
117083
- internalSerialize(data, path51, isRoot, result) {
117625
+ internalSerialize(data, path54, isRoot, result) {
117084
117626
  if (Array.isArray(data)) {
117085
117627
  data.forEach((item, i10) => {
117086
- this.internalSerialize(item, isRoot ? i10.toString() : `${path51}[${i10}]`, false, result);
117628
+ this.internalSerialize(item, isRoot ? i10.toString() : `${path54}[${i10}]`, false, result);
117087
117629
  });
117088
117630
  } else if (isPlainObject2(data)) {
117089
117631
  for (const key of Object.keys(data)) {
117090
- this.internalSerialize(data[key], isRoot ? key : `${path51}[${key}]`, false, result);
117632
+ this.internalSerialize(data[key], isRoot ? key : `${path54}[${key}]`, false, result);
117091
117633
  }
117092
117634
  } else {
117093
- result.push([path51, data]);
117635
+ result.push([path54, data]);
117094
117636
  }
117095
117637
  }
117096
117638
  deserialize(serialized) {
117097
117639
  const arrayPushStyles = /* @__PURE__ */ new WeakSet();
117098
117640
  const root = new NullProtoObj();
117099
- for (const [path51, value2] of serialized) {
117100
- const segments = this.parsePath(path51);
117641
+ for (const [path54, value2] of serialized) {
117642
+ const segments = this.parsePath(path54);
117101
117643
  let currentRef = root;
117102
117644
  let nextSegment = segments[0];
117103
117645
  for (let i10 = 1; i10 < segments.length; i10++) {
@@ -117148,13 +117690,13 @@ var BracketNotationSerializer = class {
117148
117690
  }
117149
117691
  return result;
117150
117692
  }
117151
- parsePath(path51) {
117693
+ parsePath(path54) {
117152
117694
  const segments = [];
117153
117695
  let inBrackets = false;
117154
117696
  let currentSegment = "";
117155
- for (let i10 = 0; i10 < path51.length; i10++) {
117156
- const char = path51[i10];
117157
- const nextChar = path51[i10 + 1];
117697
+ for (let i10 = 0; i10 < path54.length; i10++) {
117698
+ const char = path54[i10];
117699
+ const nextChar = path54[i10 + 1];
117158
117700
  if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[")) {
117159
117701
  if (nextChar === void 0) {
117160
117702
  inBrackets = false;
@@ -117170,7 +117712,7 @@ var BracketNotationSerializer = class {
117170
117712
  currentSegment += char;
117171
117713
  }
117172
117714
  }
117173
- return inBrackets || segments.length === 0 ? [path51] : segments;
117715
+ return inBrackets || segments.length === 0 ? [path54] : segments;
117174
117716
  }
117175
117717
  };
117176
117718
  var INTEGER_PATTERN = /^0$|^[1-9]\d*$/;
@@ -117743,11 +118285,11 @@ var OpenAPISerializer = class {
117743
118285
  return json2;
117744
118286
  }
117745
118287
  const form = new FormData();
117746
- for (const [path51, value22] of this.bracketNotation.serialize(json2)) {
118288
+ for (const [path54, value22] of this.bracketNotation.serialize(json2)) {
117747
118289
  if (value22 instanceof Blob) {
117748
- form.append(path51, value22);
118290
+ form.append(path54, value22);
117749
118291
  } else if (value22 !== void 0 && value22 !== null) {
117750
- form.append(path51, String(value22));
118292
+ form.append(path54, String(value22));
117751
118293
  }
117752
118294
  }
117753
118295
  return form;
@@ -117785,30 +118327,30 @@ function isBodylessMethod(method) {
117785
118327
  return method === "GET" || method === "HEAD";
117786
118328
  }
117787
118329
  var PARAMETER_NAME_REGEX = /^[\w-]+$/;
117788
- function getDynamicPathParams(path51) {
117789
- if (!path51.includes("{")) {
118330
+ function getDynamicPathParams(path54) {
118331
+ if (!path54.includes("{")) {
117790
118332
  return void 0;
117791
118333
  }
117792
- const len = path51.length;
118334
+ const len = path54.length;
117793
118335
  let params;
117794
118336
  let index = 1;
117795
118337
  while (index < len) {
117796
118338
  const segmentStart = index;
117797
- const slashPos = path51.indexOf("/", index);
118339
+ const slashPos = path54.indexOf("/", index);
117798
118340
  const segmentEnd = slashPos === -1 ? len : slashPos;
117799
- if (segmentEnd > segmentStart && path51.charCodeAt(segmentStart) === 123 && path51.charCodeAt(segmentEnd - 1) === 125) {
118341
+ if (segmentEnd > segmentStart && path54.charCodeAt(segmentStart) === 123 && path54.charCodeAt(segmentEnd - 1) === 125) {
117800
118342
  let parameterStart = segmentStart + 1;
117801
118343
  let allowsSlash = false;
117802
- const operator = path51.charCodeAt(parameterStart);
118344
+ const operator = path54.charCodeAt(parameterStart);
117803
118345
  if (operator === 43) {
117804
118346
  allowsSlash = true;
117805
118347
  parameterStart++;
117806
118348
  }
117807
- const parameterName = path51.slice(parameterStart, segmentEnd - 1);
118349
+ const parameterName = path54.slice(parameterStart, segmentEnd - 1);
117808
118350
  if (PARAMETER_NAME_REGEX.test(parameterName)) {
117809
118351
  params ??= [];
117810
118352
  params.push({
117811
- segment: path51.slice(segmentStart, segmentEnd),
118353
+ segment: path54.slice(segmentStart, segmentEnd),
117812
118354
  startIndex: segmentStart,
117813
118355
  parameterName,
117814
118356
  allowsSlash
@@ -117851,8 +118393,8 @@ openapi.method = (method) => ({
117851
118393
  ...openapi({ method }),
117852
118394
  name: "~openapi/method"
117853
118395
  });
117854
- openapi.path = (path51) => ({
117855
- ...openapi({ path: path51 }),
118396
+ openapi.path = (path54) => ({
118397
+ ...openapi({ path: path54 }),
117856
118398
  name: "~openapi/path"
117857
118399
  });
117858
118400
  openapi.spec = (spec) => ({
@@ -118713,22 +119255,22 @@ function visitJsonSchemaRefs(value2, visit2, schemaLevel = true, seen = /* @__PU
118713
119255
  }
118714
119256
  }
118715
119257
  }
118716
- function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path51 = []) {
119258
+ function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path54 = []) {
118717
119259
  if (!value2 || typeof value2 !== "object") {
118718
119260
  return value2;
118719
119261
  }
118720
119262
  if (Array.isArray(value2)) {
118721
- return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path51, index]));
119263
+ return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path54, index]));
118722
119264
  }
118723
119265
  const result = {};
118724
119266
  for (const key of Object.keys(value2)) {
118725
119267
  const val = value2[key];
118726
119268
  if (key === "$ref" && typeof val === "string") {
118727
- setOwn(result, key, map2(val, [...path51, key]));
119269
+ setOwn(result, key, map2(val, [...path54, key]));
118728
119270
  } else if (!schemaLevel) {
118729
- setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path51, key]));
119271
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path54, key]));
118730
119272
  } 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]));
119273
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path54, key]));
118732
119274
  } else {
118733
119275
  setOwn(result, key, val);
118734
119276
  }
@@ -119258,7 +119800,7 @@ function unlazy(maybeLazy) {
119258
119800
  function createProcedureClient(lazyableProcedure, ...rest) {
119259
119801
  const options = resolveMaybeOptionalOptions(rest);
119260
119802
  return async (...[input2, callerOptions]) => {
119261
- const path51 = toArray(options.path);
119803
+ const path54 = toArray(options.path);
119262
119804
  const { default: procedure } = await unlazy(lazyableProcedure);
119263
119805
  const clientContext = callerOptions?.context ?? {};
119264
119806
  const context = await value(options.context, clientContext) ?? {};
@@ -119271,7 +119813,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
119271
119813
  };
119272
119814
  try {
119273
119815
  const output2 = await runWithSpan("call_procedure", (span) => {
119274
- span?.setAttribute("procedure.path", path51);
119816
+ span?.setAttribute("procedure.path", path54);
119275
119817
  return intercept(
119276
119818
  options.interceptors,
119277
119819
  {
@@ -119279,7 +119821,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
119279
119821
  // input can be optional if it is undefinable
119280
119822
  input: input2,
119281
119823
  errors,
119282
- path: path51,
119824
+ path: path54,
119283
119825
  procedure,
119284
119826
  signal: callerOptions?.signal,
119285
119827
  lastEventId: callerOptions?.lastEventId
@@ -119530,10 +120072,10 @@ function augmentRouter(router, options) {
119530
120072
  }
119531
120073
  return enhanced;
119532
120074
  }
119533
- function getRouter(router, path51) {
120075
+ function getRouter(router, path54) {
119534
120076
  let current = router;
119535
- for (let i10 = 0; i10 < path51.length; i10++) {
119536
- const segment = path51[i10];
120077
+ for (let i10 = 0; i10 < path54.length; i10++) {
120078
+ const segment = path54[i10];
119537
120079
  if (!isTypescriptObject(current)) {
119538
120080
  return void 0;
119539
120081
  }
@@ -119545,7 +120087,7 @@ function getRouter(router, path51) {
119545
120087
  continue;
119546
120088
  }
119547
120089
  const lazied = current;
119548
- const rest = path51.slice(i10);
120090
+ const rest = path54.slice(i10);
119549
120091
  return new Lazy({
119550
120092
  ...lazied["~orpc"],
119551
120093
  async loader() {
@@ -119560,40 +120102,40 @@ function getRouter(router, path51) {
119560
120102
  }
119561
120103
  return current;
119562
120104
  }
119563
- function walkProcedureContractsSync(router, callback, path51 = []) {
120105
+ function walkProcedureContractsSync(router, callback, path54 = []) {
119564
120106
  const lazyResults = [];
119565
- walkProcedureContractsSyncInternal(router, callback, path51.slice(), lazyResults);
120107
+ walkProcedureContractsSyncInternal(router, callback, path54.slice(), lazyResults);
119566
120108
  return lazyResults;
119567
120109
  }
119568
- function walkProcedureContractsSyncInternal(router, callback, path51, lazyResults) {
120110
+ function walkProcedureContractsSyncInternal(router, callback, path54, lazyResults) {
119569
120111
  const hiddenContract = getHiddenRouterContract(router);
119570
120112
  if (hiddenContract !== void 0) {
119571
120113
  router = hiddenContract;
119572
120114
  }
119573
120115
  if (router instanceof ProcedureContract) {
119574
- callback(router, path51.slice());
120116
+ callback(router, path54.slice());
119575
120117
  return;
119576
120118
  }
119577
120119
  if (!isTypescriptObject(router)) {
119578
120120
  return;
119579
120121
  }
119580
120122
  for (const [key, value2] of Object.entries(router)) {
119581
- path51.push(key);
120123
+ path54.push(key);
119582
120124
  if (value2 instanceof Lazy) {
119583
- lazyResults.push({ router: value2, path: path51.slice() });
120125
+ lazyResults.push({ router: value2, path: path54.slice() });
119584
120126
  } else {
119585
- walkProcedureContractsSyncInternal(value2, callback, path51, lazyResults);
120127
+ walkProcedureContractsSyncInternal(value2, callback, path54, lazyResults);
119586
120128
  }
119587
- path51.pop();
120129
+ path54.pop();
119588
120130
  }
119589
120131
  }
119590
- async function walkProcedureContractsAsync(router, callback, path51 = []) {
120132
+ async function walkProcedureContractsAsync(router, callback, path54 = []) {
119591
120133
  const hiddenContract = getHiddenRouterContract(router);
119592
120134
  if (hiddenContract !== void 0) {
119593
120135
  router = hiddenContract;
119594
120136
  }
119595
120137
  if (router instanceof ProcedureContract) {
119596
- await callback(router, path51);
120138
+ await callback(router, path54);
119597
120139
  return;
119598
120140
  }
119599
120141
  if (!isTypescriptObject(router)) {
@@ -119602,9 +120144,9 @@ async function walkProcedureContractsAsync(router, callback, path51 = []) {
119602
120144
  for (const [key, value2] of Object.entries(router)) {
119603
120145
  if (value2 instanceof Lazy) {
119604
120146
  const { default: router2 } = await unlazy(value2);
119605
- await walkProcedureContractsAsync(router2, callback, [...path51, key]);
120147
+ await walkProcedureContractsAsync(router2, callback, [...path54, key]);
119606
120148
  } else {
119607
- await walkProcedureContractsAsync(value2, callback, [...path51, key]);
120149
+ await walkProcedureContractsAsync(value2, callback, [...path54, key]);
119608
120150
  }
119609
120151
  }
119610
120152
  }
@@ -120090,18 +120632,18 @@ function rewriteComponentSchemaRefs(schema, renameMap) {
120090
120632
  }
120091
120633
  var OpenAPIGeneratorError = class extends TypeError {
120092
120634
  };
120093
- function toOpenAPIPath(path51, dynamicPathParams) {
120635
+ function toOpenAPIPath(path54, dynamicPathParams) {
120094
120636
  if (!dynamicPathParams?.length) {
120095
- return path51;
120637
+ return path54;
120096
120638
  }
120097
120639
  let normalized = "";
120098
120640
  let currentIndex = 0;
120099
120641
  for (const param of dynamicPathParams) {
120100
- normalized += path51.slice(currentIndex, param.startIndex);
120642
+ normalized += path54.slice(currentIndex, param.startIndex);
120101
120643
  normalized += `{${param.parameterName}}`;
120102
120644
  currentIndex = param.startIndex + param.segment.length;
120103
120645
  }
120104
- normalized += path51.slice(currentIndex);
120646
+ normalized += path54.slice(currentIndex);
120105
120647
  return normalized;
120106
120648
  }
120107
120649
  function buildRequest(ctx, operation, def, meta3, dynamicPathParams) {
@@ -120535,8 +121077,8 @@ var OpenAPIGenerator = class {
120535
121077
  customErrorResponseBodySchema: options.customErrorResponseBodySchema
120536
121078
  };
120537
121079
  const errors = [];
120538
- await walkProcedureContractsAsync(router, (contract, path51) => {
120539
- if (value(options.filter, contract, path51) === false) {
121080
+ await walkProcedureContractsAsync(router, (contract, path54) => {
121081
+ if (value(options.filter, contract, path54) === false) {
120540
121082
  return;
120541
121083
  }
120542
121084
  try {
@@ -120548,7 +121090,7 @@ var OpenAPIGenerator = class {
120548
121090
  `QUERY operations require OpenAPI 3.2, but version "${version2}" was requested.`
120549
121091
  );
120550
121092
  }
120551
- const postPath = meta3?.path ?? pathToHttpPath(path51);
121093
+ const postPath = meta3?.path ?? pathToHttpPath(path54);
120552
121094
  const httpPath = meta3?.prefix ? mergeHttpPath(meta3.prefix, postPath) : postPath;
120553
121095
  const dynamicPathParams = getDynamicPathParams(httpPath);
120554
121096
  const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
@@ -120557,7 +121099,7 @@ var OpenAPIGenerator = class {
120557
121099
  operation = meta3.spec;
120558
121100
  } else {
120559
121101
  operation = {
120560
- operationId: meta3?.operationId ?? path51.join("."),
121102
+ operationId: meta3?.operationId ?? path54.join("."),
120561
121103
  summary: meta3?.summary,
120562
121104
  description: meta3?.description,
120563
121105
  deprecated: meta3?.deprecated,
@@ -120577,7 +121119,7 @@ var OpenAPIGenerator = class {
120577
121119
  if (!(e14 instanceof OpenAPIGeneratorError)) {
120578
121120
  throw e14;
120579
121121
  }
120580
- errors.push(`Procedure at ${path51.join(".") || "(root)"}: ${e14.message}`);
121122
+ errors.push(`Procedure at ${path54.join(".") || "(root)"}: ${e14.message}`);
120581
121123
  }
120582
121124
  });
120583
121125
  if (errors.length) {
@@ -120885,7 +121427,7 @@ var ResetRowSchema = external_exports.strictObject({
120885
121427
  var ResetScheduleSchema = external_exports.strictObject({ resets: external_exports.readonly(external_exports.array(ResetRowSchema)) });
120886
121428
 
120887
121429
  // src/frontdoor/controlSchemas.ts
120888
- var import_node_path41 = __toESM(require("node:path"), 1);
121430
+ var import_node_path43 = __toESM(require("node:path"), 1);
120889
121431
  init_zod();
120890
121432
  init_schema2();
120891
121433
 
@@ -121097,11 +121639,11 @@ var FrontDoorSessionsOutputSchema = external_exports.strictObject({ sessions: ex
121097
121639
  var CheckRunInputSchema = external_exports.strictObject({
121098
121640
  path: external_exports.string().min(1),
121099
121641
  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" });
121642
+ }).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" });
121101
121643
  var PoolPickInputSchema = external_exports.strictObject({
121102
121644
  pool: external_exports.string().min(1),
121103
121645
  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" });
121646
+ }).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" });
121105
121647
  var DoctorFindingSchema = external_exports.strictObject({
121106
121648
  section: external_exports.enum(DOCTOR_SECTIONS),
121107
121649
  subject: external_exports.string().optional(),
@@ -121422,16 +121964,16 @@ var StandardLink = class {
121422
121964
  /**
121423
121965
  * @throws ORPCError, transport-level errors (network failures, timeouts, etc.)
121424
121966
  */
121425
- call(path51, input2, options) {
121426
- return runWithSpan(`${ORPC_NAME}.${path51.join("/")}`, (span) => {
121967
+ call(path54, input2, options) {
121968
+ return runWithSpan(`${ORPC_NAME}.${path54.join("/")}`, (span) => {
121427
121969
  span?.setAttribute("rpc.system", ORPC_NAME);
121428
- span?.setAttribute("rpc.method", path51.join("."));
121970
+ span?.setAttribute("rpc.method", path54.join("."));
121429
121971
  if (getTracer() && isAsyncIteratorObject(input2)) {
121430
121972
  input2 = override(input2, traceAsyncIterator("consume_async_iterator_object_input", input2));
121431
121973
  } else if (getTracer() && input2 instanceof ReadableStream) {
121432
121974
  input2 = override(input2, traceReadableStream("consume_octet_stream_input", input2));
121433
121975
  }
121434
- return intercept(this.interceptors, { ...options, path: path51, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
121976
+ return intercept(this.interceptors, { ...options, path: path54, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
121435
121977
  const tracer = getTracer();
121436
121978
  const activeSpan = tracer?.getActiveSpan() ?? span;
121437
121979
  let request7 = await runWithSpan(
@@ -121488,18 +122030,18 @@ var RPCLinkCodec = class {
121488
122030
  this.headers = options.headers ?? {};
121489
122031
  this.serializer = options.serializer ?? new RPCSerializer();
121490
122032
  }
121491
- async encodeInput(input2, path51, options) {
121492
- let headers = toResolvedStandardHeaders(await value(this.headers, options, path51, input2));
122033
+ async encodeInput(input2, path54, options) {
122034
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path54, input2));
121493
122035
  if (options.lastEventId !== void 0) {
121494
122036
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
121495
122037
  }
121496
- const expectedMethod = await value(this.expectedMethod, options, path51, input2);
121497
- const baseUrl = await value(this.baseUrl, options, path51, input2);
122038
+ const expectedMethod = await value(this.expectedMethod, options, path54, input2);
122039
+ const baseUrl = await value(this.baseUrl, options, path54, input2);
121498
122040
  const [pathname, search, hash2] = parseStandardUrl(baseUrl);
121499
- const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path51)}`;
122041
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path54)}`;
121500
122042
  const serialized = this.serializer.serialize(input2);
121501
122043
  if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
121502
- const maxUrlLength = await value(this.maxUrlLength, options, path51, input2);
122044
+ const maxUrlLength = await value(this.maxUrlLength, options, path54, input2);
121503
122045
  const mergedSearch = new URLSearchParams(search);
121504
122046
  mergedSearch.append("data", stringifyJSON(serialized) ?? "");
121505
122047
  const url22 = `${newPathname}?${mergedSearch}${hash2 ?? ""}`;
@@ -121584,8 +122126,8 @@ var FetchLinkTransport = class {
121584
122126
  this.fetch = options.fetch ?? ((url2, init) => globalThis.fetch(url2, init));
121585
122127
  this.toFetchRequestOptions = options.toFetchRequest;
121586
122128
  }
121587
- async send(standardRequest, path51, options) {
121588
- let origin = await value(this.origin, options, path51);
122129
+ async send(standardRequest, path54, options) {
122130
+ let origin = await value(this.origin, options, path54);
121589
122131
  if (origin?.endsWith("/")) {
121590
122132
  origin = origin.slice(0, -1);
121591
122133
  }
@@ -121605,7 +122147,7 @@ var FetchLinkTransport = class {
121605
122147
  }
121606
122148
  }
121607
122149
  const fetch3 = this.fetch;
121608
- const response = await fetch3(url2, init, options, path51);
122150
+ const response = await fetch3(url2, init, options, path54);
121609
122151
  const standardResponse = toStandardLazyResponse(response);
121610
122152
  return standardResponse;
121611
122153
  }
@@ -121996,14 +122538,14 @@ var StandardHandler = class {
121996
122538
  span?.setAttribute("url.path", request22.url);
121997
122539
  return { matched: false };
121998
122540
  }
121999
- const { path: path51, procedure, decodeInput } = matchedOrNot;
122000
- span?.updateName(`${ORPC_NAME}.${path51.join("/")}`);
122541
+ const { path: path54, procedure, decodeInput } = matchedOrNot;
122542
+ span?.updateName(`${ORPC_NAME}.${path54.join("/")}`);
122001
122543
  span?.setAttribute("rpc.system", ORPC_NAME);
122002
- span?.setAttribute("rpc.method", path51.join("."));
122544
+ span?.setAttribute("rpc.method", path54.join("."));
122003
122545
  try {
122004
122546
  const response = await intercept(
122005
122547
  this.interceptors,
122006
- { context: context2, prefix: prefix2, request: request22, path: path51, procedure, decodeInput },
122548
+ { context: context2, prefix: prefix2, request: request22, path: path54, procedure, decodeInput },
122007
122549
  async ({ context: context3, prefix: prefix3, request: request32, path: path210, procedure: procedure2, decodeInput: decodeInput2 }) => {
122008
122550
  step2 = "decode_input";
122009
122551
  let input2 = await runWithSpan("decode_input", decodeInput2);
@@ -122037,7 +122579,7 @@ var StandardHandler = class {
122037
122579
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
122038
122580
  cause: e14
122039
122581
  }) : toORPCError(e14);
122040
- const response = await this.codec.encodeError(error63, procedure, path51, { context: context2, prefix: prefix2 });
122582
+ const response = await this.codec.encodeError(error63, procedure, path54, { context: context2, prefix: prefix2 });
122041
122583
  return { matched: true, response };
122042
122584
  }
122043
122585
  }
@@ -122143,7 +122685,7 @@ var RPCMatcher = class {
122143
122685
  this.rootRouter = router;
122144
122686
  this.index(router);
122145
122687
  }
122146
- index(router, path51 = []) {
122688
+ index(router, path54 = []) {
122147
122689
  const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
122148
122690
  if (!value(this.filter, procedure, procedurePath)) {
122149
122691
  return;
@@ -122154,7 +122696,7 @@ var RPCMatcher = class {
122154
122696
  // contract-first entries have no implementation yet, resolveProcedure fills it in on demand
122155
122697
  procedure: procedure instanceof Procedure ? procedure : void 0
122156
122698
  });
122157
- }, path51);
122699
+ }, path54);
122158
122700
  for (const result of lazyResults) {
122159
122701
  this.pendingLazyRouters.set(pathToHttpPath(result.path), result);
122160
122702
  }
@@ -122286,10 +122828,10 @@ var RPCHandlerCodec = class {
122286
122828
  }
122287
122829
  };
122288
122830
  }
122289
- encodeOutput(output2, procedure, path51, options) {
122831
+ encodeOutput(output2, procedure, path54, options) {
122290
122832
  return {
122291
122833
  headers: {},
122292
- status: value(this.outputStatus, output2, procedure, path51, options) ?? DEFAULT_SUCCESS_STATUS,
122834
+ status: value(this.outputStatus, output2, procedure, path54, options) ?? DEFAULT_SUCCESS_STATUS,
122293
122835
  body: this.serializer.serialize(output2)
122294
122836
  };
122295
122837
  }
@@ -122343,39 +122885,39 @@ function createRouter() {
122343
122885
  static: new NullProtoObj2()
122344
122886
  };
122345
122887
  }
122346
- function scanFirstGroup(path51) {
122888
+ function scanFirstGroup(path54) {
122347
122889
  let i10 = 0;
122348
122890
  let depth = 0;
122349
- for (; i10 < path51.length; i10++) {
122350
- const c10 = path51.charCodeAt(i10);
122891
+ for (; i10 < path54.length; i10++) {
122892
+ const c10 = path54.charCodeAt(i10);
122351
122893
  if (c10 === 92) i10++;
122352
122894
  else if (c10 === 40) depth++;
122353
122895
  else if (c10 === 41 && depth > 0) depth--;
122354
122896
  else if (c10 === 123 && depth === 0) break;
122355
122897
  }
122356
- if (i10 >= path51.length) return;
122898
+ if (i10 >= path54.length) return;
122357
122899
  let j10 = i10 + 1;
122358
122900
  depth = 0;
122359
- for (; j10 < path51.length; j10++) {
122360
- const c10 = path51.charCodeAt(j10);
122901
+ for (; j10 < path54.length; j10++) {
122902
+ const c10 = path54.charCodeAt(j10);
122361
122903
  if (c10 === 92) j10++;
122362
122904
  else if (c10 === 40) depth++;
122363
122905
  else if (c10 === 41 && depth > 0) depth--;
122364
122906
  else if (c10 === 125 && depth === 0) break;
122365
122907
  }
122366
- if (j10 >= path51.length) return;
122367
- const mod = path51[j10 + 1];
122908
+ if (j10 >= path54.length) return;
122909
+ const mod = path54[j10 + 1];
122368
122910
  const hasMod = mod === "?" || mod === "+" || mod === "*";
122369
122911
  return [
122370
- path51.slice(0, i10),
122371
- path51.slice(i10 + 1, j10),
122372
- path51.slice(j10 + (hasMod ? 2 : 1)),
122912
+ path54.slice(0, i10),
122913
+ path54.slice(i10 + 1, j10),
122914
+ path54.slice(j10 + (hasMod ? 2 : 1)),
122373
122915
  hasMod ? mod : void 0
122374
122916
  ];
122375
122917
  }
122376
- function expandGroupDelimiters(path51) {
122377
- if (!path51.includes("{")) return;
122378
- const group = scanFirstGroup(path51);
122918
+ function expandGroupDelimiters(path54) {
122919
+ if (!path54.includes("{")) return;
122920
+ const group = scanFirstGroup(path54);
122379
122921
  if (!group) return;
122380
122922
  const [pre2, body, suf, mod] = group;
122381
122923
  if (!mod) return [pre2 + body + suf];
@@ -122445,9 +122987,9 @@ function replaceSegmentWildcards(segment, unnamedStart, toGroupKey = toUnnamedGr
122445
122987
  }
122446
122988
  return [replaced, nextIndex];
122447
122989
  }
122448
- function encodeEscapes(path51) {
122449
- if (!path51.includes("\\")) return path51;
122450
- return path51.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
122990
+ function encodeEscapes(path54) {
122991
+ if (!path54.includes("\\")) return path54;
122992
+ return path54.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
122451
122993
  }
122452
122994
  function segmentKey(segment) {
122453
122995
  if (segment.startsWith("**")) return 2;
@@ -122476,22 +123018,22 @@ function expandModifiers(segments) {
122476
123018
  return m10[2] === "+" ? [wc2] : [wc2, without];
122477
123019
  }
122478
123020
  }
122479
- function normalizePath(path51) {
122480
- if (!path51.includes("/.")) return path51;
123021
+ function normalizePath(path54) {
123022
+ if (!path54.includes("/.")) return path54;
122481
123023
  const r10 = [];
122482
- for (const s of path51.split("/")) if (s === ".") continue;
123024
+ for (const s of path54.split("/")) if (s === ".") continue;
122483
123025
  else if (s === ".." && r10.length > 1) r10.pop();
122484
123026
  else r10.push(s);
122485
123027
  return r10.join("/") || "/";
122486
123028
  }
122487
- function splitPath(path51) {
122488
- const s = path51.split("/");
123029
+ function splitPath(path54) {
123030
+ const s = path54.split("/");
122489
123031
  s.shift();
122490
123032
  if (s[s.length - 1] === "") s.pop();
122491
123033
  return s;
122492
123034
  }
122493
- function splitRoute(path51) {
122494
- const s = splitPath(path51);
123035
+ function splitRoute(path54) {
123036
+ const s = splitPath(path54);
122495
123037
  while (s[s.length - 1] === "") s.pop();
122496
123038
  return s;
122497
123039
  }
@@ -122507,16 +123049,16 @@ function getMatchParams(segments, paramsMap) {
122507
123049
  }
122508
123050
  return params;
122509
123051
  }
122510
- function addRoute(ctx, method = "", path51, data) {
123052
+ function addRoute(ctx, method = "", path54, data) {
122511
123053
  method = method.toUpperCase();
122512
- if (path51.charCodeAt(0) !== 47) path51 = `/${path51}`;
122513
- const groupExpanded = expandGroupDelimiters(path51);
123054
+ if (path54.charCodeAt(0) !== 47) path54 = `/${path54}`;
123055
+ const groupExpanded = expandGroupDelimiters(path54);
122514
123056
  if (groupExpanded) {
122515
123057
  for (const expandedPath of groupExpanded) addRoute(ctx, method, expandedPath, data);
122516
123058
  return;
122517
123059
  }
122518
- path51 = encodeEscapes(path51);
122519
- const segments = splitRoute(path51);
123060
+ path54 = encodeEscapes(path54);
123061
+ const segments = splitRoute(path54);
122520
123062
  const expanded = expandModifiers(segments);
122521
123063
  if (expanded) {
122522
123064
  for (const p of expanded) addRoute(ctx, method, p, data);
@@ -122607,15 +123149,15 @@ function getParamRegexp(segment, unnamedStart = 0) {
122607
123149
  const regex = _s2.replace(/:([\w-]+)(?:\(([^)]*)\))?/g, (_, id2, p) => `(?<${toGroupName(id2)}>${p || "[^/]+"})`).replace(/\((?![?<])/g, () => `(?<${toUnnamedGroupKey(_i2++)}>`).replace(/\uFFFE(.)/g, (_, c10) => /[.*+?^${}()|[\]\\]/.test(c10) ? `\\${c10}` : c10);
122608
123150
  return [new RegExp(`^${regex}$`), _i2];
122609
123151
  }
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];
123152
+ function findRoute(ctx, method = "", path54, opts) {
123153
+ if (opts?.normalize) path54 = normalizePath(path54);
123154
+ if (path54.charCodeAt(path54.length - 1) === 47) path54 = path54.slice(0, -1);
123155
+ const staticNode = ctx.static[path54];
122614
123156
  if (staticNode && staticNode.methods) {
122615
123157
  const staticMatch = staticNode.methods[method] || staticNode.methods[""];
122616
123158
  if (staticMatch !== void 0) return staticMatch[0];
122617
123159
  }
122618
- const segments = splitPath(path51);
123160
+ const segments = splitPath(path54);
122619
123161
  const match = _lookupTree(ctx.root, method, segments, 0);
122620
123162
  if (match === void 0) return;
122621
123163
  if (opts?.params === false) return match;
@@ -122815,7 +123357,7 @@ var OpenAPIMatcher = class {
122815
123357
  this.rootRouter = router;
122816
123358
  this.index(router);
122817
123359
  }
122818
- index(router, path51 = []) {
123360
+ index(router, path54 = []) {
122819
123361
  const lazyResults = walkProcedureContractsSync(router, (contract, path210) => {
122820
123362
  if (!value(this.filter, contract, path210)) {
122821
123363
  return;
@@ -122830,7 +123372,7 @@ var OpenAPIMatcher = class {
122830
123372
  contract,
122831
123373
  procedure: contract instanceof Procedure ? contract : void 0
122832
123374
  });
122833
- }, path51);
123375
+ }, path54);
122834
123376
  for (const result of lazyResults) {
122835
123377
  const prefix = getOpenAPIMeta(result.router)?.prefix;
122836
123378
  this.pendingLazyRouters.add({
@@ -122917,20 +123459,20 @@ var OpenAPIMatcher = class {
122917
123459
  return entry.procedure;
122918
123460
  }
122919
123461
  };
122920
- function toRou3Pattern(path51) {
122921
- const params = getDynamicPathParams(path51);
123462
+ function toRou3Pattern(path54) {
123463
+ const params = getDynamicPathParams(path54);
122922
123464
  if (!params?.length) {
122923
- return path51;
123465
+ return path54;
122924
123466
  }
122925
123467
  for (let i10 = params.length - 1; i10 >= 0; i10--) {
122926
123468
  const param = params[i10];
122927
123469
  const pattern = param.allowsSlash ? `**:${param.parameterName}` : `:${param.parameterName}`;
122928
- path51 = path51.slice(0, param.startIndex) + pattern + path51.slice(param.startIndex + param.segment.length);
123470
+ path54 = path54.slice(0, param.startIndex) + pattern + path54.slice(param.startIndex + param.segment.length);
122929
123471
  }
122930
- return path51;
123472
+ return path54;
122931
123473
  }
122932
- function toRou3PrefixMatcher(path51) {
122933
- const pattern = toRou3Pattern(path51);
123474
+ function toRou3PrefixMatcher(path54) {
123475
+ const pattern = toRou3Pattern(path54);
122934
123476
  return routeToRegExp(pattern === "/" ? "/**" : `${pattern}/**`);
122935
123477
  }
122936
123478
  function decodeParams(params) {
@@ -123009,7 +123551,7 @@ var OpenAPIHandlerCodecCore = class {
123009
123551
  /**
123010
123552
  * @throws {TypeError} If `outputStructure` is "detailed" and the output doesn't match the expected structure.
123011
123553
  */
123012
- encodeOutput(output2, procedure, path51) {
123554
+ encodeOutput(output2, procedure, path54) {
123013
123555
  const meta3 = getOpenAPIMeta(procedure);
123014
123556
  const successStatus = meta3?.successStatus ?? DEFAULT_SUCCESS_STATUS;
123015
123557
  const outputStructure = meta3?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
@@ -123022,7 +123564,7 @@ var OpenAPIHandlerCodecCore = class {
123022
123564
  }
123023
123565
  if (!isValidDetailedOutput(output2)) {
123024
123566
  throw new TypeError(`
123025
- Invalid "detailed" output structure returned by procedure (${path51.join(".")}):
123567
+ Invalid "detailed" output structure returned by procedure (${path54.join(".")}):
123026
123568
  \u2022 Expected an object with optional properties:
123027
123569
  - status (number <400)
123028
123570
  - headers (object)
@@ -123410,7 +123952,8 @@ var IdentityValueSchema = external_exports.strictObject({
123410
123952
  name: external_exports.string(),
123411
123953
  defaultConfigProfile: external_exports.string().optional(),
123412
123954
  allowAmbientCredential: external_exports.boolean(),
123413
- credential: CredentialSummarySchema2.optional()
123955
+ credential: CredentialSummarySchema2.optional(),
123956
+ anchors: external_exports.array(AnchorSchema).optional()
123414
123957
  });
123415
123958
  var ProfileValueSchema = ConfigProfileSchema.omit({ $schema: true });
123416
123959
  var ProviderValueSchema = external_exports.strictObject({
@@ -123428,7 +123971,9 @@ var ConfigIdentitySetInputSchema = external_exports.strictObject({
123428
123971
  name: external_exports.string().min(1),
123429
123972
  defaultConfigProfile: external_exports.union([external_exports.string().min(1), external_exports.literal(false)]).optional(),
123430
123973
  allowAmbientCredential: external_exports.boolean().optional(),
123431
- credential: external_exports.union([external_exports.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional()
123974
+ credential: external_exports.union([external_exports.literal(false), CredentialWriteSchema(CREDENTIAL_TARGETS)]).optional(),
123975
+ /** `false` removes the anchors; a list replaces them. */
123976
+ anchors: external_exports.union([external_exports.literal(false), external_exports.array(AnchorSchema).min(1)]).optional()
123432
123977
  });
123433
123978
  var ConfigIdentitySetOutputSchema = storedMutationOutput("identity", "updated", IdentityValueSchema);
123434
123979
  var ConfigIdentityRemoveInputSchema = external_exports.strictObject({ name: external_exports.string().min(1), confirm: RemovalConfirmationSchema });
@@ -123549,7 +124094,8 @@ function identityValue(name, paths) {
123549
124094
  name: identity.name,
123550
124095
  ...identity.defaultConfigProfile === void 0 ? {} : { defaultConfigProfile: identity.defaultConfigProfile },
123551
124096
  allowAmbientCredential: identity.allowAmbientCredential,
123552
- ...identity.credential === void 0 ? {} : { credential: summariseCredential(identity.credential) }
124097
+ ...identity.credential === void 0 ? {} : { credential: summariseCredential(identity.credential) },
124098
+ ...identity.anchors === void 0 ? {} : { anchors: identity.anchors }
123553
124099
  };
123554
124100
  }
123555
124101
  function providerValue(name, provider) {
@@ -123570,7 +124116,7 @@ function profileValue(name, paths) {
123570
124116
  function createConfigApiRouter(deps) {
123571
124117
  const authed = doorApiAuth(deps.expectedToken);
123572
124118
  const { paths } = deps;
123573
- const route = (path51, summary) => authed.meta(openapi({ method: "POST", path: path51, summary, tags: [CONFIG_API_TAG] }));
124119
+ const route = (path54, summary) => authed.meta(openapi({ method: "POST", path: path54, summary, tags: [CONFIG_API_TAG] }));
123574
124120
  return {
123575
124121
  config: {
123576
124122
  identity: {
@@ -123580,9 +124126,9 @@ function createConfigApiRouter(deps) {
123580
124126
  return { action: "created", kind: "identity", name: input2.name, value: identityValue(input2.name, paths) };
123581
124127
  })
123582
124128
  ),
123583
- set: route("/rest/config/identity/set", "Update an identity's default profile, ambient-credential setting or credential").input(ConfigIdentitySetInputSchema).output(ConfigIdentitySetOutputSchema).handler(
124129
+ set: route("/rest/config/identity/set", "Update an identity's default profile, ambient-credential setting, credential or anchors").input(ConfigIdentitySetInputSchema).output(ConfigIdentitySetOutputSchema).handler(
123584
124130
  ({ input: input2 }) => guarded(() => {
123585
- requireChange(input2.defaultConfigProfile !== void 0 || input2.allowAmbientCredential !== void 0 || input2.credential !== void 0, "defaultConfigProfile, allowAmbientCredential or credential");
124131
+ requireChange(input2.defaultConfigProfile !== void 0 || input2.allowAmbientCredential !== void 0 || input2.credential !== void 0 || input2.anchors !== void 0, "defaultConfigProfile, allowAmbientCredential, credential or anchors");
123586
124132
  if (!identityExists(paths, input2.name)) {
123587
124133
  throw new IdentityNotFoundError(input2.name);
123588
124134
  }
@@ -123607,6 +124153,9 @@ function createConfigApiRouter(deps) {
123607
124153
  };
123608
124154
  setIdentityCredential(paths, input2.name, change);
123609
124155
  }
124156
+ if (input2.anchors !== void 0) {
124157
+ setIdentityAnchors(paths, input2.name, input2.anchors === false ? void 0 : input2.anchors);
124158
+ }
123610
124159
  return { action: "updated", kind: "identity", name: input2.name, value: identityValue(input2.name, paths) };
123611
124160
  })
123612
124161
  ),
@@ -123922,7 +124471,7 @@ function createLifecycleApiRouter(deps) {
123922
124471
  init_cliError();
123923
124472
 
123924
124473
  // src/frontdoor/launchSchemas.ts
123925
- var import_node_path42 = __toESM(require("node:path"), 1);
124474
+ var import_node_path44 = __toESM(require("node:path"), 1);
123926
124475
  init_zod();
123927
124476
  init_claudeVersion();
123928
124477
  init_identity();
@@ -123932,7 +124481,7 @@ var LaunchResolveInputSchema = external_exports.strictObject({
123932
124481
  argv: external_exports.readonly(external_exports.array(external_exports.string())).optional(),
123933
124482
  /** 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
124483
  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" });
124484
+ }).refine((input2) => import_node_path44.default.isAbsolute(input2.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
123936
124485
  var LaunchPoolDecisionSchema = external_exports.strictObject({
123937
124486
  name: external_exports.string(),
123938
124487
  reasons: external_exports.readonly(external_exports.array(external_exports.string())),
@@ -124208,11 +124757,11 @@ function rcFanoutOnDoorHub(fanout, hub) {
124208
124757
  // src/frontdoor/quotaExpiringEvents.ts
124209
124758
  init_schema2();
124210
124759
  var MS_PER_HOUR4 = 36e5;
124211
- var MS_PER_DAY3 = 864e5;
124760
+ var MS_PER_DAY4 = 864e5;
124212
124761
  var FIVE_HOUR_WINDOW_HOURS = 5;
124213
124762
  var SEVEN_DAY_WINDOW_DAYS = 7;
124214
124763
  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;
124764
+ var SEVEN_DAY_WINDOW_MS2 = SEVEN_DAY_WINDOW_DAYS * MS_PER_DAY4;
124216
124765
  var FINAL_SPAN_DENOMINATOR = 30;
124217
124766
  var QUOTA_EXPIRING_WINDOW_FRACTION = 1 / FINAL_SPAN_DENOMINATOR;
124218
124767
  function createQuotaExpiringPublisher(hub, deps) {
@@ -125010,17 +125559,17 @@ function unifiedQuotaHeaders(upstream, rejected, quotaError) {
125010
125559
  }
125011
125560
  return headers;
125012
125561
  }
125013
- var MS_PER_SECOND7 = 1e3;
125562
+ var MS_PER_SECOND8 = 1e3;
125014
125563
  function buildUsageSnapshot(upstream, quotaError, nowMs) {
125015
125564
  const used7 = upstream.get("x-codex-primary-used-percent") ?? (quotaError === void 0 ? null : EXHAUSTED_PERCENT);
125016
125565
  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;
125566
+ const sevenDay = used7 !== null && reset7 !== null ? { used_percentage: Number(used7), resets_at: new Date(Number(reset7) * MS_PER_SECOND8).toISOString() } : void 0;
125018
125567
  let fiveHour;
125019
125568
  if (Number(upstream.get("x-codex-secondary-window-minutes")) > 0) {
125020
125569
  const used5 = upstream.get("x-codex-secondary-used-percent");
125021
125570
  const reset5 = upstream.get("x-codex-secondary-reset-at");
125022
125571
  if (used5 !== null && reset5 !== null) {
125023
- fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND7).toISOString() };
125572
+ fiveHour = { used_percentage: Number(used5), resets_at: new Date(Number(reset5) * MS_PER_SECOND8).toISOString() };
125024
125573
  }
125025
125574
  }
125026
125575
  if (sevenDay === void 0 && fiveHour === void 0) {
@@ -125429,8 +125978,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
125429
125978
  request7.body.resume();
125430
125979
  return;
125431
125980
  }
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 };
125981
+ const path54 = new URL(request7.url, "http://127.0.0.1").pathname;
125982
+ const translated = { method: request7.method, path: path54, body, signal: request7.signal };
125434
125983
  const routed = await route(translated);
125435
125984
  if (request7.signal.aborted) {
125436
125985
  return;
@@ -125464,7 +126013,7 @@ function createPassthroughRoute(name, target) {
125464
126013
  headroomUpstream: target.headroomUpstream,
125465
126014
  serve: async (request7, response) => {
125466
126015
  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;
126016
+ const path54 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
125468
126017
  const headers = forwardableHeaders(request7.headers);
125469
126018
  delete headers.host;
125470
126019
  await new Promise((resolve2) => {
@@ -125472,7 +126021,7 @@ function createPassthroughRoute(name, target) {
125472
126021
  host: base.hostname,
125473
126022
  port: base.port === "" ? void 0 : Number(base.port),
125474
126023
  method: request7.method,
125475
- path: `${basePath}${path51}${incoming.search}`,
126024
+ path: `${basePath}${path54}${incoming.search}`,
125476
126025
  headers,
125477
126026
  agent
125478
126027
  };
@@ -125605,7 +126154,7 @@ async function scanRequestHead(request7, wholeBody = false) {
125605
126154
 
125606
126155
  // src/frontdoor/providerRoute.ts
125607
126156
  function createProviderRouteResolver(deps) {
125608
- const isRcSelfHostPath = (path51) => path51 === "/v1/code/sessions" || path51.startsWith("/v1/code/sessions/") || path51 === "/v1/sessions" || path51.startsWith("/v1/sessions/");
126157
+ const isRcSelfHostPath = (path54) => path54 === "/v1/code/sessions" || path54.startsWith("/v1/code/sessions/") || path54 === "/v1/sessions" || path54.startsWith("/v1/sessions/");
125609
126158
  const oauthRoute = createPassthroughRoute("anthropic", { baseUrl: `https://${CONNECT_INTERCEPT_HOST}:${String(HTTPS_PORT)}`, stripPrefix: void 0, headroomUpstream: void 0 });
125610
126159
  const passthroughByTarget = /* @__PURE__ */ new Map();
125611
126160
  const passthroughFor = (name, target) => {
@@ -125619,16 +126168,16 @@ function createProviderRouteResolver(deps) {
125619
126168
  return route;
125620
126169
  };
125621
126170
  const resolve2 = (request7) => {
125622
- const path51 = new URL(request7.url, "http://127.0.0.1").pathname;
125623
- const scoped = parseProviderPath(path51);
126171
+ const path54 = new URL(request7.url, "http://127.0.0.1").pathname;
126172
+ const scoped = parseProviderPath(path54);
125624
126173
  if (scoped === void 0) {
125625
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path51)) {
126174
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path54)) {
125626
126175
  return { ok: true, route: deps.rcSelfHostRoute };
125627
126176
  }
125628
- if (request7.session.provider !== void 0 && path51.startsWith("/v1/") && !isRcSelfHostPath(path51)) {
126177
+ if (request7.session.provider !== void 0 && path54.startsWith("/v1/") && !isRcSelfHostPath(path54)) {
125629
126178
  return resolve2({ ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` });
125630
126179
  }
125631
- return path51.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path51}` };
126180
+ return path54.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path54}` };
125632
126181
  }
125633
126182
  const { provider } = scoped;
125634
126183
  let definition;
@@ -125681,8 +126230,8 @@ function createProviderRouteResolver(deps) {
125681
126230
  let replay;
125682
126231
  const visited = /* @__PURE__ */ new Set();
125683
126232
  for (; ; ) {
125684
- const path51 = new URL(current.url, "http://127.0.0.1").pathname;
125685
- const scoped = parseProviderPath(path51);
126233
+ const path54 = new URL(current.url, "http://127.0.0.1").pathname;
126234
+ const scoped = parseProviderPath(path54);
125686
126235
  const providerName = scoped?.provider ?? current.session.provider;
125687
126236
  if (providerName !== void 0 && visited.has(providerName)) {
125688
126237
  return { ok: false, status: HTTP_STATUS.internalServerError, message: `provider routing cycle: ${[...visited, providerName].join(" -> ")}` };
@@ -125740,7 +126289,7 @@ function createProviderRouteResolver(deps) {
125740
126289
  const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
125741
126290
  replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
125742
126291
  }
125743
- const rest = scoped === void 0 ? path51 : path51.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
126292
+ const rest = scoped === void 0 ? path54 : path54.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
125744
126293
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
125745
126294
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
125746
126295
  }
@@ -125847,14 +126396,14 @@ function createRcLiveUsage(deps) {
125847
126396
  }
125848
126397
 
125849
126398
  // src/frontdoor/rcSelfHostMint.ts
125850
- var import_node_path43 = __toESM(require("node:path"), 1);
126399
+ var import_node_path45 = __toESM(require("node:path"), 1);
125851
126400
  init_account();
125852
126401
 
125853
126402
  // src/frontdoor/rcSelfHostLocal.ts
125854
126403
  var RC_SELF_HOST_OAUTH_HOST = "platform.claude.com";
125855
126404
  var RC_SELF_HOST_SCOPE_LIST = ["user:profile", "user:inference", "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
125856
126405
  var RC_SELF_HOST_OAUTH_TOKEN_TTL_SECONDS = 3600;
125857
- var MS_PER_SECOND8 = 1e3;
126406
+ var MS_PER_SECOND9 = 1e3;
125858
126407
  var HTTP_SERVICE_UNAVAILABLE = 503;
125859
126408
  function isRecord6(value2) {
125860
126409
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
@@ -125910,7 +126459,7 @@ function createRcSelfHostLocal(deps) {
125910
126459
  }
125911
126460
  if (method === "POST" && pathname.startsWith("/api/eval/")) {
125912
126461
  await deps.readBody(request7, CONTROL_BODY_CAP_BYTES);
125913
- answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND8) });
126462
+ answerServerJson(response, HTTP_STATUS.ok, { features: growthBookFeatures(), dateUpdated: Math.floor(deps.now() / MS_PER_SECOND9) });
125914
126463
  return true;
125915
126464
  }
125916
126465
  if (method === "GET" && pathname === "/api/oauth/profile") {
@@ -125977,7 +126526,7 @@ function readJsonObject(fs22, file2) {
125977
126526
  return isRecord7(parsed) ? parsed : void 0;
125978
126527
  }
125979
126528
  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));
126529
+ const parsed = readJsonObject(fs22, import_node_path45.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
125981
126530
  if (parsed === void 0) {
125982
126531
  return void 0;
125983
126532
  }
@@ -125991,11 +126540,11 @@ function mintRcSelfHostCredential(deps) {
125991
126540
  if (!isIdentityName(deps.identity)) {
125992
126541
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
125993
126542
  }
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);
126543
+ const identityDir = import_node_path45.default.join(deps.identitiesDir, deps.identity);
126544
+ const credentialsFile = import_node_path45.default.join(identityDir, CREDENTIALS_FILE2);
126545
+ const claudeJsonFile = import_node_path45.default.join(identityDir, CLAUDE_JSON2);
126546
+ const recordDir = import_node_path45.default.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
126547
+ const recordFile = import_node_path45.default.join(recordDir, RC_SELF_HOST_RECORD_FILE);
125999
126548
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
126000
126549
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
126001
126550
  const existingOauth = isRecord7(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -126011,7 +126560,7 @@ function mintRcSelfHostCredential(deps) {
126011
126560
  const organizationUuid = deps.newUuid();
126012
126561
  const accountUuid = deps.newUuid();
126013
126562
  const mintedAt = new Date(deps.now()).toISOString();
126014
- deps.fs.mkdirPrivate(import_node_path43.default.dirname(credentialsFile));
126563
+ deps.fs.mkdirPrivate(import_node_path45.default.dirname(credentialsFile));
126015
126564
  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
126565
  `);
126017
126566
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -126094,12 +126643,12 @@ function eventExcerpt(text2) {
126094
126643
  return text2.length <= RC_PENDING_SUMMARY_EXCERPT_CHARS ? text2 : `${text2.slice(0, RC_PENDING_SUMMARY_EXCERPT_CHARS)}...`;
126095
126644
  }
126096
126645
  var PERCENT_SCALE = 100;
126097
- var MS_PER_SECOND9 = 1e3;
126646
+ var MS_PER_SECOND10 = 1e3;
126098
126647
  function percentOf(fraction) {
126099
126648
  return `${String(Math.round(fraction * PERCENT_SCALE))}%`;
126100
126649
  }
126101
126650
  function resetInstantOf(epochSeconds) {
126102
- return new Date(epochSeconds * MS_PER_SECOND9).toISOString();
126651
+ return new Date(epochSeconds * MS_PER_SECOND10).toISOString();
126103
126652
  }
126104
126653
  function formatRcRateLimitInfo(info) {
126105
126654
  const parts = [info.status];
@@ -126398,7 +126947,7 @@ function registerRcCommand(frontdoor, paths) {
126398
126947
  }
126399
126948
 
126400
126949
  // src/frontdoor/rcCredentialStore.ts
126401
- var import_node_path44 = __toESM(require("node:path"), 1);
126950
+ var import_node_path46 = __toESM(require("node:path"), 1);
126402
126951
  function isSafeSessionId(sessionId) {
126403
126952
  return /^[A-Za-z0-9_-]+$/.test(sessionId);
126404
126953
  }
@@ -126424,7 +126973,7 @@ function sequenceNumOfJson(value2) {
126424
126973
  }
126425
126974
  function createRcCredentialStore(fs22, dir) {
126426
126975
  fs22.mkdirPrivate(dir);
126427
- const fileFor = (sessionId) => import_node_path44.default.join(dir, `${sessionId}.json`);
126976
+ const fileFor = (sessionId) => import_node_path46.default.join(dir, `${sessionId}.json`);
126428
126977
  const readParsed = (sessionId) => {
126429
126978
  const raw = fs22.readFileUtf8(fileFor(sessionId));
126430
126979
  if (raw === void 0) {
@@ -127534,7 +128083,7 @@ var RC_COMPAT_SESSIONS_PATH = "/v1/sessions";
127534
128083
  var RC_SESSION_ID_PREFIX2 = "cse_";
127535
128084
  var RC_SELF_HOST_API_BASE_URL = "https://api.anthropic.com";
127536
128085
  var HTTP_CONFLICT = 409;
127537
- var MS_PER_SECOND10 = 1e3;
128086
+ var MS_PER_SECOND11 = 1e3;
127538
128087
  var HTTP_SERVICE_UNAVAILABLE2 = 503;
127539
128088
  var RC_SELF_HOST_WORKER_JWT_TTL_SECONDS = 46800;
127540
128089
  var RC_SELF_HOST_KEEPALIVE_MS = 15e3;
@@ -127634,7 +128183,7 @@ function parseJsonObject5(body) {
127634
128183
  function mintWorkerJwt(randomToken, issuedAt) {
127635
128184
  const encode3 = (value2) => Buffer.from(JSON.stringify(value2), "utf8").toString("base64url");
127636
128185
  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) });
128186
+ 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
128187
  return `${header}.${payload}.${Buffer.from(randomToken(), "utf8").toString("base64url")}`;
127639
128188
  }
127640
128189
  function createRcSelfHostSurface(deps) {
@@ -128705,6 +129254,48 @@ function realFrontDoorSupervisorPorts(paths) {
128705
129254
  const pools = readPools(paths);
128706
129255
  void refreshStalePoolMembers({ poolNames: Object.keys(pools), pools, loadMembers: (identities) => loadPoolMembers(realFarmFs, paths, identities, Date.now()), refresher: anthropicRefresher });
128707
129256
  }, ANTHROPIC_USAGE_FRESHNESS_MS).unref();
129257
+ const windowOpener = createRealWindowOpener({ paths, cwd: process.cwd(), spawnDaemon: spawnDetachedSupervisor });
129258
+ let keeperRunning = false;
129259
+ setInterval(() => {
129260
+ if (keeperRunning) {
129261
+ return;
129262
+ }
129263
+ keeperRunning = true;
129264
+ void runWindowKeeper({
129265
+ fs: realFarmFs,
129266
+ stampsFile: paths.usageAnchorsFile,
129267
+ nowMs: () => Date.now(),
129268
+ timeZone: machineTimeZone(),
129269
+ anchored: () => listAnchoredIdentities(paths),
129270
+ snapshot: (identity) => readUsageSnapshot(realFarmFs, paths.usageSnapshotsDir, identity),
129271
+ open: windowOpener,
129272
+ log
129273
+ }).catch((error63) => {
129274
+ log(`window keeper failed: ${error63 instanceof Error ? error63.message : String(error63)}`);
129275
+ }).finally(() => {
129276
+ keeperRunning = false;
129277
+ });
129278
+ }, ANTHROPIC_USAGE_FRESHNESS_MS).unref();
129279
+ const jobRunner = createRealJobRunner({ paths, spawnDaemon: spawnDetachedSupervisor, fs: realFarmFs, now: () => /* @__PURE__ */ new Date() });
129280
+ const runningJobs = /* @__PURE__ */ new Set();
129281
+ setInterval(() => {
129282
+ try {
129283
+ runJobs({
129284
+ fs: realFarmFs,
129285
+ stampsFile: paths.usageJobsFile,
129286
+ nowMs: () => Date.now(),
129287
+ timeZone: machineTimeZone(),
129288
+ jobs: () => Object.entries(readJobs(paths)).map(([name, job]) => ({ name, job })),
129289
+ resolveIdentity: (target) => resolveJobIdentity({ paths, fs: realFarmFs, pools: readPools(paths), nowMs: Date.now(), identityExists: (name) => identityExists(paths, name) }, target),
129290
+ snapshot: (identity) => readUsageSnapshot(realFarmFs, paths.usageSnapshotsDir, identity),
129291
+ run: jobRunner,
129292
+ running: runningJobs,
129293
+ log
129294
+ });
129295
+ } catch (error63) {
129296
+ log(`job keeper failed: ${error63 instanceof Error ? error63.message : String(error63)}`);
129297
+ }
129298
+ }, ANTHROPIC_USAGE_FRESHNESS_MS).unref();
128708
129299
  const usageMiddleware = createUsageMiddleware({
128709
129300
  record: withQuotaRefresh(usageStore.record, quotaRefresher),
128710
129301
  defer: (task) => {
@@ -128848,7 +129439,7 @@ function realFrontDoorSupervisorPorts(paths) {
128848
129439
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
128849
129440
  const capture = captureFromEnv(process.env, paths.logsDir);
128850
129441
  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")}`);
129442
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path47.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
128852
129443
  }
128853
129444
  if (rcSelfHostSurface !== void 0) {
128854
129445
  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 +131576,8 @@ function getErrorMap2() {
130985
131576
 
130986
131577
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/helpers/parseUtil.js
130987
131578
  var makeIssue = (params) => {
130988
- const { data, path: path51, errorMaps, issueData } = params;
130989
- const fullPath = [...path51, ...issueData.path || []];
131579
+ const { data, path: path54, errorMaps, issueData } = params;
131580
+ const fullPath = [...path54, ...issueData.path || []];
130990
131581
  const fullIssue = {
130991
131582
  ...issueData,
130992
131583
  path: fullPath
@@ -131101,11 +131692,11 @@ var errorUtil;
131101
131692
 
131102
131693
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/types.js
131103
131694
  var ParseInputLazyPath = class {
131104
- constructor(parent, value2, path51, key) {
131695
+ constructor(parent, value2, path54, key) {
131105
131696
  this._cachedPath = [];
131106
131697
  this.parent = parent;
131107
131698
  this.data = value2;
131108
- this._path = path51;
131699
+ this._path = path54;
131109
131700
  this._key = key;
131110
131701
  }
131111
131702
  get path() {
@@ -134668,11 +135259,11 @@ function normalizeObjectSchema(schema) {
134668
135259
  }
134669
135260
  return void 0;
134670
135261
  }
134671
- function getDotPath(path51) {
134672
- if (path51.length === 0) {
135262
+ function getDotPath(path54) {
135263
+ if (path54.length === 0) {
134673
135264
  return "object root";
134674
135265
  }
134675
- return path51.reduce((acc, seg, index) => {
135266
+ return path54.reduce((acc, seg, index) => {
134676
135267
  if (index === 0) {
134677
135268
  return String(seg);
134678
135269
  }
@@ -138715,7 +139306,7 @@ async function serveMcp(mcp, transport, options = {}) {
138715
139306
 
138716
139307
  // src/mcp/permissions.ts
138717
139308
  var import_node_fs17 = __toESM(require("node:fs"), 1);
138718
- var import_node_path46 = __toESM(require("node:path"), 1);
139309
+ var import_node_path48 = __toESM(require("node:path"), 1);
138719
139310
  init_zod();
138720
139311
  init_store();
138721
139312
  var StoredMcpPermissionsSchema = external_exports.strictObject({
@@ -138735,10 +139326,10 @@ function effectiveMcpPermissions(flags, stored) {
138735
139326
  return { writes: flags.writes || stored.writes, remoteControl: flags.remoteControl || stored.remoteControl };
138736
139327
  }
138737
139328
  function watchMcpPermissions(paths, onChange) {
138738
- const directory = import_node_path46.default.dirname(paths.mcpPermissionsFile);
139329
+ const directory = import_node_path48.default.dirname(paths.mcpPermissionsFile);
138739
139330
  import_node_fs17.default.mkdirSync(directory, { recursive: true });
138740
139331
  const watcher = import_node_fs17.default.watch(directory, (_event, filename) => {
138741
- if (filename === null || filename === import_node_path46.default.basename(paths.mcpPermissionsFile)) {
139332
+ if (filename === null || filename === import_node_path48.default.basename(paths.mcpPermissionsFile)) {
138742
139333
  onChange();
138743
139334
  }
138744
139335
  });
@@ -139047,16 +139638,16 @@ init_credentialCache();
139047
139638
 
139048
139639
  // src/identityToken.ts
139049
139640
  var import_node_fs18 = __toESM(require("node:fs"), 1);
139050
- var import_node_path47 = __toESM(require("node:path"), 1);
139641
+ var import_node_path49 = __toESM(require("node:path"), 1);
139051
139642
  init_cliError();
139052
139643
  var TOKEN_FILE_MODE = 384;
139053
139644
  var TOKEN_DIR_MODE = 448;
139054
139645
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
139055
139646
  function identityTokenDir(paths) {
139056
- return import_node_path47.default.join(paths.root, "credentials");
139647
+ return import_node_path49.default.join(paths.root, "credentials");
139057
139648
  }
139058
139649
  function identityTokenPath(paths, identityName) {
139059
- return import_node_path47.default.join(identityTokenDir(paths), `${identityName}.token`);
139650
+ return import_node_path49.default.join(identityTokenDir(paths), `${identityName}.token`);
139060
139651
  }
139061
139652
  function storeIdentityToken(paths, identityName, raw) {
139062
139653
  const token = raw.trim();
@@ -139067,7 +139658,7 @@ function storeIdentityToken(paths, identityName, raw) {
139067
139658
  import_node_fs18.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
139068
139659
  import_node_fs18.default.chmodSync(dir, TOKEN_DIR_MODE);
139069
139660
  const target = identityTokenPath(paths, identityName);
139070
- const temp = import_node_path47.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
139661
+ const temp = import_node_path49.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
139071
139662
  import_node_fs18.default.writeFileSync(temp, `${token}
139072
139663
  `, { mode: TOKEN_FILE_MODE });
139073
139664
  import_node_fs18.default.renameSync(temp, target);
@@ -139235,7 +139826,7 @@ function registerDoctorCommand(program2, deps) {
139235
139826
  // src/headroom/commands.ts
139236
139827
  var import_node_fs19 = __toESM(require("node:fs"), 1);
139237
139828
  var import_node_http4 = __toESM(require("node:http"), 1);
139238
- var import_node_path48 = __toESM(require("node:path"), 1);
139829
+ var import_node_path50 = __toESM(require("node:path"), 1);
139239
139830
  var import_node_child_process6 = require("node:child_process");
139240
139831
  init_commandDeps();
139241
139832
  init_realFrontDoorPort();
@@ -139365,12 +139956,12 @@ function readInstalledHeadroomCommit() {
139365
139956
  if (toolDir.status !== 0) {
139366
139957
  return void 0;
139367
139958
  }
139368
- const libDir = import_node_path48.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
139959
+ const libDir = import_node_path50.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
139369
139960
  for (const python of realFarmFs.readdir(libDir)) {
139370
- const sitePackages = import_node_path48.default.join(libDir, python, "site-packages");
139961
+ const sitePackages = import_node_path50.default.join(libDir, python, "site-packages");
139371
139962
  for (const entry of realFarmFs.readdir(sitePackages)) {
139372
139963
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
139373
- const directUrl = realFarmFs.readFileUtf8(import_node_path48.default.join(sitePackages, entry, "direct_url.json"));
139964
+ const directUrl = realFarmFs.readFileUtf8(import_node_path50.default.join(sitePackages, entry, "direct_url.json"));
139374
139965
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
139375
139966
  }
139376
139967
  }
@@ -139505,6 +140096,134 @@ function registerHeadroomCommand(program2, deps) {
139505
140096
  });
139506
140097
  }
139507
140098
 
140099
+ // src/jobs.ts
140100
+ var import_node_path51 = __toESM(require("node:path"), 1);
140101
+ init_commandDeps();
140102
+ init_cliError();
140103
+ init_schema();
140104
+ init_realPorts();
140105
+ function jobOf(options) {
140106
+ if (options.identity === void 0 === (options.pool === void 0)) {
140107
+ throw new UsageError("A job runs as one identity or one pool's pick: pass exactly one of --identity or --pool.");
140108
+ }
140109
+ if (options.at === void 0 === (options.beforeReset === void 0)) {
140110
+ throw new UsageError("A job needs exactly one trigger: pass --at (repeatable) or --before-reset with --lead.");
140111
+ }
140112
+ if (options.beforeReset !== void 0 && options.lead === void 0) {
140113
+ throw new UsageError("--before-reset needs --lead, how long before the window resets the job runs.");
140114
+ }
140115
+ if (options.at !== void 0 && options.lead !== void 0) {
140116
+ throw new UsageError("--lead only goes with --before-reset.");
140117
+ }
140118
+ if (options.prompt === void 0 || options.timeout === void 0) {
140119
+ throw new UsageError("A job needs --prompt, what to run, and --timeout, how long one run may take.");
140120
+ }
140121
+ return {
140122
+ target: options.identity === void 0 ? { pool: options.pool ?? "" } : { identity: options.identity },
140123
+ trigger: options.at === void 0 ? { beforeReset: options.beforeReset ?? "fiveHour", lead: options.lead ?? "" } : { at: options.at },
140124
+ prompt: options.prompt,
140125
+ cwd: import_node_path51.default.resolve(options.cwd ?? process.cwd()),
140126
+ timeout: options.timeout,
140127
+ ...options.model === void 0 ? {} : { model: options.model },
140128
+ ...options.allowedTool === void 0 ? {} : { allowedTools: options.allowedTool }
140129
+ };
140130
+ }
140131
+ function describeTrigger(job) {
140132
+ return "at" in job.trigger ? `at ${job.trigger.at.map(formatAnchor).join(" ")}` : `${job.trigger.lead} before the ${job.trigger.beforeReset} window resets`;
140133
+ }
140134
+ function describeTarget(job) {
140135
+ return "identity" in job.target ? `identity ${job.target.identity}` : `the pick of pool ${job.target.pool}`;
140136
+ }
140137
+ function registerJobCommand(program2, deps) {
140138
+ const { paths } = deps;
140139
+ const job = withExamples(
140140
+ program2.command("job").description("Manage jobs: prompts the front door runs unattended as an identity, on a schedule or shortly before a quota window resets to use quota that would expire."),
140141
+ ["agent-shim job add digest --identity work --before-reset sevenDay --lead 6h --prompt 'summarise open PRs' --timeout 30m", "agent-shim job list"]
140142
+ );
140143
+ withExamples(
140144
+ job.command("add <name>").description("Define a job. Fails if one with this name already exists.").option("--identity <name>", "Run as this identity.").option("--pool <name>", "Run as whichever member of this pool the ranking picks when the job fires.").option("--at <spec>", `Run at these times (repeatable): ${ANCHOR_SYNTAX}.`, collectAnchor).addOption(new Option("--before-reset <window>", "Run once per instance of this quota window, when it has --lead or less left.").choices(JOB_WINDOWS)).option("--lead <duration>", "With --before-reset: how long before the window resets the job runs, a count followed by m, h, d or w, such as 6h.", parseDurationLiteral).option("--prompt <text>", "What to run.").option("--cwd <dir>", "The directory the run works in. Defaults to the current directory.").option("--timeout <duration>", "How long one run may take, such as 30m. A run that goes on longer is stopped.", parseDurationLiteral).option("--model <model>", "The model to run with. Defaults to the settings' own.").option("--allowed-tool <tool>", "A tool the run may use without asking, beyond what its settings allow (repeatable). An unattended run cannot answer a permission prompt, so any other tool is refused.", collectRepeated).option("--json", "Print the result as JSON.").action((name, options) => {
140145
+ const defined = jobOf(options);
140146
+ if ("identity" in defined.target) {
140147
+ requireIdentityNames(paths, [defined.target.identity]);
140148
+ } else {
140149
+ requirePool(paths, defined.target.pool);
140150
+ }
140151
+ const created = addJob(paths, name, defined);
140152
+ reportMutation(options.json, { action: "created", kind: "job", name, value: created }, () => {
140153
+ console.log(`Created job "${name}": runs as ${describeTarget(created)}, ${describeTrigger(created)}.`);
140154
+ });
140155
+ }),
140156
+ ["agent-shim job add digest --identity work --at mon-fri@06:00 --prompt 'summarise open PRs' --timeout 30m --cwd ~/work/app", "agent-shim job add burn --pool subs --before-reset fiveHour --lead 20m --prompt 'continue the migration plan' --timeout 20m --allowed-tool Read --allowed-tool Edit"]
140157
+ );
140158
+ withExamples(
140159
+ job.command("list").description("List every job.").option("--json", "Print the jobs as JSON.").action((options) => {
140160
+ const jobs = readJobs(paths);
140161
+ if (options.json === true) {
140162
+ printJson(Object.entries(jobs).map(([name, entry]) => ({ name, ...entry })));
140163
+ return;
140164
+ }
140165
+ const names = Object.keys(jobs).sort();
140166
+ if (names.length === 0) {
140167
+ console.log("No jobs yet. Run `agent-shim job add <name> ...` to create one.");
140168
+ return;
140169
+ }
140170
+ for (const name of names) {
140171
+ const entry = jobs[name];
140172
+ if (entry !== void 0) {
140173
+ console.log(`${name}: ${describeTarget(entry)}, ${describeTrigger(entry)}`);
140174
+ }
140175
+ }
140176
+ }),
140177
+ ["agent-shim job list", "agent-shim job list --json"]
140178
+ );
140179
+ withExamples(
140180
+ job.command("show <name>").description("Show one job.").option("--json", "Print the job as JSON.").action((name, options) => {
140181
+ const entry = requireJob(paths, name);
140182
+ if (options.json === true) {
140183
+ printJson({ name, ...entry });
140184
+ return;
140185
+ }
140186
+ console.log(`Job: ${name}`);
140187
+ console.log(`Runs as: ${describeTarget(entry)}`);
140188
+ console.log(`Trigger: ${describeTrigger(entry)}`);
140189
+ console.log(`Directory: ${entry.cwd}`);
140190
+ console.log(`Timeout: ${entry.timeout}`);
140191
+ if (entry.model !== void 0) {
140192
+ console.log(`Model: ${entry.model}`);
140193
+ }
140194
+ if (entry.allowedTools !== void 0) {
140195
+ console.log(`Allowed tools: ${entry.allowedTools.join(", ")}`);
140196
+ }
140197
+ console.log(`Prompt: ${entry.prompt}`);
140198
+ console.log(`Results: ${import_node_path51.default.join(paths.jobLogsDir, `${name}.log`)}`);
140199
+ }),
140200
+ ["agent-shim job show digest"]
140201
+ );
140202
+ withExamples(
140203
+ job.command("remove <name>").description("Delete a job.").option("--yes", "Skip the confirmation prompt.").option("--json", "Print the result as JSON.").action(async (name, options) => {
140204
+ requireJob(paths, name);
140205
+ await confirmRemoval(deps, options.yes, `job "${name}"`);
140206
+ removeJob(paths, name);
140207
+ reportMutation(options.json, { action: "removed", kind: "job", name }, () => {
140208
+ console.log(`Removed job "${name}".`);
140209
+ });
140210
+ }),
140211
+ ["agent-shim job remove digest --yes"]
140212
+ );
140213
+ withExamples(
140214
+ job.command("run <name>").description("Run a job now, in this terminal, as its trigger would: for a pool the member is picked at this moment. The result is appended to the job's log, and a failure exits non-zero.").action(async (name) => {
140215
+ const entry = requireJob(paths, name);
140216
+ const identity = resolveJobIdentity({ paths, fs: realFarmFs, pools: readPools(paths), nowMs: Date.now(), identityExists: (candidate) => identityExists(paths, candidate) }, entry.target);
140217
+ if (identity === void 0) {
140218
+ throw new UsageError(`No member of the job's pool can be picked right now.`);
140219
+ }
140220
+ await createRealJobRunner({ paths, spawnDaemon: spawnDetachedSupervisor, fs: realFarmFs, now: () => /* @__PURE__ */ new Date() })(name, identity, entry);
140221
+ console.log(`Ran job "${name}" as ${identity}; the result is in ${import_node_path51.default.join(paths.jobLogsDir, `${name}.log`)}.`);
140222
+ }),
140223
+ ["agent-shim job run digest"]
140224
+ );
140225
+ }
140226
+
139508
140227
  // src/pools.ts
139509
140228
  init_commandDeps();
139510
140229
  init_cliError();
@@ -139910,7 +140629,7 @@ function registerRunCommand(program2, handler) {
139910
140629
  }
139911
140630
 
139912
140631
  // src/usage/commands.ts
139913
- var import_node_path49 = __toESM(require("node:path"), 1);
140632
+ var import_node_path52 = __toESM(require("node:path"), 1);
139914
140633
  init_commandDeps();
139915
140634
  init_realPorts();
139916
140635
  init_account();
@@ -140048,7 +140767,7 @@ function collectAccounts(fs22, paths, identity, probe) {
140048
140767
  return names.map((name) => ({
140049
140768
  identity: name,
140050
140769
  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 }),
140770
+ signIn: identitySignIn(fs22, probe, { farmRoot: import_node_path52.default.join(paths.identitiesDir, name), hasCredentialBlock: readIdentity(paths, name)?.credential !== void 0 }),
140052
140771
  usage: readUsageSnapshot(fs22, paths.usageSnapshotsDir, name)
140053
140772
  }));
140054
140773
  }
@@ -140219,6 +140938,7 @@ function buildProgram(deps) {
140219
140938
  registerIdentityCommand(program2, deps);
140220
140939
  registerProfileCommand(program2, deps);
140221
140940
  registerPoolCommand(program2, deps);
140941
+ registerJobCommand(program2, deps);
140222
140942
  registerProviderCommand(program2, deps);
140223
140943
  registerRuleCommand(program2, deps);
140224
140944
  registerCredentialCommand(program2, deps, deps.credentialPorts);
@@ -140393,7 +141113,7 @@ async function runClaude(argvOverride) {
140393
141113
  // src/cli.ts
140394
141114
  async function main() {
140395
141115
  aliasLegacyEnv(process.env);
140396
- const invokedName = import_node_path50.default.basename(process.argv[1] ?? "agent-shim");
141116
+ const invokedName = import_node_path53.default.basename(process.argv[1] ?? "agent-shim");
140397
141117
  if (isInvokedAsClaude(invokedName)) {
140398
141118
  await runClaude();
140399
141119
  return;