claude-use 11.19.0 → 11.20.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, path61) {
322
- if (!path61)
321
+ function getElementAtPath(obj, path63) {
322
+ if (!path63)
323
323
  return obj;
324
- return path61.reduce((acc, key) => acc?.[key], obj);
324
+ return path63.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(path61, issues) {
583
+ function prefixIssues(path63, issues) {
584
584
  return issues.map((iss) => {
585
585
  var _a4;
586
586
  (_a4 = iss).path ?? (_a4.path = []);
587
- iss.path.unshift(path61);
587
+ iss.path.unshift(path63);
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, path61 = []) => {
1108
+ const processError = (error64, path63 = []) => {
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 }, [...path61, ...issue2.path]));
1111
+ issue2.errors.map((issues) => processError({ issues }, [...path63, ...issue2.path]));
1112
1112
  } else if (issue2.code === "invalid_key") {
1113
- processError({ issues: issue2.issues }, [...path61, ...issue2.path]);
1113
+ processError({ issues: issue2.issues }, [...path63, ...issue2.path]);
1114
1114
  } else if (issue2.code === "invalid_element") {
1115
- processError({ issues: issue2.issues }, [...path61, ...issue2.path]);
1115
+ processError({ issues: issue2.issues }, [...path63, ...issue2.path]);
1116
1116
  } else {
1117
- const fullpath = [...path61, ...issue2.path];
1117
+ const fullpath = [...path63, ...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, path61 = []) => {
1156
+ const processError = (error64, path63 = []) => {
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 }, [...path61, ...issue2.path]));
1160
+ issue2.errors.map((issues) => processError({ issues }, [...path63, ...issue2.path]));
1161
1161
  } else if (issue2.code === "invalid_key") {
1162
- processError({ issues: issue2.issues }, [...path61, ...issue2.path]);
1162
+ processError({ issues: issue2.issues }, [...path63, ...issue2.path]);
1163
1163
  } else if (issue2.code === "invalid_element") {
1164
- processError({ issues: issue2.issues }, [...path61, ...issue2.path]);
1164
+ processError({ issues: issue2.issues }, [...path63, ...issue2.path]);
1165
1165
  } else {
1166
- const fullpath = [...path61, ...issue2.path];
1166
+ const fullpath = [...path63, ...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 path61 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
- for (const seg of path61) {
1205
+ const path63 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1206
+ for (const seg of path63) {
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 path61 = ref.slice(1).split("/").filter(Boolean);
19203
- if (path61.length === 0) {
19202
+ const path63 = ref.slice(1).split("/").filter(Boolean);
19203
+ if (path63.length === 0) {
19204
19204
  return ctx.rootSchema;
19205
19205
  }
19206
19206
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19207
- if (path61[0] === defsKey) {
19208
- const key = path61[1] === void 0 ? void 0 : decodeJSONPointerSegment(path61[1]);
19207
+ if (path63[0] === defsKey) {
19208
+ const key = path63[1] === void 0 ? void 0 : decodeJSONPointerSegment(path63[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 path61 = require("path");
23715
+ var path63 = require("path");
23716
23716
  var os13 = require("os");
23717
23717
  var homedir = os13.homedir();
23718
23718
  var tmpdir = os13.tmpdir();
23719
23719
  var { env } = process;
23720
23720
  var macos = (name) => {
23721
- const library = path61.join(homedir, "Library");
23721
+ const library = path63.join(homedir, "Library");
23722
23722
  return {
23723
- data: path61.join(library, "Application Support", name),
23724
- config: path61.join(library, "Preferences", name),
23725
- cache: path61.join(library, "Caches", name),
23726
- log: path61.join(library, "Logs", name),
23727
- temp: path61.join(tmpdir, name)
23723
+ data: path63.join(library, "Application Support", name),
23724
+ config: path63.join(library, "Preferences", name),
23725
+ cache: path63.join(library, "Caches", name),
23726
+ log: path63.join(library, "Logs", name),
23727
+ temp: path63.join(tmpdir, name)
23728
23728
  };
23729
23729
  };
23730
23730
  var windows = (name) => {
23731
- const appData = env.APPDATA || path61.join(homedir, "AppData", "Roaming");
23732
- const localAppData = env.LOCALAPPDATA || path61.join(homedir, "AppData", "Local");
23731
+ const appData = env.APPDATA || path63.join(homedir, "AppData", "Roaming");
23732
+ const localAppData = env.LOCALAPPDATA || path63.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: path61.join(localAppData, name, "Data"),
23736
- config: path61.join(appData, name, "Config"),
23737
- cache: path61.join(localAppData, name, "Cache"),
23738
- log: path61.join(localAppData, name, "Log"),
23739
- temp: path61.join(tmpdir, name)
23735
+ data: path63.join(localAppData, name, "Data"),
23736
+ config: path63.join(appData, name, "Config"),
23737
+ cache: path63.join(localAppData, name, "Cache"),
23738
+ log: path63.join(localAppData, name, "Log"),
23739
+ temp: path63.join(tmpdir, name)
23740
23740
  };
23741
23741
  };
23742
23742
  var linux = (name) => {
23743
- const username = path61.basename(homedir);
23743
+ const username = path63.basename(homedir);
23744
23744
  return {
23745
- data: path61.join(env.XDG_DATA_HOME || path61.join(homedir, ".local", "share"), name),
23746
- config: path61.join(env.XDG_CONFIG_HOME || path61.join(homedir, ".config"), name),
23747
- cache: path61.join(env.XDG_CACHE_HOME || path61.join(homedir, ".cache"), name),
23745
+ data: path63.join(env.XDG_DATA_HOME || path63.join(homedir, ".local", "share"), name),
23746
+ config: path63.join(env.XDG_CONFIG_HOME || path63.join(homedir, ".config"), name),
23747
+ cache: path63.join(env.XDG_CACHE_HOME || path63.join(homedir, ".cache"), name),
23748
23748
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
23749
- log: path61.join(env.XDG_STATE_HOME || path61.join(homedir, ".local", "state"), name),
23750
- temp: path61.join(tmpdir, username, name)
23749
+ log: path63.join(env.XDG_STATE_HOME || path63.join(homedir, ".local", "state"), name),
23750
+ temp: path63.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, path61) {
23819
- if (typeof path61 === "string" && Object.prototype.hasOwnProperty.call(source, path61)) {
23820
- return source[path61];
23818
+ function getPropertyByPath(source, path63) {
23819
+ if (typeof path63 === "string" && Object.prototype.hasOwnProperty.call(source, path63)) {
23820
+ return source[path63];
23821
23821
  }
23822
- const parsedPath = typeof path61 === "string" ? path61.split(".") : path61;
23822
+ const parsedPath = typeof path63 === "string" ? path63.split(".") : path63;
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(path61) {
23845
+ async function isDirectory(path63) {
23846
23846
  try {
23847
- const stat = await fs_1.promises.stat(path61);
23847
+ const stat = await fs_1.promises.stat(path63);
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(path61) {
23857
+ function isDirectorySync(path63) {
23858
23858
  try {
23859
- const stat = fs_1.default.statSync(path61);
23859
+ const stat = fs_1.default.statSync(path63);
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((path61, i10) => `${i10 + 1}. ${path61}`).join("\n")} (same as ${idx + 1}.)`);
23957
+ ${[...importStack, fullPath].map((path63, i10) => `${i10 + 1}. ${path63}`).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(path61) {
24145
+ async #fileExists(path63) {
24146
24146
  try {
24147
- await promises_1.default.stat(path61);
24147
+ await promises_1.default.stat(path63);
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(path61) {
24307
+ #fileExists(path63) {
24308
24308
  try {
24309
- fs_1.default.statSync(path61);
24309
+ fs_1.default.statSync(path63);
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((path61) => path61.replace("{name}", moduleName));
24433
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path63) => path63.replace("{name}", moduleName));
24434
24434
  if (userConfiguredOptions.mergeSearchPlaces) {
24435
24435
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
24436
24436
  }
@@ -24560,7 +24560,7 @@ function parseIgnoringUnrecognisedKeys(schema, raw) {
24560
24560
  return second.success ? { success: true, data: second.data, ignored } : { success: false, issues: second.error.issues };
24561
24561
  }
24562
24562
  function describeIgnoredKeys(filePath, ignored) {
24563
- const places = ignored.map(({ path: path61, keys }) => `${path61.length === 0 ? "" : `${path61.map(String).join(".")}.`}${keys.join(", ")}`);
24563
+ const places = ignored.map(({ path: path63, keys }) => `${path63.length === 0 ? "" : `${path63.map(String).join(".")}.`}${keys.join(", ")}`);
24564
24564
  return `${filePath} has settings this version of agent-shim does not know and ignores: ${places.join("; ")}. A newer release may read them.`;
24565
24565
  }
24566
24566
  function noteIgnoredKeys(filePath, ignored) {
@@ -24582,9 +24582,9 @@ function restoreIgnoredKeys(filePath, value2) {
24582
24582
  return value2;
24583
24583
  }
24584
24584
  const restored = structuredClone(value2);
24585
- for (const { path: path61, values } of ignored) {
24585
+ for (const { path: path63, values } of ignored) {
24586
24586
  let holder = restored;
24587
- for (const step2 of path61) {
24587
+ for (const step2 of path63) {
24588
24588
  holder = isRecord(holder) ? holder[step2] : void 0;
24589
24589
  }
24590
24590
  if (isRecord(holder)) {
@@ -26987,7 +26987,7 @@ function isTimeZone(name) {
26987
26987
  return false;
26988
26988
  }
26989
26989
  }
26990
- 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, ANTIGRAVITY_MODES, ANTIGRAVITY_TIERS, ANTIGRAVITY_EFFORTS, ANTIGRAVITY_DEFAULT_MODE, ANTIGRAVITY_DEFAULT_MODEL, ANTIGRAVITY_DEFAULT_TIER_MODELS, ANTIGRAVITY_DEFAULT_EFFORT, AntigravityModelTargetSchema, AntigravityProviderConfigSchema, CODEX_TIERS, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, HttpProviderSchema, CodexProviderSchema, AntigravityProviderSchema, 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;
26990
+ 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, ANTIGRAVITY_MODES, ANTIGRAVITY_TIERS, ANTIGRAVITY_EFFORTS, ANTIGRAVITY_DEFAULT_MODE, ANTIGRAVITY_DEFAULT_MODEL, ANTIGRAVITY_DEFAULT_TIER_MODELS, ANTIGRAVITY_DEFAULT_EFFORT, AntigravityModelTargetSchema, AntigravityProviderConfigSchema, CODEX_TIERS, CODEX_EFFORTS, CODEX_LOGINS, CODEX_DEFAULT_LOGIN, CODEX_DEFAULT_MODEL, CODEX_DEFAULT_TIER_MODELS, CODEX_DEFAULT_EFFORT, CodexProviderConfigSchema, ProviderRouteSchema, HttpProviderSchema, CodexProviderSchema, AntigravityProviderSchema, ProviderSchema, ConfigProfileSchema, POOL_SELECTOR_PREFIX, POOL_NAME_PATTERN, IDENTITY_NAME_PATTERN, PoolNameSchema, SELECTOR_RE, IdentitySelectorSchema, PoolMemberSchema, POOL_PREFERENCES, PoolPreferenceSchema, WHOLE_PERCENT_MAX, CompactAtUtilisationSchema, 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;
26991
26991
  var init_schema = __esm({
26992
26992
  "src/config/schema.ts"() {
26993
26993
  "use strict";
@@ -27207,10 +27207,18 @@ var init_schema = __esm({
27207
27207
  PoolMemberSchema = external_exports.union([external_exports.string().min(1).regex(SELECTOR_RE), external_exports.strictObject({ identity: external_exports.string().min(1).regex(SELECTOR_RE), when: WhenSchema })]);
27208
27208
  POOL_PREFERENCES = ["score", "listed"];
27209
27209
  PoolPreferenceSchema = external_exports.enum(POOL_PREFERENCES);
27210
+ WHOLE_PERCENT_MAX = 100;
27211
+ CompactAtUtilisationSchema = external_exports.number().int().min(1).max(WHOLE_PERCENT_MAX);
27210
27212
  PoolSchema = external_exports.strictObject({
27211
27213
  identities: external_exports.array(PoolMemberSchema).min(1).refine((members2) => new Set(members2.map(poolMemberIdentity)).size === members2.length, { message: "pool members must be unique" }),
27212
- preference: PoolPreferenceSchema.optional()
27213
- });
27214
+ preference: PoolPreferenceSchema.optional(),
27215
+ /** Whether an interactive launch from this pool keeps going when its identity runs out of quota: the launcher moves the session to the next member and resumes the conversation there. Absent means false. */
27216
+ resumeOnLimit: external_exports.boolean().optional(),
27217
+ /** Whether a supervised session's context is compacted before its identity's quota is spent, so the resume on the next member writes a small context instead of a large one. Needs `resumeOnLimit`. Absent means false. */
27218
+ compactBeforeLimit: external_exports.boolean().optional(),
27219
+ /** The share of a quota window, in whole percent, at which sessions are compacted. Absent means the launcher decides from what compacting every session on the member would cost against what its five-hour window has left. Needs `compactBeforeLimit`. */
27220
+ compactAtUtilisation: CompactAtUtilisationSchema.optional()
27221
+ }).refine((pool) => pool.compactBeforeLimit !== true || pool.resumeOnLimit === true, { message: "compactBeforeLimit needs resumeOnLimit, since a session that is not moved has no cold cache to avoid", path: ["compactBeforeLimit"] }).refine((pool) => pool.compactAtUtilisation === void 0 || pool.compactBeforeLimit === true, { message: "compactAtUtilisation needs compactBeforeLimit", path: ["compactAtUtilisation"] });
27214
27222
  WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
27215
27223
  AnchorSchema = external_exports.strictObject({
27216
27224
  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"),
@@ -27337,10 +27345,10 @@ var init_schema = __esm({
27337
27345
  });
27338
27346
 
27339
27347
  // src/frontdoor/state.ts
27340
- function readFrontDoorState(fs24, stateFile) {
27348
+ function readFrontDoorState(fs25, stateFile) {
27341
27349
  let raw;
27342
27350
  try {
27343
- raw = fs24.readFileUtf8(stateFile);
27351
+ raw = fs25.readFileUtf8(stateFile);
27344
27352
  } catch {
27345
27353
  return void 0;
27346
27354
  }
@@ -27354,9 +27362,9 @@ function readFrontDoorState(fs24, stateFile) {
27354
27362
  return void 0;
27355
27363
  }
27356
27364
  }
27357
- function writeFrontDoorState(fs24, stateFile, state) {
27358
- fs24.mkdirp(import_node_path5.default.dirname(stateFile));
27359
- fs24.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
27365
+ function writeFrontDoorState(fs25, stateFile, state) {
27366
+ fs25.mkdirp(import_node_path5.default.dirname(stateFile));
27367
+ fs25.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
27360
27368
  `);
27361
27369
  }
27362
27370
  function directOrigin(port) {
@@ -27366,27 +27374,27 @@ function frontDoorOrigin(state) {
27366
27374
  const port = state?.directPort ?? state?.lastDirectPort;
27367
27375
  return port === void 0 ? void 0 : directOrigin(port);
27368
27376
  }
27369
- function writeFrontDoorDirectRecord(fs24, recordsDir, record2) {
27370
- fs24.mkdirp(recordsDir);
27371
- fs24.writeFilePrivate(import_node_path5.default.join(recordsDir, `${String(record2.pid)}.json`), `${JSON.stringify({ directPort: record2.directPort })}
27377
+ function writeFrontDoorDirectRecord(fs25, recordsDir, record2) {
27378
+ fs25.mkdirp(recordsDir);
27379
+ fs25.writeFilePrivate(import_node_path5.default.join(recordsDir, `${String(record2.pid)}.json`), `${JSON.stringify({ directPort: record2.directPort })}
27372
27380
  `);
27373
27381
  }
27374
- function removeFrontDoorDirectRecord(fs24, recordsDir, pid) {
27375
- fs24.removeRecursive(import_node_path5.default.join(recordsDir, `${String(pid)}.json`));
27382
+ function removeFrontDoorDirectRecord(fs25, recordsDir, pid) {
27383
+ fs25.removeRecursive(import_node_path5.default.join(recordsDir, `${String(pid)}.json`));
27376
27384
  }
27377
27385
  function recordPid(file2) {
27378
27386
  const pidText = /^([1-9]\d*)\.json$/.exec(file2)?.[1];
27379
27387
  const pid = pidText === void 0 ? void 0 : Number(pidText);
27380
27388
  return pid !== void 0 && Number.isSafeInteger(pid) ? pid : void 0;
27381
27389
  }
27382
- function readDirectRecordEntry(fs24, recordsDir, file2) {
27390
+ function readDirectRecordEntry(fs25, recordsDir, file2) {
27383
27391
  const pid = recordPid(file2);
27384
27392
  if (pid === void 0) {
27385
27393
  return void 0;
27386
27394
  }
27387
27395
  let raw;
27388
27396
  try {
27389
- raw = fs24.readFileUtf8(import_node_path5.default.join(recordsDir, file2));
27397
+ raw = fs25.readFileUtf8(import_node_path5.default.join(recordsDir, file2));
27390
27398
  } catch {
27391
27399
  return void 0;
27392
27400
  }
@@ -27400,44 +27408,44 @@ function readDirectRecordEntry(fs24, recordsDir, file2) {
27400
27408
  return { malformed: true };
27401
27409
  }
27402
27410
  }
27403
- function listFrontDoorDirectRecords(fs24, recordsDir) {
27404
- return fs24.readdir(recordsDir).flatMap((file2) => {
27405
- const entry = readDirectRecordEntry(fs24, recordsDir, file2);
27411
+ function listFrontDoorDirectRecords(fs25, recordsDir) {
27412
+ return fs25.readdir(recordsDir).flatMap((file2) => {
27413
+ const entry = readDirectRecordEntry(fs25, recordsDir, file2);
27406
27414
  return entry?.record === void 0 ? [] : [entry.record];
27407
27415
  }).sort((a10, b) => a10.pid - b.pid);
27408
27416
  }
27409
- function pruneMalformedFrontDoorDirectFiles(fs24, recordsDir, isRunning) {
27410
- for (const file2 of fs24.readdir(recordsDir)) {
27417
+ function pruneMalformedFrontDoorDirectFiles(fs25, recordsDir, isRunning) {
27418
+ for (const file2 of fs25.readdir(recordsDir)) {
27411
27419
  const writer = RECORD_TEMPORARY_FILE.exec(file2)?.[1];
27412
27420
  const stale = writer !== void 0 && !isRunning(Number(writer));
27413
- if (stale || readDirectRecordEntry(fs24, recordsDir, file2)?.malformed === true) {
27414
- fs24.removeRecursive(import_node_path5.default.join(recordsDir, file2));
27421
+ if (stale || readDirectRecordEntry(fs25, recordsDir, file2)?.malformed === true) {
27422
+ fs25.removeRecursive(import_node_path5.default.join(recordsDir, file2));
27415
27423
  }
27416
27424
  }
27417
27425
  }
27418
27426
  function liveFrontDoorDirectRecords(records, liveness) {
27419
27427
  return records.filter((record2) => liveness.doors.has(record2.pid) || liveness.unknown.has(record2.pid));
27420
27428
  }
27421
- function pruneDeadFrontDoorDirectRecords(fs24, recordsDir, records, liveness) {
27429
+ function pruneDeadFrontDoorDirectRecords(fs25, recordsDir, records, liveness) {
27422
27430
  for (const record2 of records) {
27423
27431
  if (!liveness.doors.has(record2.pid) && !liveness.unknown.has(record2.pid)) {
27424
- removeFrontDoorDirectRecord(fs24, recordsDir, record2.pid);
27432
+ removeFrontDoorDirectRecord(fs25, recordsDir, record2.pid);
27425
27433
  }
27426
27434
  }
27427
27435
  }
27428
- function writeFrontDoorSession(fs24, sessionsDir, session) {
27429
- fs24.mkdirPrivate(sessionsDir);
27430
- fs24.writeFilePrivate(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
27436
+ function writeFrontDoorSession(fs25, sessionsDir, session) {
27437
+ fs25.mkdirPrivate(sessionsDir);
27438
+ fs25.writeFilePrivate(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
27431
27439
  `);
27432
27440
  }
27433
- function listFrontDoorSessions(fs24, sessionsDir) {
27441
+ function listFrontDoorSessions(fs25, sessionsDir) {
27434
27442
  const sessions = [];
27435
- for (const name of fs24.readdir(sessionsDir)) {
27443
+ for (const name of fs25.readdir(sessionsDir)) {
27436
27444
  if (!name.endsWith(".json")) {
27437
27445
  continue;
27438
27446
  }
27439
27447
  try {
27440
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs24.readFileUtf8(import_node_path5.default.join(sessionsDir, name)) ?? ""));
27448
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs25.readFileUtf8(import_node_path5.default.join(sessionsDir, name)) ?? ""));
27441
27449
  if (parsed.success) {
27442
27450
  sessions.push({ pid: parsed.data.pid, startedAt: parsed.data.startedAt, ...parsed.data.supervisorPid === void 0 ? {} : { supervisorPid: parsed.data.supervisorPid } });
27443
27451
  }
@@ -27447,27 +27455,27 @@ function listFrontDoorSessions(fs24, sessionsDir) {
27447
27455
  }
27448
27456
  return sessions.sort((a10, b) => a10.pid - b.pid);
27449
27457
  }
27450
- function removeFrontDoorSession(fs24, sessionsDir, pid) {
27451
- fs24.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
27458
+ function removeFrontDoorSession(fs25, sessionsDir, pid) {
27459
+ fs25.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
27452
27460
  }
27453
- function pruneDeadFrontDoorSessions(fs24, sessionsDir, isRunning) {
27461
+ function pruneDeadFrontDoorSessions(fs25, sessionsDir, isRunning) {
27454
27462
  const removed = [];
27455
- for (const session of listFrontDoorSessions(fs24, sessionsDir)) {
27463
+ for (const session of listFrontDoorSessions(fs25, sessionsDir)) {
27456
27464
  if (!isRunning(session.pid)) {
27457
- removeFrontDoorSession(fs24, sessionsDir, session.pid);
27465
+ removeFrontDoorSession(fs25, sessionsDir, session.pid);
27458
27466
  removed.push(session.pid);
27459
27467
  }
27460
27468
  }
27461
27469
  return removed;
27462
27470
  }
27463
- function liveSessionTokens(fs24, sessionsDir) {
27471
+ function liveSessionTokens(fs25, sessionsDir) {
27464
27472
  const tokens = /* @__PURE__ */ new Set();
27465
- for (const name of fs24.readdir(sessionsDir)) {
27473
+ for (const name of fs25.readdir(sessionsDir)) {
27466
27474
  if (!name.endsWith(".json")) {
27467
27475
  continue;
27468
27476
  }
27469
27477
  try {
27470
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs24.readFileUtf8(import_node_path5.default.join(sessionsDir, name)) ?? ""));
27478
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs25.readFileUtf8(import_node_path5.default.join(sessionsDir, name)) ?? ""));
27471
27479
  if (parsed.success) {
27472
27480
  tokens.add(parsed.data.token);
27473
27481
  }
@@ -27529,43 +27537,43 @@ function parseJson(raw, schema) {
27529
27537
  const parsed = schema.safeParse(JSON.parse(raw));
27530
27538
  return parsed.success ? parsed.data : void 0;
27531
27539
  }
27532
- function readHeadroomState(fs24, stateFile) {
27540
+ function readHeadroomState(fs25, stateFile) {
27533
27541
  try {
27534
- return parseJson(fs24.readFileUtf8(stateFile), HeadroomStateSchema);
27542
+ return parseJson(fs25.readFileUtf8(stateFile), HeadroomStateSchema);
27535
27543
  } catch {
27536
27544
  return void 0;
27537
27545
  }
27538
27546
  }
27539
- function writeHeadroomState(fs24, stateFile, state) {
27540
- fs24.mkdirp(import_node_path6.default.dirname(stateFile));
27541
- fs24.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
27547
+ function writeHeadroomState(fs25, stateFile, state) {
27548
+ fs25.mkdirp(import_node_path6.default.dirname(stateFile));
27549
+ fs25.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
27542
27550
  `);
27543
27551
  }
27544
- function resolveServingHeadroomState(fs24, files, isRunning) {
27545
- const current = readHeadroomState(fs24, files.stateFile);
27552
+ function resolveServingHeadroomState(fs25, files, isRunning) {
27553
+ const current = readHeadroomState(fs25, files.stateFile);
27546
27554
  if (current !== void 0) {
27547
27555
  return { path: files.stateFile, state: current };
27548
27556
  }
27549
- const legacy = readHeadroomState(fs24, files.legacyStateFile);
27557
+ const legacy = readHeadroomState(fs25, files.legacyStateFile);
27550
27558
  if (legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid)) {
27551
27559
  return { path: files.legacyStateFile, state: legacy };
27552
27560
  }
27553
27561
  return void 0;
27554
27562
  }
27555
- function migrateHeadroomState(fs24, files, isRunning) {
27556
- const legacy = readHeadroomState(fs24, files.legacyStateFile);
27563
+ function migrateHeadroomState(fs25, files, isRunning) {
27564
+ const legacy = readHeadroomState(fs25, files.legacyStateFile);
27557
27565
  const legacyLive = legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid);
27558
- const current = readHeadroomState(fs24, files.stateFile);
27566
+ const current = readHeadroomState(fs25, files.stateFile);
27559
27567
  if (current !== void 0 || legacyLive) {
27560
- if (!legacyLive && fs24.readFileUtf8(files.legacyStateFile) !== void 0) {
27561
- fs24.removeRecursive(files.legacyStateFile);
27568
+ if (!legacyLive && fs25.readFileUtf8(files.legacyStateFile) !== void 0) {
27569
+ fs25.removeRecursive(files.legacyStateFile);
27562
27570
  }
27563
27571
  return;
27564
27572
  }
27565
27573
  if (legacy !== void 0) {
27566
- writeHeadroomState(fs24, files.stateFile, legacy);
27574
+ writeHeadroomState(fs25, files.stateFile, legacy);
27567
27575
  }
27568
- fs24.removeRecursive(files.legacyStateFile);
27576
+ fs25.removeRecursive(files.legacyStateFile);
27569
27577
  }
27570
27578
  function hashAllowlist(allowlist) {
27571
27579
  return (0, import_node_crypto2.createHash)("sha256").update(allowlist.join("\n")).digest("hex");
@@ -27598,27 +27606,27 @@ function isAdmissibleUrl(entry) {
27598
27606
  function parseAllowlistFile(content) {
27599
27607
  return content.replace(/^\uFEFF/, "").replace(ALLOWLIST_FILE_COMMENT, "").split(ALLOWLIST_FILE_SEPARATORS).map((entry) => entry.replace(ALLOWLIST_SURROUNDING_WHITESPACE, "")).filter((entry) => entry !== "" && !ALLOWLIST_ENTRY_WHITESPACE.test(entry) && (entry.includes("://") ? isAdmissibleUrl(entry) : isBareHost(entry)));
27600
27608
  }
27601
- function writeAllowlistFile(fs24, allowlistFile, allowlist) {
27602
- fs24.mkdirPrivate(import_node_path6.default.dirname(allowlistFile));
27603
- fs24.writeFilePrivate(allowlistFile, formatAllowlistFile(allowlist));
27609
+ function writeAllowlistFile(fs25, allowlistFile, allowlist) {
27610
+ fs25.mkdirPrivate(import_node_path6.default.dirname(allowlistFile));
27611
+ fs25.writeFilePrivate(allowlistFile, formatAllowlistFile(allowlist));
27604
27612
  }
27605
- function pruneStaleAllowlistTemporaries(fs24, allowlistFile, isRunning) {
27613
+ function pruneStaleAllowlistTemporaries(fs25, allowlistFile, isRunning) {
27606
27614
  const prefix = `${import_node_path6.default.basename(allowlistFile)}.`;
27607
- for (const name of fs24.readdir(import_node_path6.default.dirname(allowlistFile))) {
27615
+ for (const name of fs25.readdir(import_node_path6.default.dirname(allowlistFile))) {
27608
27616
  const writer = name.startsWith(prefix) ? /^([1-9]\d*)\.tmp$/.exec(name.slice(prefix.length))?.[1] : void 0;
27609
27617
  if (writer !== void 0 && !isRunning(Number(writer))) {
27610
- fs24.removeRecursive(import_node_path6.default.join(import_node_path6.default.dirname(allowlistFile), name));
27618
+ fs25.removeRecursive(import_node_path6.default.join(import_node_path6.default.dirname(allowlistFile), name));
27611
27619
  }
27612
27620
  }
27613
27621
  }
27614
- function readAllProviders(fs24, providersDir) {
27622
+ function readAllProviders(fs25, providersDir) {
27615
27623
  const result = [];
27616
- for (const name of fs24.readdir(providersDir)) {
27624
+ for (const name of fs25.readdir(providersDir)) {
27617
27625
  if (!name.endsWith(".json")) {
27618
27626
  continue;
27619
27627
  }
27620
27628
  try {
27621
- const parsed = parseJson(fs24.readFileUtf8(import_node_path6.default.join(providersDir, name)), ProviderSchema);
27629
+ const parsed = parseJson(fs25.readFileUtf8(import_node_path6.default.join(providersDir, name)), ProviderSchema);
27622
27630
  if (parsed !== void 0) {
27623
27631
  result.push({ name: name.slice(0, -".json".length), provider: parsed });
27624
27632
  }
@@ -27628,22 +27636,22 @@ function readAllProviders(fs24, providersDir) {
27628
27636
  }
27629
27637
  return result;
27630
27638
  }
27631
- function writeSession(fs24, sessionsDir, session) {
27632
- fs24.mkdirp(sessionsDir);
27633
- fs24.writeFileUtf8(import_node_path6.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
27639
+ function writeSession(fs25, sessionsDir, session) {
27640
+ fs25.mkdirp(sessionsDir);
27641
+ fs25.writeFileUtf8(import_node_path6.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
27634
27642
  `);
27635
27643
  }
27636
- function removeSession(fs24, sessionsDir, pid) {
27637
- fs24.removeRecursive(import_node_path6.default.join(sessionsDir, `${String(pid)}.json`));
27644
+ function removeSession(fs25, sessionsDir, pid) {
27645
+ fs25.removeRecursive(import_node_path6.default.join(sessionsDir, `${String(pid)}.json`));
27638
27646
  }
27639
- function listSessions(fs24, sessionsDir) {
27647
+ function listSessions(fs25, sessionsDir) {
27640
27648
  const sessions = [];
27641
- for (const name of fs24.readdir(sessionsDir)) {
27649
+ for (const name of fs25.readdir(sessionsDir)) {
27642
27650
  if (!name.endsWith(".json")) {
27643
27651
  continue;
27644
27652
  }
27645
27653
  try {
27646
- const parsed = parseJson(fs24.readFileUtf8(import_node_path6.default.join(sessionsDir, name)), HeadroomSessionSchema);
27654
+ const parsed = parseJson(fs25.readFileUtf8(import_node_path6.default.join(sessionsDir, name)), HeadroomSessionSchema);
27647
27655
  if (parsed !== void 0) {
27648
27656
  sessions.push(parsed);
27649
27657
  }
@@ -27653,22 +27661,22 @@ function listSessions(fs24, sessionsDir) {
27653
27661
  }
27654
27662
  return sessions.sort((a10, b) => a10.pid - b.pid);
27655
27663
  }
27656
- function sessionsForSupervisor(fs24, sessionsDir, supervisorPid) {
27657
- return listSessions(fs24, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
27664
+ function sessionsForSupervisor(fs25, sessionsDir, supervisorPid) {
27665
+ return listSessions(fs25, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
27658
27666
  }
27659
- function pruneDeadSessions(fs24, sessionsDir, isRunning) {
27667
+ function pruneDeadSessions(fs25, sessionsDir, isRunning) {
27660
27668
  const removed = [];
27661
- for (const session of listSessions(fs24, sessionsDir)) {
27669
+ for (const session of listSessions(fs25, sessionsDir)) {
27662
27670
  if (!isRunning(session.pid)) {
27663
- removeSession(fs24, sessionsDir, session.pid);
27671
+ removeSession(fs25, sessionsDir, session.pid);
27664
27672
  removed.push(session.pid);
27665
27673
  }
27666
27674
  }
27667
27675
  return removed;
27668
27676
  }
27669
- function readStartLock(fs24, lockFile) {
27677
+ function readStartLock(fs25, lockFile) {
27670
27678
  try {
27671
- return parseJson(fs24.readFileUtf8(lockFile), HeadroomLockSchema);
27679
+ return parseJson(fs25.readFileUtf8(lockFile), HeadroomLockSchema);
27672
27680
  } catch {
27673
27681
  return void 0;
27674
27682
  }
@@ -27761,12 +27769,12 @@ function earlierReleaseAllowlistHash(providers, doorOrigin) {
27761
27769
  }
27762
27770
  return hashAllowlist([...entries].sort());
27763
27771
  }
27764
- function earlierReleaseDaemon(fs24, paths, daemon) {
27772
+ function earlierReleaseDaemon(fs25, paths, daemon) {
27765
27773
  if (daemonIdentity(daemon.commandLine, daemon.socketPath) !== "earlier-release") {
27766
27774
  return void 0;
27767
27775
  }
27768
- const providers = readAllProviders(fs24, paths.providersDir).map((entry) => entry.provider);
27769
- const expected = earlierReleaseAllowlistHash(providers, frontDoorOrigin(readFrontDoorState(fs24, paths.frontdoorStateFile)));
27776
+ const providers = readAllProviders(fs25, paths.providersDir).map((entry) => entry.provider);
27777
+ const expected = earlierReleaseAllowlistHash(providers, frontDoorOrigin(readFrontDoorState(fs25, paths.frontdoorStateFile)));
27770
27778
  return { admitsServingDoor: daemon.recordedHash === expected };
27771
27779
  }
27772
27780
  var EARLIER_RELEASE_ALLOWLIST, EARLIER_RELEASE_ANTHROPIC_UPSTREAM;
@@ -27791,8 +27799,8 @@ function awaitingCause(daemonPid, identity, allowlistFile) {
27791
27799
  }
27792
27800
  return `the headroom supervisor has not written an allowlist admitting this launch's upstreams to ${allowlistFile} within ${String(HEADROOM_START_TIMEOUT_MS)}ms`;
27793
27801
  }
27794
- function daemonAdmits(fs24, allowlistFile, recordedHash, required2) {
27795
- const content = fs24.readFileUtf8(allowlistFile);
27802
+ function daemonAdmits(fs25, allowlistFile, recordedHash, required2) {
27803
+ const content = fs25.readFileUtf8(allowlistFile);
27796
27804
  if (content === void 0 || recordedHash === void 0) {
27797
27805
  return false;
27798
27806
  }
@@ -28182,7 +28190,7 @@ function verifyAllowlistFile(allowlistFile, ports) {
28182
28190
  const replaceable = fileStat === void 0 || fileStat.kind === "file" || fileStat.kind === "symlink";
28183
28191
  return { message: refusal2, repairable: replaceable };
28184
28192
  }
28185
- function prepareHeadroomSocket(fs24, ports, paths, supervisorPid) {
28193
+ function prepareHeadroomSocket(fs25, ports, paths, supervisorPid) {
28186
28194
  const unsupported = platformRefusal(ports.platform);
28187
28195
  if (unsupported !== void 0) {
28188
28196
  return { refused: unsupported };
@@ -28197,18 +28205,18 @@ function prepareHeadroomSocket(fs24, ports, paths, supervisorPid) {
28197
28205
  if (ports.lstat(paths.headroomSocketDir)?.kind === "symlink") {
28198
28206
  return { refused: `the headroom socket directory ${paths.headroomSocketDir} is a symlink; it must be the real directory` };
28199
28207
  }
28200
- fs24.mkdirPrivate(paths.headroomSocketDir);
28208
+ fs25.mkdirPrivate(paths.headroomSocketDir);
28201
28209
  const refusal2 = ownerOnlyRefusal("socket directory", paths.headroomSocketDir, ports.lstat(paths.headroomSocketDir), "dir", ports.currentUid());
28202
28210
  return refusal2 === void 0 ? { socketPath } : { refused: refusal2 };
28203
28211
  }
28204
- function pruneStaleHeadroomSockets(fs24, paths, isRunning) {
28212
+ function pruneStaleHeadroomSockets(fs25, paths, isRunning) {
28205
28213
  const removed = [];
28206
- for (const name of fs24.readdir(paths.headroomSocketDir)) {
28214
+ for (const name of fs25.readdir(paths.headroomSocketDir)) {
28207
28215
  const pid = HEADROOM_SOCKET_NAME.exec(name)?.[1];
28208
28216
  if (pid === void 0 || isRunning(Number.parseInt(pid, 10))) {
28209
28217
  continue;
28210
28218
  }
28211
- fs24.removeRecursive(import_node_path7.default.join(paths.headroomSocketDir, name));
28219
+ fs25.removeRecursive(import_node_path7.default.join(paths.headroomSocketDir, name));
28212
28220
  removed.push(name);
28213
28221
  }
28214
28222
  return removed;
@@ -28355,37 +28363,37 @@ function compareVersions2(a10, b) {
28355
28363
  return 0;
28356
28364
  }
28357
28365
  async function runSupervisor(initialConfig, ports, options = {}) {
28358
- const { fs: fs24, paths } = ports;
28366
+ const { fs: fs25, paths } = ports;
28359
28367
  let config2 = initialConfig;
28360
- migrateHeadroomState(fs24, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
28361
- const previousState = resolveServingHeadroomState(fs24, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
28368
+ migrateHeadroomState(fs25, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
28369
+ const previousState = resolveServingHeadroomState(fs25, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
28362
28370
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
28363
28371
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
28364
28372
  return 0;
28365
28373
  }
28366
28374
  let installedSource = previousState?.installedSource;
28367
28375
  const ownsState = () => {
28368
- const owner = readHeadroomState(fs24, paths.headroomStateFile)?.supervisorPid;
28376
+ const owner = readHeadroomState(fs25, paths.headroomStateFile)?.supervisorPid;
28369
28377
  return owner === void 0 || owner === ports.ownPid || !ports.isRunning(owner);
28370
28378
  };
28371
28379
  const writeOwnState = (state) => {
28372
28380
  if (!ownsState()) {
28373
28381
  return false;
28374
28382
  }
28375
- writeHeadroomState(fs24, paths.headroomStateFile, state);
28383
+ writeHeadroomState(fs25, paths.headroomStateFile, state);
28376
28384
  return true;
28377
28385
  };
28378
28386
  const fail = (message) => {
28379
28387
  if (writeOwnState({ lastError: message })) {
28380
- fs24.removeRecursive(paths.headroomLockFile);
28388
+ fs25.removeRecursive(paths.headroomLockFile);
28381
28389
  }
28382
28390
  ports.log(`agent-shim headroom supervisor: ${message}`);
28383
28391
  return 1;
28384
28392
  };
28385
28393
  const syncAllowlistFile = (allowlist) => {
28386
28394
  try {
28387
- if (fs24.readFileUtf8(paths.headroomAllowlistFile) !== formatAllowlistFile(allowlist)) {
28388
- writeAllowlistFile(fs24, paths.headroomAllowlistFile, allowlist);
28395
+ if (fs25.readFileUtf8(paths.headroomAllowlistFile) !== formatAllowlistFile(allowlist)) {
28396
+ writeAllowlistFile(fs25, paths.headroomAllowlistFile, allowlist);
28389
28397
  ports.log(`agent-shim headroom supervisor: wrote allowlist [${allowlist.join(", ")}] to ${paths.headroomAllowlistFile}`);
28390
28398
  }
28391
28399
  return void 0;
@@ -28403,9 +28411,9 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28403
28411
  }
28404
28412
  ports.log(`agent-shim headroom supervisor: repairing the allowlist file: ${problem.message}`);
28405
28413
  try {
28406
- fs24.mkdirPrivate(paths.headroomDir);
28407
- fs24.mkdirPrivate(import_node_path8.default.dirname(paths.headroomAllowlistFile));
28408
- writeAllowlistFile(fs24, paths.headroomAllowlistFile, allowlist);
28414
+ fs25.mkdirPrivate(paths.headroomDir);
28415
+ fs25.mkdirPrivate(import_node_path8.default.dirname(paths.headroomAllowlistFile));
28416
+ writeAllowlistFile(fs25, paths.headroomAllowlistFile, allowlist);
28409
28417
  } catch (error63) {
28410
28418
  return `could not write the headroom allowlist file ${paths.headroomAllowlistFile}: ${error63 instanceof Error ? error63.message : String(error63)}`;
28411
28419
  }
@@ -28430,20 +28438,20 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28430
28438
  installedSource = config2.source;
28431
28439
  return void 0;
28432
28440
  };
28433
- const socket = prepareHeadroomSocket(fs24, ports.socketTrust, paths, ports.ownPid);
28441
+ const socket = prepareHeadroomSocket(fs25, ports.socketTrust, paths, ports.ownPid);
28434
28442
  if (socket.refused !== void 0) {
28435
28443
  return fail(socket.refused);
28436
28444
  }
28437
28445
  const { socketPath } = socket;
28438
- pruneStaleHeadroomSockets(fs24, paths, ports.isRunning);
28439
- pruneStaleAllowlistTemporaries(fs24, paths.headroomAllowlistFile, ports.isRunning);
28446
+ pruneStaleHeadroomSockets(fs25, paths, ports.isRunning);
28447
+ pruneStaleAllowlistTemporaries(fs25, paths.headroomAllowlistFile, ports.isRunning);
28440
28448
  const installFailure = ensureInstalled();
28441
28449
  if (installFailure !== void 0) {
28442
28450
  return fail(installFailure);
28443
28451
  }
28444
28452
  const version2 = ports.headroomVersion() ?? "unknown";
28445
28453
  writeOwnState({ supervisorPid: ports.ownPid, version: version2, installedSource });
28446
- ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: managing headroom on allowlist [${currentHeadroomAllowlistInputs(fs24, paths, ports.frontDoorLiveness).frontDoorOrigins.join(", ")}]`);
28454
+ ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: managing headroom on allowlist [${currentHeadroomAllowlistInputs(fs25, paths, ports.frontDoorLiveness).frontDoorOrigins.join(", ")}]`);
28447
28455
  const orphanPid = previousState?.headroomPid;
28448
28456
  const orphanSocket = previousState?.socketPath ?? (previousState?.supervisorPid === void 0 ? void 0 : headroomSocketPath(paths, previousState.supervisorPid));
28449
28457
  const orphanIdentity = orphanPid === void 0 || orphanSocket === void 0 || !ports.isRunning(orphanPid) ? void 0 : daemonIdentity(ports.daemonCommandLine(orphanPid), orphanSocket);
@@ -28478,12 +28486,12 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28478
28486
  ticks += 1;
28479
28487
  config2 = ports.readConfig();
28480
28488
  const settingsHash = hashSettings(config2.settings);
28481
- const inputs = currentHeadroomAllowlistInputs(fs24, paths, ports.frontDoorLiveness);
28482
- pruneDeadFrontDoorDirectRecords(fs24, paths.frontdoorDirectRecordsDir, inputs.frontDoorRecords, inputs.frontDoorLiveness);
28483
- pruneMalformedFrontDoorDirectFiles(fs24, paths.frontdoorDirectRecordsDir, ports.isRunning);
28489
+ const inputs = currentHeadroomAllowlistInputs(fs25, paths, ports.frontDoorLiveness);
28490
+ pruneDeadFrontDoorDirectRecords(fs25, paths.frontdoorDirectRecordsDir, inputs.frontDoorRecords, inputs.frontDoorLiveness);
28491
+ pruneMalformedFrontDoorDirectFiles(fs25, paths.frontdoorDirectRecordsDir, ports.isRunning);
28484
28492
  const allowlist = inputs.frontDoorOrigins;
28485
28493
  const allowlistHash = hashAllowlist(allowlist);
28486
- pruneDeadSessions(fs24, paths.headroomSessionsDir, ports.isRunning);
28494
+ pruneDeadSessions(fs25, paths.headroomSessionsDir, ports.isRunning);
28487
28495
  const ownsNow = ownsState();
28488
28496
  if (!ownsNow && !superseded) {
28489
28497
  ports.log("agent-shim headroom supervisor: another supervisor now owns the state file; serving this daemon's own sessions until they end");
@@ -28530,7 +28538,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28530
28538
  runningSettingsHash = settingsHash;
28531
28539
  const recorded = writeOwnState(servingState(pid));
28532
28540
  if (recorded) {
28533
- fs24.removeRecursive(paths.headroomLockFile);
28541
+ fs25.removeRecursive(paths.headroomLockFile);
28534
28542
  }
28535
28543
  idleSince = void 0;
28536
28544
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(pid)} ready on unix socket ${socketPath}`);
@@ -28558,7 +28566,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28558
28566
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(headroomPid)} now serves allowlist [${allowlist.join(", ")}]`);
28559
28567
  }
28560
28568
  if (runningSettingsHash !== settingsHash || installedSource !== config2.source) {
28561
- if (sessionsForSupervisor(fs24, paths.headroomSessionsDir, ports.ownPid).length === 0) {
28569
+ if (sessionsForSupervisor(fs25, paths.headroomSessionsDir, ports.ownPid).length === 0) {
28562
28570
  ports.log("agent-shim headroom supervisor: configuration drifted and no sessions are live; restarting headroom");
28563
28571
  ports.stopProcess(headroomPid);
28564
28572
  headroomPid = void 0;
@@ -28567,7 +28575,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
28567
28575
  continue;
28568
28576
  }
28569
28577
  }
28570
- const sessions = sessionsForSupervisor(fs24, paths.headroomSessionsDir, ports.ownPid);
28578
+ const sessions = sessionsForSupervisor(fs25, paths.headroomSessionsDir, ports.ownPid);
28571
28579
  if (sessions.length === 0) {
28572
28580
  idleSince ??= ports.now();
28573
28581
  const idleMs = ports.now() - idleSince;
@@ -28592,9 +28600,9 @@ function undeterminedFrontDoors(inputs) {
28592
28600
  return reason === void 0 ? [] : [{ pid: record2.pid, origin: directOrigin(record2.directPort), reason }];
28593
28601
  });
28594
28602
  }
28595
- function currentHeadroomAllowlistInputs(fs24, paths, frontDoorLiveness) {
28596
- const named = frontDoorOrigin(readFrontDoorState(fs24, paths.frontdoorStateFile));
28597
- const records = listFrontDoorDirectRecords(fs24, paths.frontdoorDirectRecordsDir);
28603
+ function currentHeadroomAllowlistInputs(fs25, paths, frontDoorLiveness) {
28604
+ const named = frontDoorOrigin(readFrontDoorState(fs25, paths.frontdoorStateFile));
28605
+ const records = listFrontDoorDirectRecords(fs25, paths.frontdoorDirectRecordsDir);
28598
28606
  const liveness = frontDoorLiveness(records.map((record2) => record2.pid));
28599
28607
  const live = liveFrontDoorDirectRecords(records, liveness).map((record2) => directOrigin(record2.directPort));
28600
28608
  return {
@@ -28603,8 +28611,8 @@ function currentHeadroomAllowlistInputs(fs24, paths, frontDoorLiveness) {
28603
28611
  frontDoorOrigins: [.../* @__PURE__ */ new Set([...named === void 0 ? [] : [named], ...live])].sort()
28604
28612
  };
28605
28613
  }
28606
- function launchRequiredUpstreams(fs24, paths) {
28607
- const door = frontDoorOrigin(readFrontDoorState(fs24, paths.frontdoorStateFile));
28614
+ function launchRequiredUpstreams(fs25, paths) {
28615
+ const door = frontDoorOrigin(readFrontDoorState(fs25, paths.frontdoorStateFile));
28608
28616
  return door === void 0 ? [] : [door];
28609
28617
  }
28610
28618
  async function waitUntilReady(ports, socketPath, pid) {
@@ -29762,8 +29770,8 @@ var require_utils = __commonJS({
29762
29770
  }
29763
29771
  return output2;
29764
29772
  };
29765
- exports2.basename = (path61, { windows } = {}) => {
29766
- const segs = path61.split(windows ? /[\\/]/ : "/");
29773
+ exports2.basename = (path63, { windows } = {}) => {
29774
+ const segs = path63.split(windows ? /[\\/]/ : "/");
29767
29775
  const last = segs[segs.length - 1];
29768
29776
  if (last === "") {
29769
29777
  return segs[segs.length - 2];
@@ -31435,8 +31443,8 @@ var init_classify = __esm({
31435
31443
  function poolNameOf(selector) {
31436
31444
  return selector.startsWith(POOL_SELECTOR_PREFIX) ? selector.slice(POOL_SELECTOR_PREFIX.length) : void 0;
31437
31445
  }
31438
- function readActiveIdentity(fs24, activeIdentityFile) {
31439
- const trimmed = fs24.readFileUtf8(activeIdentityFile)?.trim();
31446
+ function readActiveIdentity(fs25, activeIdentityFile) {
31447
+ const trimmed = fs25.readFileUtf8(activeIdentityFile)?.trim();
31440
31448
  return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
31441
31449
  }
31442
31450
  function isNonEmpty(value2) {
@@ -31483,8 +31491,8 @@ function decideConfigProfile(params) {
31483
31491
  }
31484
31492
  return { source: "none" };
31485
31493
  }
31486
- function loadIdentity(identitiesDir, name, fs24) {
31487
- return loadConfigFile(import_node_path11.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs24.readConfigFile);
31494
+ function loadIdentity(identitiesDir, name, fs25) {
31495
+ return loadConfigFile(import_node_path11.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs25.readConfigFile);
31488
31496
  }
31489
31497
  var import_node_path11, IDENTITY_DECISION_SOURCES, CONFIG_PROFILE_DECISION_SOURCES;
31490
31498
  var init_identity = __esm({
@@ -32888,8 +32896,8 @@ var init_pipeline = __esm({
32888
32896
  });
32889
32897
 
32890
32898
  // src/launcher/farm.ts
32891
- function readFarmManifest(fs24, farmRoot) {
32892
- const raw = fs24.readFileUtf8(import_node_path19.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs24.readFileUtf8(import_node_path19.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
32899
+ function readFarmManifest(fs25, farmRoot) {
32900
+ const raw = fs25.readFileUtf8(import_node_path19.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs25.readFileUtf8(import_node_path19.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
32893
32901
  if (raw === void 0) {
32894
32902
  return void 0;
32895
32903
  }
@@ -32947,9 +32955,9 @@ function buildEntryFacts(params) {
32947
32955
  entries
32948
32956
  };
32949
32957
  }
32950
- function listSubtree(fs24, root, rel) {
32958
+ function listSubtree(fs25, root, rel) {
32951
32959
  const absolute = import_node_path19.default.join(root, rel);
32952
- const stat = fs24.lstat(absolute);
32960
+ const stat = fs25.lstat(absolute);
32953
32961
  if (stat === void 0) {
32954
32962
  return [];
32955
32963
  }
@@ -32957,10 +32965,10 @@ function listSubtree(fs24, root, rel) {
32957
32965
  return [{ rel, kind: "symlink" }];
32958
32966
  }
32959
32967
  if (stat.kind === "dir") {
32960
- const children = [...fs24.readdir(absolute)].sort().flatMap((name) => listSubtree(fs24, root, `${rel}/${name}`));
32968
+ const children = [...fs25.readdir(absolute)].sort().flatMap((name) => listSubtree(fs25, root, `${rel}/${name}`));
32961
32969
  return [{ rel, kind: "dir" }, ...children];
32962
32970
  }
32963
- const contentHash = fs24.hashFile(absolute);
32971
+ const contentHash = fs25.hashFile(absolute);
32964
32972
  return [{ rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } }];
32965
32973
  }
32966
32974
  function topLevelScopeRoots(roots) {
@@ -32974,25 +32982,25 @@ function topLevelScopeRoots(roots) {
32974
32982
  }
32975
32983
  return kept;
32976
32984
  }
32977
- function reconciliationScope(fs24, farmRoot, manifest) {
32985
+ function reconciliationScope(fs25, farmRoot, manifest) {
32978
32986
  if (manifest !== void 0) {
32979
32987
  return topLevelScopeRoots(manifest.materialised);
32980
32988
  }
32981
- return [...fs24.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs24.lstat(import_node_path19.default.join(farmRoot, name))?.kind === "dir").sort();
32989
+ return [...fs25.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs25.lstat(import_node_path19.default.join(farmRoot, name))?.kind === "dir").sort();
32982
32990
  }
32983
- function collectFarmListing(fs24, farmRoot, scopeRoots) {
32984
- return scopeRoots.flatMap((root) => listSubtree(fs24, farmRoot, root));
32991
+ function collectFarmListing(fs25, farmRoot, scopeRoots) {
32992
+ return scopeRoots.flatMap((root) => listSubtree(fs25, farmRoot, root));
32985
32993
  }
32986
- function collectCanonicalCounterparts(fs24, claudeHome, farmListing) {
32994
+ function collectCanonicalCounterparts(fs25, claudeHome, farmListing) {
32987
32995
  const out = [];
32988
32996
  for (const entry of farmListing) {
32989
32997
  const absolute = import_node_path19.default.join(claudeHome, entry.rel);
32990
- const stat = fs24.lstat(absolute);
32998
+ const stat = fs25.lstat(absolute);
32991
32999
  if (stat === void 0) {
32992
33000
  continue;
32993
33001
  }
32994
33002
  if (stat.kind === "file") {
32995
- const contentHash = fs24.hashFile(absolute);
33003
+ const contentHash = fs25.hashFile(absolute);
32996
33004
  out.push({ rel: entry.rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } });
32997
33005
  continue;
32998
33006
  }
@@ -33435,6 +33443,7 @@ function buildLayoutPaths(root) {
33435
33443
  usageAnchorsFile: import_node_path20.default.join(root, "usage", "anchors.json"),
33436
33444
  usageJobsFile: import_node_path20.default.join(root, "usage", "jobs.json"),
33437
33445
  jobLogsDir: import_node_path20.default.join(root, "logs", "jobs"),
33446
+ superviseDir: import_node_path20.default.join(root, "supervise"),
33438
33447
  mcpPermissionsFile: import_node_path20.default.join(root, "mcp", "permissions.json")
33439
33448
  };
33440
33449
  }
@@ -34172,7 +34181,7 @@ var init_package = __esm({
34172
34181
  "package.json"() {
34173
34182
  package_default = {
34174
34183
  name: "claude-use",
34175
- version: "11.19.0",
34184
+ version: "11.20.0",
34176
34185
  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.",
34177
34186
  license: "MIT",
34178
34187
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -34285,14 +34294,14 @@ function isIdentityName(name) {
34285
34294
  function claudeJsonPath(identitiesDir, identity) {
34286
34295
  return import_node_path24.default.join(identitiesDir, identity, CLAUDE_JSON);
34287
34296
  }
34288
- function readAccountMetadata(fs24, identitiesDir, identity) {
34297
+ function readAccountMetadata(fs25, identitiesDir, identity) {
34289
34298
  if (!isIdentityName(identity)) {
34290
34299
  throw new Error(`"${identity}" is not a valid identity name.`);
34291
34300
  }
34292
- return readAccountMetadataFile(fs24, claudeJsonPath(identitiesDir, identity));
34301
+ return readAccountMetadataFile(fs25, claudeJsonPath(identitiesDir, identity));
34293
34302
  }
34294
- function readAccountMetadataFile(fs24, file2) {
34295
- const raw = fs24.readFileUtf8(file2);
34303
+ function readAccountMetadataFile(fs25, file2) {
34304
+ const raw = fs25.readFileUtf8(file2);
34296
34305
  if (raw === void 0) {
34297
34306
  return void 0;
34298
34307
  }
@@ -34322,19 +34331,19 @@ function readAccountMetadataFile(fs24, file2) {
34322
34331
  }
34323
34332
  return account.data;
34324
34333
  }
34325
- function createAccountReader(fs24, identitiesDir) {
34334
+ function createAccountReader(fs25, identitiesDir) {
34326
34335
  const cache = /* @__PURE__ */ new Map();
34327
34336
  return (identity) => {
34328
34337
  if (!isIdentityName(identity)) {
34329
34338
  throw new Error(`"${identity}" is not a valid identity name.`);
34330
34339
  }
34331
- const stat = fs24.lstat(claudeJsonPath(identitiesDir, identity));
34340
+ const stat = fs25.lstat(claudeJsonPath(identitiesDir, identity));
34332
34341
  const stamp = stat === void 0 ? "absent" : `${String(stat.mtimeMs)}:${String(stat.sizeBytes)}`;
34333
34342
  const cached2 = cache.get(identity);
34334
34343
  if (cached2?.stamp === stamp) {
34335
34344
  return cached2.account;
34336
34345
  }
34337
- const account = readAccountMetadata(fs24, identitiesDir, identity);
34346
+ const account = readAccountMetadata(fs25, identitiesDir, identity);
34338
34347
  cache.set(identity, { stamp, account });
34339
34348
  return account;
34340
34349
  };
@@ -34445,11 +34454,11 @@ function identifyRequest(headers) {
34445
34454
  function directOrigin2(port) {
34446
34455
  return `http://127.0.0.1:${String(port)}`;
34447
34456
  }
34448
- function parseProviderPath(path61) {
34449
- if (!path61.startsWith(PROVIDER_PATH_PREFIX)) {
34457
+ function parseProviderPath(path63) {
34458
+ if (!path63.startsWith(PROVIDER_PATH_PREFIX)) {
34450
34459
  return void 0;
34451
34460
  }
34452
- const tail = path61.slice(PROVIDER_PATH_PREFIX.length);
34461
+ const tail = path63.slice(PROVIDER_PATH_PREFIX.length);
34453
34462
  const slash = tail.indexOf("/");
34454
34463
  if (slash <= 0) {
34455
34464
  return void 0;
@@ -34776,12 +34785,12 @@ function decoderFor(encoding) {
34776
34785
  return void 0;
34777
34786
  }
34778
34787
  }
34779
- function destinationOf(path61, sessionProvider) {
34780
- const scoped = parseProviderPath(path61);
34788
+ function destinationOf(path63, sessionProvider) {
34789
+ const scoped = parseProviderPath(path63);
34781
34790
  if (scoped !== void 0) {
34782
34791
  return { provider: scoped.provider, endpoint: scoped.rest };
34783
34792
  }
34784
- return { provider: sessionProvider ?? ANTHROPIC_PROVIDER, endpoint: path61 };
34793
+ return { provider: sessionProvider ?? ANTHROPIC_PROVIDER, endpoint: path63 };
34785
34794
  }
34786
34795
  function buildRecord(event, context) {
34787
34796
  const { scan } = context;
@@ -35165,10 +35174,12 @@ function rankPool(input2) {
35165
35174
  const warmHere = sticky2?.identity === candidate.identity && nowMs - Date.parse(sticky2.at) <= PROMPT_CACHE_TTL_MS;
35166
35175
  if (input2.resuming && input2.resumeContextTokens !== void 0 && fiveHour !== void 0 && !warmHere) {
35167
35176
  const perToken = utilisationPerBilledToken(assessment.member.records);
35168
- const cost = perToken === void 0 ? void 0 : input2.resumeContextTokens * perToken;
35177
+ const committed = input2.committedContextTokens?.[candidate.identity] ?? 0;
35178
+ const cost = perToken === void 0 ? void 0 : (input2.resumeContextTokens + committed) * perToken;
35169
35179
  if (cost !== void 0 && cost > fiveHour.remaining) {
35170
35180
  dryAfterMs.push(0);
35171
- drySpots.push(`resuming a ${String(input2.resumeContextTokens)}-token conversation here would cost about ${percent(cost)} of the 5h window, which has ${percent(fiveHour.remaining)} left`);
35181
+ const alongside = committed === 0 ? "" : ` (with ${String(committed)} tokens of other conversations already moving here)`;
35182
+ drySpots.push(`resuming a ${String(input2.resumeContextTokens)}-token conversation here${alongside} would cost about ${percent(cost)} of the 5h window, which has ${percent(fiveHour.remaining)} left`);
35172
35183
  }
35173
35184
  }
35174
35185
  if (drySpots.length === 0) {
@@ -35236,8 +35247,8 @@ function segmentDay(epochMs) {
35236
35247
  function segmentName(day, pid) {
35237
35248
  return `${day}.${String(pid)}.jsonl`;
35238
35249
  }
35239
- function listLogSegments(fs24, logDir) {
35240
- return fs24.readdir(logDir).flatMap((name) => {
35250
+ function listLogSegments(fs25, logDir) {
35251
+ return fs25.readdir(logDir).flatMap((name) => {
35241
35252
  const match = SEGMENT_RE.exec(name);
35242
35253
  const day = match?.[1];
35243
35254
  if (day === void 0) {
@@ -35246,15 +35257,15 @@ function listLogSegments(fs24, logDir) {
35246
35257
  return [{ name, day, endsAt: Date.parse(`${day}T00:00:00.000Z`) + DAY_MS }];
35247
35258
  }).sort((left, right) => left.day.localeCompare(right.day) || left.name.localeCompare(right.name));
35248
35259
  }
35249
- function readUsageLog(fs24, logDir, options = {}) {
35260
+ function readUsageLog(fs25, logDir, options = {}) {
35250
35261
  const { sinceMs } = options;
35251
35262
  const records = [];
35252
35263
  let invalidLines = 0;
35253
- for (const segment of listLogSegments(fs24, logDir)) {
35264
+ for (const segment of listLogSegments(fs25, logDir)) {
35254
35265
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
35255
35266
  continue;
35256
35267
  }
35257
- const contents = fs24.readFileUtf8(import_node_path25.default.join(logDir, segment.name));
35268
+ const contents = fs25.readFileUtf8(import_node_path25.default.join(logDir, segment.name));
35258
35269
  if (contents === void 0) {
35259
35270
  continue;
35260
35271
  }
@@ -35290,9 +35301,9 @@ function snapshotPath(snapshotsDir, identity) {
35290
35301
  }
35291
35302
  return import_node_path25.default.join(snapshotsDir, `${identity}.json`);
35292
35303
  }
35293
- function readUsageSnapshot(fs24, snapshotsDir, identity) {
35304
+ function readUsageSnapshot(fs25, snapshotsDir, identity) {
35294
35305
  const file2 = snapshotPath(snapshotsDir, identity);
35295
- const raw = fs24.readFileUtf8(file2);
35306
+ const raw = fs25.readFileUtf8(file2);
35296
35307
  if (raw === void 0) {
35297
35308
  return void 0;
35298
35309
  }
@@ -35308,8 +35319,8 @@ function readUsageSnapshot(fs24, snapshotsDir, identity) {
35308
35319
  }
35309
35320
  return snapshot.data;
35310
35321
  }
35311
- function listUsageSnapshots(fs24, snapshotsDir) {
35312
- return fs24.readdir(snapshotsDir).flatMap((name) => {
35322
+ function listUsageSnapshots(fs25, snapshotsDir) {
35323
+ return fs25.readdir(snapshotsDir).flatMap((name) => {
35313
35324
  if (!name.endsWith(".json")) {
35314
35325
  return [];
35315
35326
  }
@@ -35317,7 +35328,7 @@ function listUsageSnapshots(fs24, snapshotsDir) {
35317
35328
  if (!isIdentityName(identity)) {
35318
35329
  return [];
35319
35330
  }
35320
- const snapshot = readUsageSnapshot(fs24, snapshotsDir, identity);
35331
+ const snapshot = readUsageSnapshot(fs25, snapshotsDir, identity);
35321
35332
  return snapshot === void 0 ? [] : [snapshot];
35322
35333
  }).sort((left, right) => left.identity.localeCompare(right.identity));
35323
35334
  }
@@ -35391,11 +35402,11 @@ var init_read = __esm({
35391
35402
  });
35392
35403
 
35393
35404
  // src/usage/store.ts
35394
- function pruneUsageLog(fs24, logDir, nowMs) {
35405
+ function pruneUsageLog(fs25, logDir, nowMs) {
35395
35406
  const cutoff = nowMs - USAGE_RETENTION_MS;
35396
- for (const segment of listLogSegments(fs24, logDir)) {
35407
+ for (const segment of listLogSegments(fs25, logDir)) {
35397
35408
  if (segment.endsAt <= cutoff) {
35398
- fs24.removeRecursive(import_node_path26.default.join(logDir, segment.name));
35409
+ fs25.removeRecursive(import_node_path26.default.join(logDir, segment.name));
35399
35410
  }
35400
35411
  }
35401
35412
  }
@@ -35424,7 +35435,7 @@ function foldProviderState(current, record2) {
35424
35435
  };
35425
35436
  }
35426
35437
  function createUsageStore(deps) {
35427
- const { fs: fs24, paths } = deps;
35438
+ const { fs: fs25, paths } = deps;
35428
35439
  let prunedDay;
35429
35440
  const rewriteSnapshot = (identity, fold) => {
35430
35441
  if (!isIdentityName(identity)) {
@@ -35433,7 +35444,7 @@ function createUsageStore(deps) {
35433
35444
  }
35434
35445
  let current;
35435
35446
  try {
35436
- current = readUsageSnapshot(fs24, paths.usageSnapshotsDir, identity);
35447
+ current = readUsageSnapshot(fs25, paths.usageSnapshotsDir, identity);
35437
35448
  } catch (error63) {
35438
35449
  if (!(error63 instanceof UsageSnapshotError)) {
35439
35450
  throw error63;
@@ -35460,8 +35471,8 @@ function createUsageStore(deps) {
35460
35471
  ...account === void 0 ? {} : { account },
35461
35472
  providers
35462
35473
  });
35463
- fs24.mkdirPrivate(paths.usageSnapshotsDir);
35464
- fs24.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
35474
+ fs25.mkdirPrivate(paths.usageSnapshotsDir);
35475
+ fs25.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
35465
35476
  `);
35466
35477
  deps.publish?.(snapshot);
35467
35478
  return true;
@@ -35470,14 +35481,14 @@ function createUsageStore(deps) {
35470
35481
  record: (input2) => {
35471
35482
  const record2 = UsageRecordSchema.parse(input2);
35472
35483
  const nowMs = deps.now();
35473
- fs24.mkdirPrivate(paths.usageDir);
35474
- fs24.mkdirPrivate(paths.usageLogDir);
35484
+ fs25.mkdirPrivate(paths.usageDir);
35485
+ fs25.mkdirPrivate(paths.usageLogDir);
35475
35486
  const day = segmentDay(nowMs);
35476
35487
  if (prunedDay !== day) {
35477
- pruneUsageLog(fs24, paths.usageLogDir, nowMs);
35488
+ pruneUsageLog(fs25, paths.usageLogDir, nowMs);
35478
35489
  prunedDay = day;
35479
35490
  }
35480
- fs24.appendFilePrivate(import_node_path26.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
35491
+ fs25.appendFilePrivate(import_node_path26.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
35481
35492
  `);
35482
35493
  if (record2.identity !== void 0) {
35483
35494
  rewriteSnapshot(record2.identity, (current) => ({ ...current?.providers, [record2.provider]: foldProviderState(current?.providers[record2.provider], record2) }));
@@ -35519,14 +35530,14 @@ var init_store2 = __esm({
35519
35530
  function errorMessage(error63) {
35520
35531
  return error63 instanceof Error ? error63.message : String(error63);
35521
35532
  }
35522
- function loadPoolMembers(fs24, paths, identities, nowMs) {
35533
+ function loadPoolMembers(fs25, paths, identities, nowMs) {
35523
35534
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
35524
- const log = readUsageLog(fs24, paths.usageLogDir, { sinceMs: windowStartMs });
35535
+ const log = readUsageLog(fs25, paths.usageLogDir, { sinceMs: windowStartMs });
35525
35536
  return identities.map((identity) => {
35526
35537
  const records = log.records.filter((record2) => record2.identity === identity && record2.provider === ANTHROPIC_PROVIDER && Date.parse(record2.at) >= windowStartMs);
35527
35538
  try {
35528
- const snapshot = readUsageSnapshot(fs24, paths.usageSnapshotsDir, identity);
35529
- const account = readAccountMetadata(fs24, paths.identitiesDir, identity) ?? snapshot?.account;
35539
+ const snapshot = readUsageSnapshot(fs25, paths.usageSnapshotsDir, identity);
35540
+ const account = readAccountMetadata(fs25, paths.identitiesDir, identity) ?? snapshot?.account;
35530
35541
  return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
35531
35542
  } catch (error63) {
35532
35543
  if (error63 instanceof UsageSnapshotError || error63 instanceof AccountMetadataError) {
@@ -35568,6 +35579,7 @@ function rankNamedPool(input2, poolName, stack, sticky) {
35568
35579
  nowMs: input2.nowMs,
35569
35580
  resuming: input2.resuming,
35570
35581
  ...input2.resumeContextTokens === void 0 ? {} : { resumeContextTokens: input2.resumeContextTokens },
35582
+ ...input2.committedContextTokens === void 0 ? {} : { committedContextTokens: input2.committedContextTokens },
35571
35583
  ...sticky === void 0 ? {} : { sticky },
35572
35584
  ...pool.preference === void 0 ? {} : { preference: pool.preference }
35573
35585
  });
@@ -35598,9 +35610,9 @@ function nestedMember(input2, nestedName, childStack, sticky) {
35598
35610
  missing: nested.missing
35599
35611
  };
35600
35612
  }
35601
- function readPicksFile(fs24, file2) {
35613
+ function readPicksFile(fs25, file2) {
35602
35614
  const empty = { schemaVersion: SCHEMA_VERSION, picks: {} };
35603
- const raw = fs24.readFileUtf8(file2);
35615
+ const raw = fs25.readFileUtf8(file2);
35604
35616
  if (raw === void 0) {
35605
35617
  return { file: empty };
35606
35618
  }
@@ -35613,17 +35625,17 @@ function readPicksFile(fs24, file2) {
35613
35625
  const result = PicksFileSchema.safeParse(parsed);
35614
35626
  return result.success ? { file: result.data } : { file: empty, problem: `${file2} is not a picks file this agent-shim can read` };
35615
35627
  }
35616
- function readStickyPick(fs24, picksFile, directory) {
35617
- const read = readPicksFile(fs24, picksFile);
35628
+ function readStickyPick(fs25, picksFile, directory) {
35629
+ const read = readPicksFile(fs25, picksFile);
35618
35630
  const entry = read.file.picks[directory];
35619
35631
  return { ...entry === void 0 ? {} : { sticky: entry }, ...read.problem === void 0 ? {} : { problem: read.problem } };
35620
35632
  }
35621
- function recordStickyPick(fs24, picksFile, directory, identity, nowMs) {
35622
- const current = readPicksFile(fs24, picksFile).file.picks;
35633
+ function recordStickyPick(fs25, picksFile, directory, identity, nowMs) {
35634
+ const current = readPicksFile(fs25, picksFile).file.picks;
35623
35635
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
35624
35636
  const next = { schemaVersion: SCHEMA_VERSION, picks: { ...Object.fromEntries(kept), [directory]: { identity, at: new Date(nowMs).toISOString() } } };
35625
- fs24.mkdirPrivate(import_node_path27.default.dirname(picksFile));
35626
- fs24.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
35637
+ fs25.mkdirPrivate(import_node_path27.default.dirname(picksFile));
35638
+ fs25.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
35627
35639
  `);
35628
35640
  }
35629
35641
  var import_node_path27, PoolGraphError, SCHEMA_VERSION, PickEntrySchema, PicksFileSchema;
@@ -37286,14 +37298,14 @@ var require_util2 = __commonJS({
37286
37298
  }
37287
37299
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
37288
37300
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
37289
- let path61 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
37301
+ let path63 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
37290
37302
  if (origin[origin.length - 1] === "/") {
37291
37303
  origin = origin.slice(0, origin.length - 1);
37292
37304
  }
37293
- if (path61 && path61[0] !== "/") {
37294
- path61 = `/${path61}`;
37305
+ if (path63 && path63[0] !== "/") {
37306
+ path63 = `/${path63}`;
37295
37307
  }
37296
- return new URL(`${origin}${path61}`);
37308
+ return new URL(`${origin}${path63}`);
37297
37309
  }
37298
37310
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
37299
37311
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -38114,9 +38126,9 @@ var require_diagnostics = __commonJS({
38114
38126
  "undici:client:sendHeaders",
38115
38127
  (evt) => {
38116
38128
  const {
38117
- request: { method, path: path61, origin }
38129
+ request: { method, path: path63, origin }
38118
38130
  } = evt;
38119
- debugLog("sending request to %s %s%s", method, origin, path61);
38131
+ debugLog("sending request to %s %s%s", method, origin, path63);
38120
38132
  }
38121
38133
  );
38122
38134
  }
@@ -38134,14 +38146,14 @@ var require_diagnostics = __commonJS({
38134
38146
  "undici:request:headers",
38135
38147
  (evt) => {
38136
38148
  const {
38137
- request: { method, path: path61, origin },
38149
+ request: { method, path: path63, origin },
38138
38150
  response: { statusCode }
38139
38151
  } = evt;
38140
38152
  debugLog(
38141
38153
  "received response to %s %s%s - HTTP %d",
38142
38154
  method,
38143
38155
  origin,
38144
- path61,
38156
+ path63,
38145
38157
  statusCode
38146
38158
  );
38147
38159
  }
@@ -38150,23 +38162,23 @@ var require_diagnostics = __commonJS({
38150
38162
  "undici:request:trailers",
38151
38163
  (evt) => {
38152
38164
  const {
38153
- request: { method, path: path61, origin }
38165
+ request: { method, path: path63, origin }
38154
38166
  } = evt;
38155
- debugLog("trailers received from %s %s%s", method, origin, path61);
38167
+ debugLog("trailers received from %s %s%s", method, origin, path63);
38156
38168
  }
38157
38169
  );
38158
38170
  diagnosticsChannel.subscribe(
38159
38171
  "undici:request:error",
38160
38172
  (evt) => {
38161
38173
  const {
38162
- request: { method, path: path61, origin },
38174
+ request: { method, path: path63, origin },
38163
38175
  error: error63
38164
38176
  } = evt;
38165
38177
  debugLog(
38166
38178
  "request to %s %s%s errored - %s",
38167
38179
  method,
38168
38180
  origin,
38169
- path61,
38181
+ path63,
38170
38182
  error63.message
38171
38183
  );
38172
38184
  }
@@ -38281,7 +38293,7 @@ var require_request = __commonJS({
38281
38293
  var kHandler = /* @__PURE__ */ Symbol("handler");
38282
38294
  var Request2 = class {
38283
38295
  constructor(origin, {
38284
- path: path61,
38296
+ path: path63,
38285
38297
  method,
38286
38298
  body,
38287
38299
  headers,
@@ -38298,11 +38310,11 @@ var require_request = __commonJS({
38298
38310
  maxRedirections,
38299
38311
  typeOfService
38300
38312
  }, handler) {
38301
- if (typeof path61 !== "string") {
38313
+ if (typeof path63 !== "string") {
38302
38314
  throw new InvalidArgumentError2("path must be a string");
38303
- } else if (path61[0] !== "/" && !(path61.startsWith("http://") || path61.startsWith("https://")) && method !== "CONNECT") {
38315
+ } else if (path63[0] !== "/" && !(path63.startsWith("http://") || path63.startsWith("https://")) && method !== "CONNECT") {
38304
38316
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
38305
- } else if (invalidPathRegex.test(path61)) {
38317
+ } else if (invalidPathRegex.test(path63)) {
38306
38318
  throw new InvalidArgumentError2("invalid request path");
38307
38319
  }
38308
38320
  if (typeof method !== "string") {
@@ -38377,7 +38389,7 @@ var require_request = __commonJS({
38377
38389
  this.completed = false;
38378
38390
  this.aborted = false;
38379
38391
  this.upgrade = upgrade || null;
38380
- this.path = query ? serializePathWithQuery(path61, query) : path61;
38392
+ this.path = query ? serializePathWithQuery(path63, query) : path63;
38381
38393
  this.origin = origin;
38382
38394
  this.protocol = getProtocolFromUrlString(origin);
38383
38395
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -43559,7 +43571,7 @@ var require_client_h1 = __commonJS({
43559
43571
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
43560
43572
  }
43561
43573
  function writeH1(client, request7) {
43562
- const { method, path: path61, host, upgrade, blocking, reset } = request7;
43574
+ const { method, path: path63, host, upgrade, blocking, reset } = request7;
43563
43575
  let { body, headers, contentLength } = request7;
43564
43576
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
43565
43577
  if (util2.isFormDataLike(body)) {
@@ -43637,7 +43649,7 @@ var require_client_h1 = __commonJS({
43637
43649
  if (socket.setTypeOfService) {
43638
43650
  socket.setTypeOfService(request7.typeOfService);
43639
43651
  }
43640
- let header = `${method} ${path61} HTTP/1.1\r
43652
+ let header = `${method} ${path63} HTTP/1.1\r
43641
43653
  `;
43642
43654
  if (typeof host === "string") {
43643
43655
  header += `host: ${host}\r
@@ -44316,7 +44328,7 @@ var require_client_h2 = __commonJS({
44316
44328
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
44317
44329
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
44318
44330
  const session = client[kHTTP2Session];
44319
- const { method, path: path61, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
44331
+ const { method, path: path63, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
44320
44332
  let { body } = request7;
44321
44333
  if (upgrade != null && upgrade !== "websocket") {
44322
44334
  util2.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -44385,7 +44397,7 @@ var require_client_h2 = __commonJS({
44385
44397
  }
44386
44398
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
44387
44399
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
44388
- headers[HTTP2_HEADER_PATH] = path61;
44400
+ headers[HTTP2_HEADER_PATH] = path63;
44389
44401
  if (protocol === "ws:" || protocol === "wss:") {
44390
44402
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
44391
44403
  } else {
@@ -44427,7 +44439,7 @@ var require_client_h2 = __commonJS({
44427
44439
  stream.setTimeout(headersTimeout);
44428
44440
  return true;
44429
44441
  }
44430
- headers[HTTP2_HEADER_PATH] = path61;
44442
+ headers[HTTP2_HEADER_PATH] = path63;
44431
44443
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
44432
44444
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
44433
44445
  if (body && typeof body.read === "function") {
@@ -46779,10 +46791,10 @@ var require_proxy_agent = __commonJS({
46779
46791
  };
46780
46792
  const {
46781
46793
  origin,
46782
- path: path61 = "/",
46794
+ path: path63 = "/",
46783
46795
  headers = {}
46784
46796
  } = opts;
46785
- opts.path = origin + path61;
46797
+ opts.path = origin + path63;
46786
46798
  if (!("host" in headers) && !("Host" in headers)) {
46787
46799
  const { host } = new URL(origin);
46788
46800
  headers.host = host;
@@ -48891,20 +48903,20 @@ var require_mock_utils = __commonJS({
48891
48903
  }
48892
48904
  return normalizedQp;
48893
48905
  }
48894
- function safeUrl(path61) {
48895
- if (typeof path61 !== "string") {
48896
- return path61;
48906
+ function safeUrl(path63) {
48907
+ if (typeof path63 !== "string") {
48908
+ return path63;
48897
48909
  }
48898
- const pathSegments = path61.split("?", 3);
48910
+ const pathSegments = path63.split("?", 3);
48899
48911
  if (pathSegments.length !== 2) {
48900
- return path61;
48912
+ return path63;
48901
48913
  }
48902
48914
  const qp2 = new URLSearchParams(pathSegments.pop());
48903
48915
  qp2.sort();
48904
48916
  return [...pathSegments, qp2.toString()].join("?");
48905
48917
  }
48906
- function matchKey(mockDispatch2, { path: path61, method, body, headers }) {
48907
- const pathMatch = matchValue(mockDispatch2.path, path61);
48918
+ function matchKey(mockDispatch2, { path: path63, method, body, headers }) {
48919
+ const pathMatch = matchValue(mockDispatch2.path, path63);
48908
48920
  const methodMatch = matchValue(mockDispatch2.method, method);
48909
48921
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
48910
48922
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -48929,8 +48941,8 @@ var require_mock_utils = __commonJS({
48929
48941
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
48930
48942
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
48931
48943
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
48932
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path61, ignoreTrailingSlash }) => {
48933
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path61)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path61), resolvedPath);
48944
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path63, ignoreTrailingSlash }) => {
48945
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path63)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path63), resolvedPath);
48934
48946
  });
48935
48947
  if (matchedMockDispatches.length === 0) {
48936
48948
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -48969,19 +48981,19 @@ var require_mock_utils = __commonJS({
48969
48981
  mockDispatches.splice(index, 1);
48970
48982
  }
48971
48983
  }
48972
- function removeTrailingSlash(path61) {
48973
- while (path61.endsWith("/")) {
48974
- path61 = path61.slice(0, -1);
48984
+ function removeTrailingSlash(path63) {
48985
+ while (path63.endsWith("/")) {
48986
+ path63 = path63.slice(0, -1);
48975
48987
  }
48976
- if (path61.length === 0) {
48977
- path61 = "/";
48988
+ if (path63.length === 0) {
48989
+ path63 = "/";
48978
48990
  }
48979
- return path61;
48991
+ return path63;
48980
48992
  }
48981
48993
  function buildKey(opts) {
48982
- const { path: path61, method, body, headers, query } = opts;
48994
+ const { path: path63, method, body, headers, query } = opts;
48983
48995
  return {
48984
- path: path61,
48996
+ path: path63,
48985
48997
  method,
48986
48998
  body,
48987
48999
  headers,
@@ -49671,10 +49683,10 @@ var require_pending_interceptors_formatter = __commonJS({
49671
49683
  }
49672
49684
  format(pendingInterceptors) {
49673
49685
  const withPrettyHeaders = pendingInterceptors.map(
49674
- ({ method, path: path61, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
49686
+ ({ method, path: path63, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
49675
49687
  Method: method,
49676
49688
  Origin: origin,
49677
- Path: path61,
49689
+ Path: path63,
49678
49690
  "Status code": statusCode,
49679
49691
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
49680
49692
  Invocations: timesInvoked,
@@ -49756,9 +49768,9 @@ var require_mock_agent = __commonJS({
49756
49768
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
49757
49769
  const dispatchOpts = { ...opts };
49758
49770
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
49759
- const [path61, searchParams] = dispatchOpts.path.split("?");
49771
+ const [path63, searchParams] = dispatchOpts.path.split("?");
49760
49772
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
49761
- dispatchOpts.path = `${path61}?${normalizedSearchParams}`;
49773
+ dispatchOpts.path = `${path63}?${normalizedSearchParams}`;
49762
49774
  }
49763
49775
  return this[kAgent].dispatch(dispatchOpts, handler);
49764
49776
  }
@@ -50159,12 +50171,12 @@ var require_snapshot_recorder = __commonJS({
50159
50171
  * @return {Promise<void>} - Resolves when snapshots are loaded
50160
50172
  */
50161
50173
  async loadSnapshots(filePath) {
50162
- const path61 = filePath || this.#snapshotPath;
50163
- if (!path61) {
50174
+ const path63 = filePath || this.#snapshotPath;
50175
+ if (!path63) {
50164
50176
  throw new InvalidArgumentError2("Snapshot path is required");
50165
50177
  }
50166
50178
  try {
50167
- const data = await readFile(resolve2(path61), "utf8");
50179
+ const data = await readFile(resolve2(path63), "utf8");
50168
50180
  const parsed = JSON.parse(data);
50169
50181
  if (Array.isArray(parsed)) {
50170
50182
  this.#snapshots.clear();
@@ -50178,7 +50190,7 @@ var require_snapshot_recorder = __commonJS({
50178
50190
  if (error63.code === "ENOENT") {
50179
50191
  this.#snapshots.clear();
50180
50192
  } else {
50181
- throw new UndiciError(`Failed to load snapshots from ${path61}`, { cause: error63 });
50193
+ throw new UndiciError(`Failed to load snapshots from ${path63}`, { cause: error63 });
50182
50194
  }
50183
50195
  }
50184
50196
  }
@@ -50189,11 +50201,11 @@ var require_snapshot_recorder = __commonJS({
50189
50201
  * @returns {Promise<void>} - Resolves when snapshots are saved
50190
50202
  */
50191
50203
  async saveSnapshots(filePath) {
50192
- const path61 = filePath || this.#snapshotPath;
50193
- if (!path61) {
50204
+ const path63 = filePath || this.#snapshotPath;
50205
+ if (!path63) {
50194
50206
  throw new InvalidArgumentError2("Snapshot path is required");
50195
50207
  }
50196
- const resolvedPath = resolve2(path61);
50208
+ const resolvedPath = resolve2(path63);
50197
50209
  await mkdir(dirname3(resolvedPath), { recursive: true });
50198
50210
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
50199
50211
  hash: hash2,
@@ -50825,15 +50837,15 @@ var require_redirect_handler = __commonJS({
50825
50837
  return;
50826
50838
  }
50827
50839
  const { origin, pathname, search } = util2.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
50828
- const path61 = search ? `${pathname}${search}` : pathname;
50829
- const redirectUrlString = `${origin}${path61}`;
50840
+ const path63 = search ? `${pathname}${search}` : pathname;
50841
+ const redirectUrlString = `${origin}${path63}`;
50830
50842
  for (const historyUrl of this.history) {
50831
50843
  if (historyUrl.toString() === redirectUrlString) {
50832
50844
  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.`);
50833
50845
  }
50834
50846
  }
50835
50847
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
50836
- this.opts.path = path61;
50848
+ this.opts.path = path63;
50837
50849
  this.opts.origin = origin;
50838
50850
  this.opts.query = null;
50839
50851
  }
@@ -52593,10 +52605,10 @@ var require_cache_handler = __commonJS({
52593
52605
  }
52594
52606
  return locationUrl.pathname + locationUrl.search;
52595
52607
  }
52596
- function deleteCachedUri(store, cacheKey, path61) {
52608
+ function deleteCachedUri(store, cacheKey, path63) {
52597
52609
  deleteCachedValue(store, {
52598
52610
  ...cacheKey,
52599
- path: path61
52611
+ path: path63
52600
52612
  });
52601
52613
  for (let i10 = 0; i10 < util2.safeHTTPMethods.length; i10++) {
52602
52614
  const method = util2.safeHTTPMethods[i10];
@@ -52604,7 +52616,7 @@ var require_cache_handler = __commonJS({
52604
52616
  deleteCachedValue(store, {
52605
52617
  ...cacheKey,
52606
52618
  method,
52607
- path: path61
52619
+ path: path63
52608
52620
  });
52609
52621
  }
52610
52622
  }
@@ -52615,9 +52627,9 @@ var require_cache_handler = __commonJS({
52615
52627
  }
52616
52628
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
52617
52629
  for (let i10 = 0; i10 < values.length; i10++) {
52618
- const path61 = getSameOriginPath(cacheKey, values[i10]);
52619
- if (path61 !== void 0) {
52620
- deleteCachedUri(store, cacheKey, path61);
52630
+ const path63 = getSameOriginPath(cacheKey, values[i10]);
52631
+ if (path63 !== void 0) {
52632
+ deleteCachedUri(store, cacheKey, path63);
52621
52633
  }
52622
52634
  }
52623
52635
  }
@@ -57617,11 +57629,11 @@ var require_fetch = __commonJS({
57617
57629
  function dispatch({ body }) {
57618
57630
  const url2 = requestCurrentURL(request7);
57619
57631
  const agent = fetchParams.controller.dispatcher;
57620
- const path61 = url2.pathname + url2.search;
57632
+ const path63 = url2.pathname + url2.search;
57621
57633
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
57622
57634
  return new Promise((resolve2, reject) => agent.dispatch(
57623
57635
  {
57624
- path: hasTrailingQuestionMark ? `${path61}?` : path61,
57636
+ path: hasTrailingQuestionMark ? `${path63}?` : path63,
57625
57637
  origin: url2.origin,
57626
57638
  method: request7.method,
57627
57639
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -58568,9 +58580,9 @@ var require_util5 = __commonJS({
58568
58580
  }
58569
58581
  }
58570
58582
  }
58571
- function validateCookiePath(path61) {
58572
- for (let i10 = 0; i10 < path61.length; ++i10) {
58573
- const code = path61.charCodeAt(i10);
58583
+ function validateCookiePath(path63) {
58584
+ for (let i10 = 0; i10 < path63.length; ++i10) {
58585
+ const code = path63.charCodeAt(i10);
58574
58586
  if (code < 32 || // exclude CTLs (0-31)
58575
58587
  code > 126 || // exclude DEL and non-ascii
58576
58588
  code === 59) {
@@ -61918,11 +61930,11 @@ var require_undici = __commonJS({
61918
61930
  if (typeof opts.path !== "string") {
61919
61931
  throw new InvalidArgumentError2("invalid opts.path");
61920
61932
  }
61921
- let path61 = opts.path;
61933
+ let path63 = opts.path;
61922
61934
  if (!opts.path.startsWith("/")) {
61923
- path61 = `/${path61}`;
61935
+ path63 = `/${path63}`;
61924
61936
  }
61925
- url2 = new URL(util2.parseOrigin(url2).origin + path61);
61937
+ url2 = new URL(util2.parseOrigin(url2).origin + path63);
61926
61938
  } else {
61927
61939
  if (!opts) {
61928
61940
  opts = typeof url2 === "object" ? url2 : {};
@@ -62293,14 +62305,14 @@ var init_selfIdentity = __esm({
62293
62305
 
62294
62306
  // src/frontdoor/trust.ts
62295
62307
  function resolveTrustBundle(params) {
62296
- const { caCertFile, bundlesDir, variable, inherited, fs: fs24 } = params;
62308
+ const { caCertFile, bundlesDir, variable, inherited, fs: fs25 } = params;
62297
62309
  if (inherited === void 0 || inherited === "" || import_node_path35.default.resolve(inherited) === import_node_path35.default.resolve(caCertFile)) {
62298
62310
  return { path: caCertFile };
62299
62311
  }
62300
- const caPem = fs24.readFileUtf8(caCertFile);
62312
+ const caPem = fs25.readFileUtf8(caCertFile);
62301
62313
  let inheritedPem;
62302
62314
  try {
62303
- inheritedPem = fs24.readFileUtf8(inherited);
62315
+ inheritedPem = fs25.readFileUtf8(inherited);
62304
62316
  } catch (error63) {
62305
62317
  return {
62306
62318
  path: caCertFile,
@@ -62313,9 +62325,9 @@ function resolveTrustBundle(params) {
62313
62325
  const combined = `${inheritedPem.trimEnd()}
62314
62326
  ${caPem}`;
62315
62327
  const bundle = import_node_path35.default.join(bundlesDir, `${(0, import_node_crypto11.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
62316
- if (!fs24.exists(bundle)) {
62317
- fs24.mkdirp(bundlesDir);
62318
- fs24.writeFileAtomic(bundle, combined);
62328
+ if (!fs25.exists(bundle)) {
62329
+ fs25.mkdirp(bundlesDir);
62330
+ fs25.writeFileAtomic(bundle, combined);
62319
62331
  }
62320
62332
  return { path: bundle };
62321
62333
  }
@@ -62482,20 +62494,20 @@ function lockHolder(contents) {
62482
62494
  const pid = Number((contents ?? "").trim());
62483
62495
  return Number.isInteger(pid) && pid > 0 ? pid : void 0;
62484
62496
  }
62485
- function acquireUpdateLock(fs24, isProcessAlive, pid, lockPath) {
62486
- const take = () => fs24.writeFileExclusive(lockPath, `${String(pid)}
62497
+ function acquireUpdateLock(fs25, isProcessAlive, pid, lockPath) {
62498
+ const take = () => fs25.writeFileExclusive(lockPath, `${String(pid)}
62487
62499
  `);
62488
62500
  const release = () => {
62489
- fs24.unlink(lockPath);
62501
+ fs25.unlink(lockPath);
62490
62502
  };
62491
62503
  if (take()) {
62492
62504
  return release;
62493
62505
  }
62494
- const holder = lockHolder(fs24.readFileUtf8(lockPath));
62506
+ const holder = lockHolder(fs25.readFileUtf8(lockPath));
62495
62507
  if (holder !== void 0 && holder !== pid && isProcessAlive(holder)) {
62496
62508
  throw new UpdateConflictError(`another agent-shim update (pid ${String(holder)}) is already running`);
62497
62509
  }
62498
- fs24.unlink(lockPath);
62510
+ fs25.unlink(lockPath);
62499
62511
  if (!take()) {
62500
62512
  throw new UpdateConflictError("another agent-shim update took the lock while it was being replaced");
62501
62513
  }
@@ -63196,9 +63208,175 @@ var init_extraFlags = __esm({
63196
63208
  }
63197
63209
  });
63198
63210
 
63211
+ // src/usage/resumeContext.ts
63212
+ function projectDirNameOf(cwd) {
63213
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
63214
+ }
63215
+ function resumeTargetOf(passthrough) {
63216
+ const end = passthrough.indexOf("--");
63217
+ const tokens = end === -1 ? passthrough : passthrough.slice(0, end);
63218
+ for (const [index, token] of tokens.entries()) {
63219
+ if (token === "--continue" || token === "-c") {
63220
+ return { kind: "latest" };
63221
+ }
63222
+ if (token === "--resume" || token === "-r") {
63223
+ const next = tokens[index + 1];
63224
+ return next === void 0 || next.startsWith("-") ? void 0 : { kind: "id", id: next };
63225
+ }
63226
+ if (token.startsWith("--resume=")) {
63227
+ const id2 = token.slice("--resume=".length);
63228
+ return id2 === "" ? void 0 : { kind: "id", id: id2 };
63229
+ }
63230
+ }
63231
+ return void 0;
63232
+ }
63233
+ function countOf(usage, key) {
63234
+ const value2 = key in usage ? Reflect.get(usage, key) : void 0;
63235
+ return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0 ? value2 : 0;
63236
+ }
63237
+ function contextTokensOfTranscript(text2) {
63238
+ const lines = text2.split("\n");
63239
+ for (let index = lines.length - 1; index >= 0; index -= 1) {
63240
+ const line = lines[index];
63241
+ if (line === void 0 || line === "") {
63242
+ continue;
63243
+ }
63244
+ let parsed;
63245
+ try {
63246
+ parsed = JSON.parse(line);
63247
+ } catch {
63248
+ continue;
63249
+ }
63250
+ if (typeof parsed !== "object" || parsed === null || !("type" in parsed) || parsed.type !== "assistant" || !("message" in parsed)) {
63251
+ continue;
63252
+ }
63253
+ const { message } = parsed;
63254
+ if (typeof message !== "object" || message === null || !("usage" in message) || typeof message.usage !== "object" || message.usage === null) {
63255
+ continue;
63256
+ }
63257
+ const { usage } = message;
63258
+ return countOf(usage, "input_tokens") + countOf(usage, "cache_read_input_tokens") + countOf(usage, "cache_creation_input_tokens");
63259
+ }
63260
+ return void 0;
63261
+ }
63262
+ function newestTranscript(fs25, projectDir) {
63263
+ let newest;
63264
+ let newestMs = -Infinity;
63265
+ for (const name of fs25.readdir(projectDir)) {
63266
+ if (!name.endsWith(".jsonl")) {
63267
+ continue;
63268
+ }
63269
+ const candidate = import_node_path40.default.join(projectDir, name);
63270
+ const stat = fs25.lstat(candidate);
63271
+ if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
63272
+ newestMs = stat.mtimeMs;
63273
+ newest = candidate;
63274
+ }
63275
+ }
63276
+ return newest;
63277
+ }
63278
+ function latestConversationId(fs25, params) {
63279
+ const file2 = newestTranscript(fs25, import_node_path40.default.join(params.claudeHome, "projects", projectDirNameOf(params.cwd)));
63280
+ return file2 === void 0 ? void 0 : import_node_path40.default.basename(file2, ".jsonl");
63281
+ }
63282
+ function resumedContextTokens(fs25, params) {
63283
+ const target = resumeTargetOf(params.passthrough);
63284
+ if (target === void 0) {
63285
+ return void 0;
63286
+ }
63287
+ const projectDir = import_node_path40.default.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
63288
+ const file2 = target.kind === "id" ? import_node_path40.default.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs25, projectDir);
63289
+ const text2 = file2 === void 0 ? void 0 : fs25.readFileUtf8(file2);
63290
+ return text2 === void 0 ? void 0 : contextTokensOfTranscript(text2);
63291
+ }
63292
+ var import_node_path40;
63293
+ var init_resumeContext = __esm({
63294
+ "src/usage/resumeContext.ts"() {
63295
+ "use strict";
63296
+ import_node_path40 = __toESM(require("node:path"), 1);
63297
+ }
63298
+ });
63299
+
63300
+ // src/launcher/claudeSession.ts
63301
+ function isFlag(token) {
63302
+ return token?.startsWith("-") === true;
63303
+ }
63304
+ function withConversation(passthrough, conversation, id2) {
63305
+ const end = passthrough.indexOf(TERMINATOR2);
63306
+ const head = end === -1 ? passthrough : passthrough.slice(0, end);
63307
+ const tail = end === -1 ? [] : passthrough.slice(end);
63308
+ const kept = [];
63309
+ for (let index = 0; index < head.length; index += 1) {
63310
+ const token = head[index];
63311
+ if (token === void 0 || CONTINUE_FLAGS.has(token) || token.startsWith("--resume=") || token.startsWith("--session-id=")) {
63312
+ continue;
63313
+ }
63314
+ if (VALUED_CONVERSATION_FLAGS.has(token)) {
63315
+ if (!isFlag(head[index + 1]) && head[index + 1] !== void 0) {
63316
+ index += 1;
63317
+ }
63318
+ continue;
63319
+ }
63320
+ kept.push(token);
63321
+ }
63322
+ return [...kept, conversation === "start" ? "--session-id" : "--resume", id2, ...tail];
63323
+ }
63324
+ function hasSettingsArgument(passthrough) {
63325
+ const end = passthrough.indexOf(TERMINATOR2);
63326
+ return (end === -1 ? passthrough : passthrough.slice(0, end)).some((token) => token === "--settings" || token.startsWith("--settings="));
63327
+ }
63328
+ function withSupervision(passthrough, supervised) {
63329
+ const conversation = supervised.conversation === "as-given" ? passthrough : withConversation(passthrough, supervised.conversation, supervised.sessionId);
63330
+ if (supervised.settings === void 0) {
63331
+ return conversation;
63332
+ }
63333
+ const end = conversation.indexOf(TERMINATOR2);
63334
+ return end === -1 ? [...conversation, "--settings", supervised.settings] : [...conversation.slice(0, end), "--settings", supervised.settings, ...conversation.slice(end)];
63335
+ }
63336
+ function opensPicker(passthrough) {
63337
+ const end = passthrough.indexOf(TERMINATOR2);
63338
+ const head = end === -1 ? passthrough : passthrough.slice(0, end);
63339
+ return head.some((token, index) => (token === "--resume" || token === "-r") && (head[index + 1] === void 0 || isFlag(head[index + 1])));
63340
+ }
63341
+ function isPrintRun(passthrough) {
63342
+ const end = passthrough.indexOf(TERMINATOR2);
63343
+ return (end === -1 ? passthrough : passthrough.slice(0, end)).some((token) => token === "-p" || token === "--print");
63344
+ }
63345
+ function initialConversationOf(passthrough, context) {
63346
+ if (isPrintRun(passthrough)) {
63347
+ return { reason: "a print run ends by itself" };
63348
+ }
63349
+ const target = resumeTargetOf(passthrough);
63350
+ if (target?.kind === "id") {
63351
+ return CONVERSATION_ID_RE.test(target.id) ? { sessionId: target.id, conversation: "as-given" } : { reason: "the conversation id is not a plain identifier" };
63352
+ }
63353
+ if (target?.kind === "latest") {
63354
+ const latest = context.latestId();
63355
+ if (latest === void 0) {
63356
+ return { reason: "there is no conversation in this directory to continue" };
63357
+ }
63358
+ return CONVERSATION_ID_RE.test(latest) ? { sessionId: latest, conversation: "resume" } : { reason: "the latest conversation's id is not a plain identifier" };
63359
+ }
63360
+ if (opensPicker(passthrough)) {
63361
+ return { reason: "the conversation picker names no conversation until one is chosen" };
63362
+ }
63363
+ return { sessionId: context.newId(), conversation: "start" };
63364
+ }
63365
+ var TERMINATOR2, VALUED_CONVERSATION_FLAGS, CONTINUE_FLAGS, CONVERSATION_ID_RE;
63366
+ var init_claudeSession = __esm({
63367
+ "src/launcher/claudeSession.ts"() {
63368
+ "use strict";
63369
+ init_resumeContext();
63370
+ TERMINATOR2 = "--";
63371
+ VALUED_CONVERSATION_FLAGS = /* @__PURE__ */ new Set(["--resume", "-r", "--session-id"]);
63372
+ CONTINUE_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c"]);
63373
+ CONVERSATION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
63374
+ }
63375
+ });
63376
+
63199
63377
  // src/launcher/pool.ts
63200
63378
  function isResuming(passthrough) {
63201
- const end = passthrough.indexOf(TERMINATOR2);
63379
+ const end = passthrough.indexOf(TERMINATOR3);
63202
63380
  return (end === -1 ? passthrough : passthrough.slice(0, end)).some((token) => RESUME_FLAGS.has(token));
63203
63381
  }
63204
63382
  function resolvePoolLaunch(params) {
@@ -63225,6 +63403,7 @@ function resolvePoolLaunch(params) {
63225
63403
  nowMs,
63226
63404
  resuming,
63227
63405
  ...params.resumeContextTokens === void 0 ? {} : { resumeContextTokens: params.resumeContextTokens },
63406
+ ...params.committedContextTokens === void 0 ? {} : { committedContextTokens: params.committedContextTokens },
63228
63407
  identityExists: (name) => loadIdentity(params.paths.identitiesDir, name, params.fs) !== void 0,
63229
63408
  ...stickyRead.sticky === void 0 ? {} : { sticky: stickyRead.sticky }
63230
63409
  });
@@ -63282,7 +63461,7 @@ function resolvePoolLaunch(params) {
63282
63461
  params.sleep(Math.max(earliestReturn.atMs - nowMs, 0));
63283
63462
  }
63284
63463
  }
63285
- var RESUME_FLAGS, TERMINATOR2, REASONS_LOGGED;
63464
+ var RESUME_FLAGS, TERMINATOR3, REASONS_LOGGED;
63286
63465
  var init_pool = __esm({
63287
63466
  "src/launcher/pool.ts"() {
63288
63467
  "use strict";
@@ -63290,96 +63469,11 @@ var init_pool = __esm({
63290
63469
  init_preflight();
63291
63470
  init_poolPick();
63292
63471
  RESUME_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c", "--resume", "-r"]);
63293
- TERMINATOR2 = "--";
63472
+ TERMINATOR3 = "--";
63294
63473
  REASONS_LOGGED = 3;
63295
63474
  }
63296
63475
  });
63297
63476
 
63298
- // src/usage/resumeContext.ts
63299
- function projectDirNameOf(cwd) {
63300
- return cwd.replace(/[^A-Za-z0-9]/g, "-");
63301
- }
63302
- function resumeTargetOf(passthrough) {
63303
- const end = passthrough.indexOf("--");
63304
- const tokens = end === -1 ? passthrough : passthrough.slice(0, end);
63305
- for (const [index, token] of tokens.entries()) {
63306
- if (token === "--continue" || token === "-c") {
63307
- return { kind: "latest" };
63308
- }
63309
- if (token === "--resume" || token === "-r") {
63310
- const next = tokens[index + 1];
63311
- return next === void 0 || next.startsWith("-") ? void 0 : { kind: "id", id: next };
63312
- }
63313
- if (token.startsWith("--resume=")) {
63314
- const id2 = token.slice("--resume=".length);
63315
- return id2 === "" ? void 0 : { kind: "id", id: id2 };
63316
- }
63317
- }
63318
- return void 0;
63319
- }
63320
- function countOf(usage, key) {
63321
- const value2 = key in usage ? Reflect.get(usage, key) : void 0;
63322
- return typeof value2 === "number" && Number.isFinite(value2) && value2 >= 0 ? value2 : 0;
63323
- }
63324
- function contextTokensOfTranscript(text2) {
63325
- const lines = text2.split("\n");
63326
- for (let index = lines.length - 1; index >= 0; index -= 1) {
63327
- const line = lines[index];
63328
- if (line === void 0 || line === "") {
63329
- continue;
63330
- }
63331
- let parsed;
63332
- try {
63333
- parsed = JSON.parse(line);
63334
- } catch {
63335
- continue;
63336
- }
63337
- if (typeof parsed !== "object" || parsed === null || !("type" in parsed) || parsed.type !== "assistant" || !("message" in parsed)) {
63338
- continue;
63339
- }
63340
- const { message } = parsed;
63341
- if (typeof message !== "object" || message === null || !("usage" in message) || typeof message.usage !== "object" || message.usage === null) {
63342
- continue;
63343
- }
63344
- const { usage } = message;
63345
- return countOf(usage, "input_tokens") + countOf(usage, "cache_read_input_tokens") + countOf(usage, "cache_creation_input_tokens");
63346
- }
63347
- return void 0;
63348
- }
63349
- function resumedContextTokens(fs24, params) {
63350
- const target = resumeTargetOf(params.passthrough);
63351
- if (target === void 0) {
63352
- return void 0;
63353
- }
63354
- const projectDir = import_node_path40.default.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
63355
- let file2;
63356
- if (target.kind === "id") {
63357
- file2 = import_node_path40.default.join(projectDir, `${target.id}.jsonl`);
63358
- } else {
63359
- let newestMs = -Infinity;
63360
- for (const name of fs24.readdir(projectDir)) {
63361
- if (!name.endsWith(".jsonl")) {
63362
- continue;
63363
- }
63364
- const candidate = import_node_path40.default.join(projectDir, name);
63365
- const stat = fs24.lstat(candidate);
63366
- if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
63367
- newestMs = stat.mtimeMs;
63368
- file2 = candidate;
63369
- }
63370
- }
63371
- }
63372
- const text2 = file2 === void 0 ? void 0 : fs24.readFileUtf8(file2);
63373
- return text2 === void 0 ? void 0 : contextTokensOfTranscript(text2);
63374
- }
63375
- var import_node_path40;
63376
- var init_resumeContext = __esm({
63377
- "src/usage/resumeContext.ts"() {
63378
- "use strict";
63379
- import_node_path40 = __toESM(require("node:path"), 1);
63380
- }
63381
- });
63382
-
63383
63477
  // src/launcher/spawn.ts
63384
63478
  function childExitCode(result) {
63385
63479
  if (result.status !== null) {
@@ -63487,10 +63581,14 @@ function resolveIdentityCredential(identity, credential, env, port) {
63487
63581
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: resolution.message };
63488
63582
  }
63489
63583
  function pickFromPool(decided, params, parsedArgv, readOnly) {
63490
- const { paths, fs: fs24, proc, log } = params;
63584
+ const { paths, fs: fs25, proc, log } = params;
63491
63585
  if (decided.pool === void 0) {
63492
63586
  return { identityDecision: decided };
63493
63587
  }
63588
+ if (params.supervised?.member !== void 0) {
63589
+ const reasons = ["resumed here by the supervising launcher after the previous member ran out of quota"];
63590
+ return { identityDecision: { ...decided, name: params.supervised.member }, poolExplanation: `pool ${decided.pool}: ${reasons.join("; ")}`, poolPick: { name: decided.pool, reasons } };
63591
+ }
63494
63592
  const farmRuntime = params.farm;
63495
63593
  if (farmRuntime === void 0) {
63496
63594
  log.error(`agent-shim: pool "${decided.pool}" was selected, but this launcher has no farm wired to read usage and pick a member with.`);
@@ -63502,7 +63600,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
63502
63600
  selectedVia: decided.source,
63503
63601
  pools: params.pools,
63504
63602
  paths,
63505
- fs: fs24,
63603
+ fs: fs25,
63506
63604
  usageFs: farmRuntime.fs,
63507
63605
  cwd: farmRuntime.cwd,
63508
63606
  now: farmRuntime.now,
@@ -63525,7 +63623,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
63525
63623
  };
63526
63624
  }
63527
63625
  function decideLaunch(params, readOnly) {
63528
- const { paths, fs: fs24, proc, log } = params;
63626
+ const { paths, fs: fs25, proc, log } = params;
63529
63627
  const { env, argv } = proc;
63530
63628
  const parsedArgv = parseLauncherArgv(argv);
63531
63629
  const cliOverride = buildCliOverride({
@@ -63540,7 +63638,7 @@ function decideLaunch(params, readOnly) {
63540
63638
  argv0Identity: parsedArgv.identity,
63541
63639
  directoryPinnedIdentity: params.directoryPinnedIdentity,
63542
63640
  readActiveIdentityFile: () => {
63543
- const raw = fs24.readFileUtf8(paths.activeIdentityFile);
63641
+ const raw = fs25.readFileUtf8(paths.activeIdentityFile);
63544
63642
  if (raw === void 0) {
63545
63643
  return void 0;
63546
63644
  }
@@ -63575,7 +63673,7 @@ function decideLaunch(params, readOnly) {
63575
63673
  }
63576
63674
  let loadedIdentity;
63577
63675
  if (identityDecision.name !== void 0) {
63578
- loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs24);
63676
+ loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs25);
63579
63677
  if (loadedIdentity === void 0) {
63580
63678
  log.error(
63581
63679
  `agent-shim: no identity named "${identityDecision.name}" (selected via ${identityDecision.source}). Run \`agent-shim identity add ${identityDecision.name}\` first.`
@@ -63590,7 +63688,7 @@ function decideLaunch(params, readOnly) {
63590
63688
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
63591
63689
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
63592
63690
  });
63593
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs24.readConfigFile(import_node_path41.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
63691
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs25.readConfigFile(import_node_path41.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
63594
63692
  log.error(
63595
63693
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
63596
63694
  );
@@ -63599,7 +63697,7 @@ function decideLaunch(params, readOnly) {
63599
63697
  const farmContext = farm !== void 0 && farmIdentity !== void 0 ? { farm, identity: farmIdentity, cascade: farm.loadCascade(configProfileDecision.name, cliOverride) } : void 0;
63600
63698
  const providerParams = {
63601
63699
  paths,
63602
- port: fs24,
63700
+ port: fs25,
63603
63701
  ...parsedArgv.provider === void 0 || parsedArgv.provider === false ? {} : { cliProvider: parsedArgv.provider },
63604
63702
  ...farmContext === void 0 ? {} : { cascade: farmContext.cascade }
63605
63703
  };
@@ -63698,7 +63796,7 @@ function decideLaunch(params, readOnly) {
63698
63796
  const args = buildArgv({
63699
63797
  toolFlags: buildFlagArgs(flags),
63700
63798
  extraFlags: splitExtraFlags(env.CLAUDE_EXTRA_FLAGS),
63701
- passthrough: parsedArgv.rest
63799
+ passthrough: params.supervised === void 0 ? parsedArgv.rest : withSupervision(parsedArgv.rest, params.supervised)
63702
63800
  });
63703
63801
  const configDir = configDirEscapeHatchApplies || identityDecision.name === void 0 ? env.CLAUDE_CONFIG_DIR : import_node_path41.default.join(paths.identitiesDir, identityDecision.name);
63704
63802
  const decision = {
@@ -63810,6 +63908,7 @@ function prepareLaunch(params) {
63810
63908
  log.info(`agent-shim: routing through the front door on 127.0.0.1:${String(frontDoor.port)}${resolvedProvider === void 0 ? ` (OAuth via the door's CONNECT surface on 127.0.0.1:${String(frontDoor.connectPort)}, usage recorded)` : ` (provider ${resolvedProvider.name})`}`);
63811
63909
  }
63812
63910
  const frontDoorRelease = frontDoor === void 0 ? void 0 : frontDoorPort?.release;
63911
+ const sessionId = params.supervised?.sessionId ?? (0, import_node_crypto14.randomUUID)();
63813
63912
  const finalEnv = buildEnv({
63814
63913
  baseEnv: env,
63815
63914
  configDirEscapeHatch: configDirEscapeHatchApplies,
@@ -63819,7 +63918,7 @@ function prepareLaunch(params) {
63819
63918
  ...identityCredential === void 0 ? {} : { identityCredential },
63820
63919
  ...frontDoor === void 0 ? {} : { frontdoor: frontDoor },
63821
63920
  ...headroom === void 0 ? {} : { headroom },
63822
- sessionId: (0, import_node_crypto14.randomUUID)()
63921
+ sessionId
63823
63922
  });
63824
63923
  const releases = [...headroom === void 0 || headroomPort === void 0 ? [] : [headroomPort.release], ...frontDoorRelease === void 0 ? [] : [frontDoorRelease]];
63825
63924
  const release = () => {
@@ -63827,7 +63926,7 @@ function prepareLaunch(params) {
63827
63926
  registered();
63828
63927
  }
63829
63928
  };
63830
- return { bin: decided.bin, args: finalArgv, env: finalEnv, release, markChildStarted: updateCheck.markChildStarted, decision };
63929
+ return { bin: decided.bin, args: finalArgv, env: finalEnv, sessionId, release, markChildStarted: updateCheck.markChildStarted, decision };
63831
63930
  }
63832
63931
  function resolveLaunch(params) {
63833
63932
  const decided = decideLaunch(params, true);
@@ -63857,10 +63956,10 @@ function resolveLaunch(params) {
63857
63956
  environment
63858
63957
  };
63859
63958
  }
63860
- function runLaunchPlan(plan, spawn7) {
63959
+ function runLaunchPlan(plan, spawn8) {
63861
63960
  try {
63862
63961
  plan.markChildStarted();
63863
- const result = spawn7.spawnSync(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
63962
+ const result = spawn8.spawnSync(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
63864
63963
  if (result.error !== void 0) {
63865
63964
  throw result.error;
63866
63965
  }
@@ -63887,6 +63986,7 @@ var init_launcher = __esm({
63887
63986
  init_identity();
63888
63987
  init_flags();
63889
63988
  init_extraFlags();
63989
+ init_claudeSession();
63890
63990
  init_pool();
63891
63991
  init_resumeContext();
63892
63992
  init_lock();
@@ -101310,8 +101410,8 @@ var require_utils3 = __commonJS({
101310
101410
  }
101311
101411
  return ind;
101312
101412
  }
101313
- function removeDotSegments(path61) {
101314
- let input2 = path61;
101413
+ function removeDotSegments(path63) {
101414
+ let input2 = path63;
101315
101415
  const output2 = [];
101316
101416
  let nextSlash = -1;
101317
101417
  let len = 0;
@@ -101720,8 +101820,8 @@ var require_schemes = __commonJS({
101720
101820
  }
101721
101821
  if (wsComponent.resourceName) {
101722
101822
  const queryIndex = wsComponent.resourceName.indexOf("?");
101723
- const path61 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
101724
- wsComponent.path = path61 && path61 !== "/" ? path61 : void 0;
101823
+ const path63 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
101824
+ wsComponent.path = path63 && path63 !== "/" ? path63 : void 0;
101725
101825
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
101726
101826
  wsComponent.resourceName = void 0;
101727
101827
  }
@@ -105234,12 +105334,12 @@ var require_dist2 = __commonJS({
105234
105334
  throw new Error(`Unknown format "${name}"`);
105235
105335
  return f;
105236
105336
  };
105237
- function addFormats(ajv, list, fs24, exportName) {
105337
+ function addFormats(ajv, list, fs25, exportName) {
105238
105338
  var _a4;
105239
105339
  var _b2;
105240
105340
  (_a4 = (_b2 = ajv.opts.code).formats) !== null && _a4 !== void 0 ? _a4 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
105241
105341
  for (const f of list)
105242
- ajv.addFormat(f, fs24[f]);
105342
+ ajv.addFormat(f, fs25[f]);
105243
105343
  }
105244
105344
  module2.exports = exports2 = formatsPlugin;
105245
105345
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -105248,7 +105348,7 @@ var require_dist2 = __commonJS({
105248
105348
  });
105249
105349
 
105250
105350
  // src/cli.ts
105251
- var import_node_path60 = __toESM(require("node:path"), 1);
105351
+ var import_node_path62 = __toESM(require("node:path"), 1);
105252
105352
 
105253
105353
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
105254
105354
  var CommanderError = class extends Error {
@@ -108361,9 +108461,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
108361
108461
  * @param {string} [path]
108362
108462
  * @return {(string|null|Command)}
108363
108463
  */
108364
- executableDir(path61) {
108365
- if (path61 === void 0) return this._executableDir;
108366
- this._executableDir = path61;
108464
+ executableDir(path63) {
108465
+ if (path63 === void 0) return this._executableDir;
108466
+ this._executableDir = path63;
108367
108467
  return this;
108368
108468
  }
108369
108469
  /**
@@ -110012,19 +110112,19 @@ function writePools(paths, pools) {
110012
110112
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
110013
110113
  }
110014
110114
  function poolCycleOf(pools, name) {
110015
- const walk2 = (current, path61) => {
110115
+ const walk2 = (current, path63) => {
110016
110116
  for (const entry of pools[current]?.identities ?? []) {
110017
110117
  const nested = poolNameOf(poolMemberIdentity(entry));
110018
110118
  if (nested === void 0) {
110019
110119
  continue;
110020
110120
  }
110021
110121
  if (nested === name) {
110022
- return [...path61, nested];
110122
+ return [...path63, nested];
110023
110123
  }
110024
- if (path61.includes(nested)) {
110124
+ if (path63.includes(nested)) {
110025
110125
  continue;
110026
110126
  }
110027
- const found = walk2(nested, [...path61, nested]);
110127
+ const found = walk2(nested, [...path63, nested]);
110028
110128
  if (found !== void 0) {
110029
110129
  return found;
110030
110130
  }
@@ -110046,7 +110146,24 @@ function validateMembers(pools, name, members2) {
110046
110146
  throw new UsageError(`Member "pool:${cycle[1] ?? name}" would make pool "${name}" reach itself: ${cycle.join(" -> ")}. A pool cannot nest itself, directly or through another pool.`);
110047
110147
  }
110048
110148
  }
110049
- function addPool(paths, name, identities, preference) {
110149
+ function requireConsistent(name, pool) {
110150
+ const parsed = PoolSchema.safeParse(pool);
110151
+ if (!parsed.success) {
110152
+ throw new UsageError(`Pool "${name}": ${parsed.error.issues.map((issue2) => issue2.message).join("; ")}.`);
110153
+ }
110154
+ }
110155
+ function poolPolicyOf(policy) {
110156
+ return {
110157
+ ...policy.preference === void 0 ? {} : { preference: policy.preference },
110158
+ ...policy.resumeOnLimit === true ? { resumeOnLimit: true } : {},
110159
+ ...policy.compactBeforeLimit === true ? { compactBeforeLimit: true } : {},
110160
+ ...policy.compactAtUtilisation === void 0 ? {} : { compactAtUtilisation: policy.compactAtUtilisation }
110161
+ };
110162
+ }
110163
+ function isPoolChange(change) {
110164
+ return change.identities !== void 0 || change.preference !== void 0 || change.resumeOnLimit !== void 0 || change.compactBeforeLimit !== void 0 || change.compactAtUtilisation !== void 0;
110165
+ }
110166
+ function addPool(paths, name, identities, policy = {}) {
110050
110167
  if (!PoolNameSchema.safeParse(name).success) {
110051
110168
  throw new InvalidPoolNameError(name);
110052
110169
  }
@@ -110055,14 +110172,21 @@ function addPool(paths, name, identities, preference) {
110055
110172
  throw new PoolAlreadyExistsError(name);
110056
110173
  }
110057
110174
  validateMembers(pools, name, identities);
110058
- const pool = { identities: [...identities], ...preference === void 0 ? {} : { preference } };
110175
+ const pool = { identities: [...identities], ...poolPolicyOf(policy) };
110176
+ requireConsistent(name, pool);
110059
110177
  writePools(paths, { ...pools, [name]: pool });
110060
110178
  return pool;
110061
110179
  }
110062
- function setPool(paths, name, identities, preference) {
110063
- requirePool(paths, name);
110180
+ function changePool(paths, name, change) {
110181
+ const existing = requirePool(paths, name);
110182
+ const identities = change.identities ?? existing.identities;
110064
110183
  validateMembers(readPools(paths), name, identities);
110065
- const pool = { identities: [...identities], ...preference === void 0 ? {} : { preference } };
110184
+ const preference = change.preference === void 0 ? existing.preference : change.preference === false ? void 0 : change.preference;
110185
+ const resumeOnLimit = change.resumeOnLimit ?? existing.resumeOnLimit;
110186
+ const compactBeforeLimit = change.compactBeforeLimit ?? existing.compactBeforeLimit;
110187
+ const compactAtUtilisation = change.compactAtUtilisation === void 0 ? existing.compactAtUtilisation : change.compactAtUtilisation === false ? void 0 : change.compactAtUtilisation;
110188
+ const pool = { identities: [...identities], ...poolPolicyOf({ preference, resumeOnLimit, compactBeforeLimit, compactAtUtilisation }) };
110189
+ requireConsistent(name, pool);
110066
110190
  writePools(paths, { ...readPools(paths), [name]: pool });
110067
110191
  return pool;
110068
110192
  }
@@ -110965,6 +111089,9 @@ function cacheChange(options, existing) {
110965
111089
  }
110966
111090
  }
110967
111091
 
111092
+ // src/cli/parsers.ts
111093
+ init_schema();
111094
+
110968
111095
  // src/usage/anchor.ts
110969
111096
  init_schema();
110970
111097
  var MS_PER_SECOND = 1e3;
@@ -111090,6 +111217,15 @@ function collectRepeated(value2, previous = []) {
111090
111217
  function collectAnchor(value2, previous = []) {
111091
111218
  return [...previous, asInvalidArgument(() => parseAnchor(value2))];
111092
111219
  }
111220
+ function parseUtilisationPercent(value2) {
111221
+ return asInvalidArgument(() => {
111222
+ const percent2 = CompactAtUtilisationSchema.safeParse(Number(value2));
111223
+ if (!percent2.success) {
111224
+ throw new Error(`"${value2}" is not a whole percent from 1 to 100`);
111225
+ }
111226
+ return percent2.data;
111227
+ });
111228
+ }
111093
111229
  function parseDurationLiteral(value2) {
111094
111230
  return asInvalidArgument(() => {
111095
111231
  parseDuration(value2);
@@ -113110,17 +113246,17 @@ function parseEntry2(project, entry) {
113110
113246
  const base = match?.[1];
113111
113247
  return base === void 0 ? { project, sessionId: entry, superseded: false, entry } : { project, sessionId: base, superseded: true, entry };
113112
113248
  }
113113
- function listSessions2(fs24, configDir) {
113249
+ function listSessions2(fs25, configDir) {
113114
113250
  const found = [];
113115
- for (const project of fs24.readdir(import_node_path33.default.join(configDir, PROJECTS_DIR))) {
113251
+ for (const project of fs25.readdir(import_node_path33.default.join(configDir, PROJECTS_DIR))) {
113116
113252
  const projectDir = import_node_path33.default.join(configDir, PROJECTS_DIR, project);
113117
113253
  const entries = /* @__PURE__ */ new Set();
113118
- for (const name of fs24.readdir(projectDir)) {
113254
+ for (const name of fs25.readdir(projectDir)) {
113119
113255
  if (name.endsWith(TRANSCRIPT_SUFFIX)) {
113120
113256
  entries.add(name.slice(0, -TRANSCRIPT_SUFFIX.length));
113121
113257
  continue;
113122
113258
  }
113123
- const children = fs24.readdir(import_node_path33.default.join(projectDir, name));
113259
+ const children = fs25.readdir(import_node_path33.default.join(projectDir, name));
113124
113260
  if (children.includes(SUBAGENTS_DIR) || children.includes(WORKFLOWS_DIR)) {
113125
113261
  entries.add(name);
113126
113262
  }
@@ -113131,9 +113267,9 @@ function listSessions2(fs24, configDir) {
113131
113267
  }
113132
113268
  return found.sort((left, right) => left.project.localeCompare(right.project) || left.entry.localeCompare(right.entry));
113133
113269
  }
113134
- function locateAgents(fs24, configDir, relativeDir, workflowRunId, report) {
113270
+ function locateAgents(fs25, configDir, relativeDir, workflowRunId, report) {
113135
113271
  const located = [];
113136
- for (const name of listDirOrReport(fs24, configDir, relativeDir, report)) {
113272
+ for (const name of listDirOrReport(fs25, configDir, relativeDir, report)) {
113137
113273
  if (!name.startsWith(AGENT_FILE_PREFIX) || !name.endsWith(META_SUFFIX)) {
113138
113274
  continue;
113139
113275
  }
@@ -113182,17 +113318,17 @@ function toNode(read, children) {
113182
113318
  function describeFailure(error63) {
113183
113319
  return error63 instanceof Error ? error63.message : String(error63);
113184
113320
  }
113185
- function readFileOrReport(fs24, configDir, relative, report) {
113321
+ function readFileOrReport(fs25, configDir, relative, report) {
113186
113322
  try {
113187
- return fs24.readFileUtf8(import_node_path33.default.join(configDir, relative));
113323
+ return fs25.readFileUtf8(import_node_path33.default.join(configDir, relative));
113188
113324
  } catch (error63) {
113189
113325
  report({ path: relative, reason: `could not be read: ${describeFailure(error63)}` });
113190
113326
  return void 0;
113191
113327
  }
113192
113328
  }
113193
- function listDirOrReport(fs24, configDir, relative, report) {
113329
+ function listDirOrReport(fs25, configDir, relative, report) {
113194
113330
  try {
113195
- return fs24.readdir(import_node_path33.default.join(configDir, relative));
113331
+ return fs25.readdir(import_node_path33.default.join(configDir, relative));
113196
113332
  } catch (error63) {
113197
113333
  report({ path: relative, reason: `could not be listed: ${describeFailure(error63)}` });
113198
113334
  return [];
@@ -113215,22 +113351,22 @@ var WorkflowRunFileSchema = external_exports.object({
113215
113351
  phases: external_exports.array(external_exports.object({ title: external_exports.string() })).default([]),
113216
113352
  summary: external_exports.string().optional()
113217
113353
  });
113218
- function summariseSession(fs24, configDir, ref) {
113354
+ function summariseSession(fs25, configDir, ref) {
113219
113355
  const sessionRelative = import_node_path33.default.join(PROJECTS_DIR, ref.project, ref.entry);
113220
113356
  const subagentsRelative = import_node_path33.default.join(sessionRelative, SUBAGENTS_DIR);
113221
113357
  const workflowsUnderSubagents = import_node_path33.default.join(subagentsRelative, WORKFLOWS_DIR);
113222
113358
  const isMeta = (name) => name.startsWith(AGENT_FILE_PREFIX) && name.endsWith(META_SUFFIX);
113223
- let agentCount = fs24.readdir(import_node_path33.default.join(configDir, subagentsRelative)).filter(isMeta).length;
113224
- for (const runDir of fs24.readdir(import_node_path33.default.join(configDir, workflowsUnderSubagents))) {
113359
+ let agentCount = fs25.readdir(import_node_path33.default.join(configDir, subagentsRelative)).filter(isMeta).length;
113360
+ for (const runDir of fs25.readdir(import_node_path33.default.join(configDir, workflowsUnderSubagents))) {
113225
113361
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
113226
- agentCount += fs24.readdir(import_node_path33.default.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
113362
+ agentCount += fs25.readdir(import_node_path33.default.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
113227
113363
  }
113228
113364
  }
113229
- const workflowRunCount = fs24.readdir(import_node_path33.default.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
113230
- const transcript = fs24.lstat(import_node_path33.default.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
113365
+ const workflowRunCount = fs25.readdir(import_node_path33.default.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
113366
+ const transcript = fs25.lstat(import_node_path33.default.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
113231
113367
  return { ...ref, agentCount, workflowRunCount, ...transcript === void 0 ? {} : { updatedAt: new Date(transcript.mtimeMs).toISOString() } };
113232
113368
  }
113233
- function readSessionAgentTree(fs24, configDir, ref, options = {}) {
113369
+ function readSessionAgentTree(fs25, configDir, ref, options = {}) {
113234
113370
  const problems = [];
113235
113371
  const report = (problem) => {
113236
113372
  problems.push(problem);
@@ -113238,15 +113374,15 @@ function readSessionAgentTree(fs24, configDir, ref, options = {}) {
113238
113374
  const sessionRelative = import_node_path33.default.join(PROJECTS_DIR, ref.project, ref.entry);
113239
113375
  const subagentsRelative = import_node_path33.default.join(sessionRelative, SUBAGENTS_DIR);
113240
113376
  const workflowsUnderSubagents = import_node_path33.default.join(subagentsRelative, WORKFLOWS_DIR);
113241
- const located = locateAgents(fs24, configDir, subagentsRelative, void 0, report);
113242
- for (const runDir of listDirOrReport(fs24, configDir, workflowsUnderSubagents, report)) {
113377
+ const located = locateAgents(fs25, configDir, subagentsRelative, void 0, report);
113378
+ for (const runDir of listDirOrReport(fs25, configDir, workflowsUnderSubagents, report)) {
113243
113379
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
113244
- located.push(...locateAgents(fs24, configDir, import_node_path33.default.join(workflowsUnderSubagents, runDir), runDir, report));
113380
+ located.push(...locateAgents(fs25, configDir, import_node_path33.default.join(workflowsUnderSubagents, runDir), runDir, report));
113245
113381
  }
113246
113382
  }
113247
113383
  const agents = /* @__PURE__ */ new Map();
113248
113384
  for (const candidate of located) {
113249
- const text2 = readFileOrReport(fs24, configDir, candidate.metaPath, report);
113385
+ const text2 = readFileOrReport(fs25, configDir, candidate.metaPath, report);
113250
113386
  if (text2 === void 0) {
113251
113387
  continue;
113252
113388
  }
@@ -113258,7 +113394,7 @@ function readSessionAgentTree(fs24, configDir, ref, options = {}) {
113258
113394
  agents.set(candidate.id, { located: candidate, meta: parsed.data });
113259
113395
  }
113260
113396
  const teamNames = [...new Set([...agents.values()].flatMap((agent) => agent.meta.teamName === void 0 ? [] : [agent.meta.teamName]))].sort();
113261
- const parentOf4 = resolveParents(fs24, configDir, agents, report);
113397
+ const parentOf4 = resolveParents(fs25, configDir, agents, report);
113262
113398
  const childrenOf = /* @__PURE__ */ new Map();
113263
113399
  const roots = [];
113264
113400
  for (const id2 of agents.keys()) {
@@ -113281,12 +113417,12 @@ function readSessionAgentTree(fs24, configDir, ref, options = {}) {
113281
113417
  sessionId: ref.sessionId,
113282
113418
  superseded: ref.superseded,
113283
113419
  agents: roots.sort().map(build),
113284
- tasks: readTasks(fs24, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id2) => !ownTaskLists(ref.sessionId).includes(id2)), report),
113285
- workflowRuns: readWorkflowRuns(fs24, configDir, import_node_path33.default.join(sessionRelative, WORKFLOWS_DIR), report),
113420
+ tasks: readTasks(fs25, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id2) => !ownTaskLists(ref.sessionId).includes(id2)), report),
113421
+ workflowRuns: readWorkflowRuns(fs25, configDir, import_node_path33.default.join(sessionRelative, WORKFLOWS_DIR), report),
113286
113422
  problems
113287
113423
  };
113288
113424
  }
113289
- function resolveParents(fs24, configDir, agents, report) {
113425
+ function resolveParents(fs25, configDir, agents, report) {
113290
113426
  const parentOf4 = /* @__PURE__ */ new Map();
113291
113427
  const transcriptCache = /* @__PURE__ */ new Map();
113292
113428
  const transcriptOf = (agent) => {
@@ -113294,7 +113430,7 @@ function resolveParents(fs24, configDir, agents, report) {
113294
113430
  if (cached2 !== void 0) {
113295
113431
  return cached2;
113296
113432
  }
113297
- const text2 = readFileOrReport(fs24, configDir, agent.located.transcriptPath, report) ?? "";
113433
+ const text2 = readFileOrReport(fs25, configDir, agent.located.transcriptPath, report) ?? "";
113298
113434
  transcriptCache.set(agent.located.id, text2);
113299
113435
  return text2;
113300
113436
  };
@@ -113344,16 +113480,16 @@ function resolveParents(fs24, configDir, agents, report) {
113344
113480
  function ownTaskLists(sessionId) {
113345
113481
  return [sessionId, `${SHORT_SESSION_LIST_PREFIX}${sessionId.slice(0, SHORT_SESSION_ID_LENGTH)}`];
113346
113482
  }
113347
- function readTasks(fs24, configDir, ownLists, sharedLists, report) {
113483
+ function readTasks(fs25, configDir, ownLists, sharedLists, report) {
113348
113484
  const tasks = [];
113349
113485
  [...ownLists, ...sharedLists].forEach((scope, index) => {
113350
113486
  const relativeDir = import_node_path33.default.join(TASKS_DIR, scope);
113351
- for (const name of [...listDirOrReport(fs24, configDir, relativeDir, report)].sort()) {
113487
+ for (const name of [...listDirOrReport(fs25, configDir, relativeDir, report)].sort()) {
113352
113488
  if (name.startsWith(".") || !name.endsWith(JSON_SUFFIX)) {
113353
113489
  continue;
113354
113490
  }
113355
113491
  const relative = import_node_path33.default.join(relativeDir, name);
113356
- const text2 = readFileOrReport(fs24, configDir, relative, report);
113492
+ const text2 = readFileOrReport(fs25, configDir, relative, report);
113357
113493
  const parsed = TaskFileSchema.safeParse(text2 === void 0 ? void 0 : parseJson3(text2));
113358
113494
  if (parsed.success) {
113359
113495
  tasks.push(index < ownLists.length ? parsed.data : { ...parsed.data, taskList: scope });
@@ -113364,14 +113500,14 @@ function readTasks(fs24, configDir, ownLists, sharedLists, report) {
113364
113500
  });
113365
113501
  return tasks;
113366
113502
  }
113367
- function readWorkflowRuns(fs24, configDir, relativeDir, report) {
113503
+ function readWorkflowRuns(fs25, configDir, relativeDir, report) {
113368
113504
  const runs = [];
113369
- for (const name of [...listDirOrReport(fs24, configDir, relativeDir, report)].sort()) {
113505
+ for (const name of [...listDirOrReport(fs25, configDir, relativeDir, report)].sort()) {
113370
113506
  if (!name.startsWith(WORKFLOW_RUN_PREFIX) || !name.endsWith(JSON_SUFFIX)) {
113371
113507
  continue;
113372
113508
  }
113373
113509
  const relative = import_node_path33.default.join(relativeDir, name);
113374
- const text2 = readFileOrReport(fs24, configDir, relative, report);
113510
+ const text2 = readFileOrReport(fs25, configDir, relative, report);
113375
113511
  const parsed = WorkflowRunFileSchema.safeParse(text2 === void 0 ? void 0 : parseJson3(text2));
113376
113512
  if (!parsed.success) {
113377
113513
  if (text2 !== void 0) {
@@ -113395,11 +113531,11 @@ var SessionLookupError = class extends CliError {
113395
113531
  function identityConfigDir(identitiesDir, identity) {
113396
113532
  return import_node_path34.default.join(identitiesDir, identity);
113397
113533
  }
113398
- function historyStores(fs24, identitiesDir, identities) {
113534
+ function historyStores(fs25, identitiesDir, identities) {
113399
113535
  const byRealPath = /* @__PURE__ */ new Map();
113400
113536
  for (const identity of identities) {
113401
113537
  const configDir = identityConfigDir(identitiesDir, identity);
113402
- const real = fs24.realpath(import_node_path34.default.join(configDir, "projects"));
113538
+ const real = fs25.realpath(import_node_path34.default.join(configDir, "projects"));
113403
113539
  if (real === void 0) {
113404
113540
  continue;
113405
113541
  }
@@ -113412,15 +113548,15 @@ function historyStores(fs24, identitiesDir, identities) {
113412
113548
  }
113413
113549
  return [...byRealPath.values()];
113414
113550
  }
113415
- function collectSessionList(fs24, identitiesDir, identities, filters) {
113551
+ function collectSessionList(fs25, identitiesDir, identities, filters) {
113416
113552
  const names = filters.identity === void 0 ? identities : identities.filter((name) => name === filters.identity);
113417
113553
  if (filters.identity !== void 0 && names.length === 0) {
113418
113554
  throw new SessionLookupError(`no identity named "${filters.identity}"`);
113419
113555
  }
113420
113556
  const sessions = [];
113421
- for (const store of historyStores(fs24, identitiesDir, names)) {
113422
- for (const ref of listSessions2(fs24, store.configDir)) {
113423
- const summary = summariseSession(fs24, store.configDir, ref);
113557
+ for (const store of historyStores(fs25, identitiesDir, names)) {
113558
+ for (const ref of listSessions2(fs25, store.configDir)) {
113559
+ const summary = summariseSession(fs25, store.configDir, ref);
113424
113560
  if (filters.all === true || summary.agentCount > 0 || summary.workflowRunCount > 0) {
113425
113561
  sessions.push({ ...summary, identities: store.identities });
113426
113562
  }
@@ -113428,14 +113564,14 @@ function collectSessionList(fs24, identitiesDir, identities, filters) {
113428
113564
  }
113429
113565
  return sessions.sort((left, right) => (right.updatedAt ?? "").localeCompare(left.updatedAt ?? "") || left.sessionId.localeCompare(right.sessionId));
113430
113566
  }
113431
- function locateSession(fs24, identitiesDir, identities, query, onlyIdentity) {
113567
+ function locateSession(fs25, identitiesDir, identities, query, onlyIdentity) {
113432
113568
  const names = onlyIdentity === void 0 ? identities : identities.filter((name) => name === onlyIdentity);
113433
113569
  if (onlyIdentity !== void 0 && names.length === 0) {
113434
113570
  throw new SessionLookupError(`no identity named "${onlyIdentity}"`);
113435
113571
  }
113436
113572
  const matches = [];
113437
- for (const store of historyStores(fs24, identitiesDir, names)) {
113438
- for (const ref of listSessions2(fs24, store.configDir)) {
113573
+ for (const store of historyStores(fs25, identitiesDir, names)) {
113574
+ for (const ref of listSessions2(fs25, store.configDir)) {
113439
113575
  if (ref.sessionId.startsWith(query)) {
113440
113576
  matches.push({ identities: store.identities, configDir: store.configDir, ref });
113441
113577
  }
@@ -113452,9 +113588,9 @@ function locateSession(fs24, identitiesDir, identities, query, onlyIdentity) {
113452
113588
  }
113453
113589
  throw new SessionLookupError(`"${query}" matches ${String(candidates.length)} sessions: ${candidates.map((match) => `${match.ref.sessionId} (${match.identities.join(", ")})`).join("; ")}; give more of the id or pass --identity`);
113454
113590
  }
113455
- function showSession(fs24, identitiesDir, identities, query, onlyIdentity) {
113456
- const located = locateSession(fs24, identitiesDir, identities, query, onlyIdentity);
113457
- return { identities: located.identities, tree: readSessionAgentTree(fs24, located.configDir, located.ref) };
113591
+ function showSession(fs25, identitiesDir, identities, query, onlyIdentity) {
113592
+ const located = locateSession(fs25, identitiesDir, identities, query, onlyIdentity);
113593
+ return { identities: located.identities, tree: readSessionAgentTree(fs25, located.configDir, located.ref) };
113458
113594
  }
113459
113595
 
113460
113596
  // src/frontdoor/commands.ts
@@ -113826,8 +113962,8 @@ var StampsFileSchema = external_exports.strictObject({
113826
113962
  schemaVersion: external_exports.literal(STAMPS_SCHEMA_VERSION),
113827
113963
  handled: external_exports.record(external_exports.string().min(1), external_exports.iso.datetime())
113828
113964
  });
113829
- function readHandled(fs24, file2) {
113830
- const raw = fs24.readFileUtf8(file2);
113965
+ function readHandled(fs25, file2) {
113966
+ const raw = fs25.readFileUtf8(file2);
113831
113967
  if (raw === void 0) {
113832
113968
  return {};
113833
113969
  }
@@ -113840,10 +113976,10 @@ function readHandled(fs24, file2) {
113840
113976
  const result = StampsFileSchema.safeParse(parsed);
113841
113977
  return result.success ? Object.fromEntries(Object.entries(result.data.handled).map(([key, at2]) => [key, Date.parse(at2)])) : {};
113842
113978
  }
113843
- function writeHandled(fs24, file2, handled) {
113979
+ function writeHandled(fs25, file2, handled) {
113844
113980
  const next = { schemaVersion: STAMPS_SCHEMA_VERSION, handled: Object.fromEntries(Object.entries(handled).map(([key, at2]) => [key, new Date(at2).toISOString()])) };
113845
- fs24.mkdirPrivate(import_node_path43.default.dirname(file2));
113846
- fs24.writeFilePrivate(file2, `${JSON.stringify(next, null, 2)}
113981
+ fs25.mkdirPrivate(import_node_path43.default.dirname(file2));
113982
+ fs25.writeFilePrivate(file2, `${JSON.stringify(next, null, 2)}
113847
113983
  `);
113848
113984
  }
113849
113985
 
@@ -114611,9 +114747,9 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
114611
114747
  }
114612
114748
  }
114613
114749
  async function serveFrontDoor(idleShutdownMinutes, ports, options) {
114614
- const { fs: fs24, paths } = ports;
114750
+ const { fs: fs25, paths } = ports;
114615
114751
  const servingBinary = ports.statOwnExecutable();
114616
- const previous = readFrontDoorState(fs24, paths.frontdoorStateFile);
114752
+ const previous = readFrontDoorState(fs25, paths.frontdoorStateFile);
114617
114753
  let lastPort = previous?.lastPort;
114618
114754
  let lastConnectPort = previous?.lastConnectPort;
114619
114755
  let lastDirectPort = previous?.lastDirectPort;
@@ -114624,12 +114760,12 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
114624
114760
  });
114625
114761
  const fail = (message) => {
114626
114762
  ports.closeRcStreamHub();
114627
- writeFrontDoorState(fs24, paths.frontdoorStateFile, { lastError: message, ...sticky() });
114628
- fs24.removeRecursive(paths.frontdoorLockFile);
114763
+ writeFrontDoorState(fs25, paths.frontdoorStateFile, { lastError: message, ...sticky() });
114764
+ fs25.removeRecursive(paths.frontdoorLockFile);
114629
114765
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
114630
114766
  return 1;
114631
114767
  };
114632
- writeFrontDoorState(fs24, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
114768
+ writeFrontDoorState(fs25, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
114633
114769
  const previousSticky = lastPort;
114634
114770
  let http9;
114635
114771
  try {
@@ -114669,16 +114805,16 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
114669
114805
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom admits the new address once its supervisor rewrites the allowlist file)`);
114670
114806
  }
114671
114807
  lastDirectPort = direct.port;
114672
- writeFrontDoorDirectRecord(fs24, paths.frontdoorDirectRecordsDir, { pid: ports.ownPid, directPort: direct.port });
114673
- writeFrontDoorState(fs24, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http9.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
114808
+ writeFrontDoorDirectRecord(fs25, paths.frontdoorDirectRecordsDir, { pid: ports.ownPid, directPort: direct.port });
114809
+ writeFrontDoorState(fs25, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http9.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
114674
114810
  ports.doorHealth.generation({ providerPort: http9.port, connectPort: connect3.port, directPort: direct.port });
114675
- fs24.removeRecursive(paths.frontdoorLockFile);
114811
+ fs25.removeRecursive(paths.frontdoorLockFile);
114676
114812
  ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http9.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
114677
114813
  const watchdog = ports.startWatchdog?.();
114678
114814
  let idleSince;
114679
114815
  let ticks = 0;
114680
114816
  const supersedingOwner = () => {
114681
- const owner = readFrontDoorState(fs24, paths.frontdoorStateFile)?.supervisorPid;
114817
+ const owner = readFrontDoorState(fs25, paths.frontdoorStateFile)?.supervisorPid;
114682
114818
  return owner !== void 0 && owner !== ports.ownPid && ports.isRunning(owner) ? owner : void 0;
114683
114819
  };
114684
114820
  let supersededBy;
@@ -114693,12 +114829,12 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
114693
114829
  await connect3.close();
114694
114830
  await http9.close();
114695
114831
  ports.closeRcStreamHub();
114696
- removeFrontDoorDirectRecord(fs24, paths.frontdoorDirectRecordsDir, ports.ownPid);
114832
+ removeFrontDoorDirectRecord(fs25, paths.frontdoorDirectRecordsDir, ports.ownPid);
114697
114833
  };
114698
114834
  const shutdown = async () => {
114699
114835
  await closeServing();
114700
114836
  if (supersedingOwner() === void 0) {
114701
- writeFrontDoorState(fs24, paths.frontdoorStateFile, sticky());
114837
+ writeFrontDoorState(fs25, paths.frontdoorStateFile, sticky());
114702
114838
  }
114703
114839
  return 0;
114704
114840
  };
@@ -114709,8 +114845,8 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
114709
114845
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
114710
114846
  }
114711
114847
  ticks += 1;
114712
- const listed = listFrontDoorSessions(fs24, paths.frontdoorSessionsDir);
114713
- const pruned = pruneDeadFrontDoorSessions(fs24, paths.frontdoorSessionsDir, ports.isRunning);
114848
+ const listed = listFrontDoorSessions(fs25, paths.frontdoorSessionsDir);
114849
+ const pruned = pruneDeadFrontDoorSessions(fs25, paths.frontdoorSessionsDir, ports.isRunning);
114714
114850
  ports.observeLaunchRegistry(listed, pruned);
114715
114851
  ports.checkQuotaExpiry();
114716
114852
  const prunedPids = new Set(pruned);
@@ -114796,8 +114932,8 @@ function parseConnectTarget(authority) {
114796
114932
  }
114797
114933
  return { host, port };
114798
114934
  }
114799
- function servedByPipeline(path61) {
114800
- return path61?.startsWith(ROUTED_PATH_PREFIX) === true;
114935
+ function servedByPipeline(path63) {
114936
+ return path63?.startsWith(ROUTED_PATH_PREFIX) === true;
114801
114937
  }
114802
114938
  var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
114803
114939
  "connection",
@@ -115482,11 +115618,11 @@ function createRcSessionTracker(deps) {
115482
115618
  };
115483
115619
  const observeExchange = (request7) => {
115484
115620
  const method = (request7.method ?? "").toUpperCase();
115485
- const path61 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
115486
- if (!path61.startsWith(RC_SESSIONS_PATH_PREFIX)) {
115621
+ const path63 = new URL(request7.url ?? "/", "http://127.0.0.1").pathname;
115622
+ if (!path63.startsWith(RC_SESSIONS_PATH_PREFIX)) {
115487
115623
  return void 0;
115488
115624
  }
115489
- const tail = path61.slice(RC_SESSIONS_PATH_PREFIX.length);
115625
+ const tail = path63.slice(RC_SESSIONS_PATH_PREFIX.length);
115490
115626
  const facts = {
115491
115627
  oauthAuthorization: oauthAuthorizationOf(request7.headers),
115492
115628
  anthropicVersion: singleHeader(request7.headers, "anthropic-version"),
@@ -115855,8 +115991,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
115855
115991
  function isRcReadFileEncoding(value2) {
115856
115992
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value2);
115857
115993
  }
115858
- function buildRcReadFilePayload(requestId, path61, options) {
115859
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path61, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
115994
+ function buildRcReadFilePayload(requestId, path63, options) {
115995
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path63, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
115860
115996
  }
115861
115997
  function buildRcFileSuggestionsPayload(requestId, query) {
115862
115998
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -115958,15 +116094,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
115958
116094
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
115959
116095
  return result.ok ? { ...result, requestId } : result;
115960
116096
  }
115961
- async function readRcSessionFile(deps, sessionId, path61, options) {
115962
- if (path61 === "") {
116097
+ async function readRcSessionFile(deps, sessionId, path63, options) {
116098
+ if (path63 === "") {
115963
116099
  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" };
115964
116100
  }
115965
116101
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
115966
116102
  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" };
115967
116103
  }
115968
116104
  const requestId = deps.newUuid();
115969
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path61, options), `read ${path61} from session ${sessionId}`);
116105
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path63, options), `read ${path63} from session ${sessionId}`);
115970
116106
  return result.ok ? { ...result, requestId } : result;
115971
116107
  }
115972
116108
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -116137,11 +116273,11 @@ function createRcControlHandler(deps) {
116137
116273
  path: "read-file",
116138
116274
  read: (body) => {
116139
116275
  const session = bodyString(body, "session");
116140
- const path61 = bodyString(body, "path");
116276
+ const path63 = bodyString(body, "path");
116141
116277
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
116142
116278
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
116143
- const refused2 = session === void 0 || path61 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
116144
- 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, path61, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
116279
+ const refused2 = session === void 0 || path63 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
116280
+ 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, path63, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
116145
116281
  }
116146
116282
  },
116147
116283
  {
@@ -116451,9 +116587,9 @@ function requestIdOfBody(body) {
116451
116587
  }
116452
116588
  function frontDoorRcControl(transport, token) {
116453
116589
  const headers = { authorization: `Bearer ${token}` };
116454
- const listAnswerOf = async (path61, what) => {
116590
+ const listAnswerOf = async (path63, what) => {
116455
116591
  try {
116456
- return await transport.request({ method: "GET", path: path61, headers });
116592
+ return await transport.request({ method: "GET", path: path63, headers });
116457
116593
  } catch (error63) {
116458
116594
  throw new Error(`${what}: could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}`, { cause: error63 });
116459
116595
  }
@@ -116525,10 +116661,10 @@ function frontDoorRcControl(transport, token) {
116525
116661
  }
116526
116662
  return pending;
116527
116663
  };
116528
- const writeOf = async (path61, body, describeFailure2) => {
116664
+ const writeOf = async (path63, body, describeFailure2) => {
116529
116665
  let answer;
116530
116666
  try {
116531
- answer = await transport.request({ method: "POST", path: path61, headers: { ...headers, "content-type": "application/json" }, body });
116667
+ answer = await transport.request({ method: "POST", path: path63, headers: { ...headers, "content-type": "application/json" }, body });
116532
116668
  } catch (error63) {
116533
116669
  return { ok: false, message: `could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}` };
116534
116670
  }
@@ -116559,10 +116695,10 @@ function frontDoorRcControl(transport, token) {
116559
116695
  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}`),
116560
116696
  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}`),
116561
116697
  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}`),
116562
- readFile: async (sessionId, path61, options) => await writeOf(
116698
+ readFile: async (sessionId, path63, options) => await writeOf(
116563
116699
  `${CONTROL_PATH_PREFIX}/read-file`,
116564
- JSON.stringify({ session: sessionId, path: path61, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
116565
- (status, message) => `reading ${path61} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
116700
+ JSON.stringify({ session: sessionId, path: path63, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
116701
+ (status, message) => `reading ${path63} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
116566
116702
  ),
116567
116703
  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}`),
116568
116704
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -116856,12 +116992,12 @@ function tlsFacts(options) {
116856
116992
  }
116857
116993
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
116858
116994
  const agent = new ExemptTlsAgent();
116859
- const post = async (path61, headers, body) => await new Promise((resolve2, reject) => {
116995
+ const post = async (path63, headers, body) => await new Promise((resolve2, reject) => {
116860
116996
  const options = {
116861
116997
  host: target.host,
116862
116998
  port: target.port,
116863
116999
  method: "POST",
116864
- path: path61,
117000
+ path: path63,
116865
117001
  // 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.
116866
117002
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
116867
117003
  agent
@@ -116926,12 +117062,12 @@ function lateRcStreamDial(resolve2) {
116926
117062
  }
116927
117063
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
116928
117064
  const agent = new ExemptTlsAgent();
116929
- const request7 = async (method, path61, headers, body, signal) => await new Promise((resolve2, reject) => {
117065
+ const request7 = async (method, path63, headers, body, signal) => await new Promise((resolve2, reject) => {
116930
117066
  const options = {
116931
117067
  host: target.host,
116932
117068
  port: target.port,
116933
117069
  method,
116934
- path: path61,
117070
+ path: path63,
116935
117071
  // 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.
116936
117072
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
116937
117073
  agent,
@@ -116973,9 +117109,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
116973
117109
  return { status, body: await readAll(response) };
116974
117110
  },
116975
117111
  openStream: async (sessionId, headers, resume, signal) => {
116976
- const path61 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
117112
+ const path63 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
116977
117113
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
116978
- const { status, response } = await request7("GET", path61, streamHeaders, void 0, signal);
117114
+ const { status, response } = await request7("GET", path63, streamHeaders, void 0, signal);
116979
117115
  if (!isSuccessful2(status)) {
116980
117116
  await readAll(response);
116981
117117
  return { status, chunks: NO_CHUNKS };
@@ -117214,12 +117350,12 @@ function decideSignIn(facts) {
117214
117350
  function credentialsFilePath(farmRoot) {
117215
117351
  return import_node_path45.default.join(farmRoot, CREDENTIALS_FILE);
117216
117352
  }
117217
- function identitySignIn(fs24, probe, identity) {
117353
+ function identitySignIn(fs25, probe, identity) {
117218
117354
  const probing = !identity.hasCredentialBlock;
117219
117355
  return decideSignIn({
117220
117356
  hasCredentialBlock: identity.hasCredentialBlock,
117221
117357
  keychainItem: probing && probe.platform === "darwin" && probe.run !== void 0 ? keychainHasItem(probe.run, identity.farmRoot) : void 0,
117222
- credentialsFile: probing && fs24.lstat(credentialsFilePath(identity.farmRoot)) !== void 0,
117358
+ credentialsFile: probing && fs25.lstat(credentialsFilePath(identity.farmRoot)) !== void 0,
117223
117359
  platform: probe.platform
117224
117360
  });
117225
117361
  }
@@ -118280,11 +118416,11 @@ function tryOrUndefined(fn2) {
118280
118416
  return void 0;
118281
118417
  }
118282
118418
  }
118283
- function pathToHttpPath(path61) {
118284
- return `/${path61.map(safeEncodeURIComponent).join("/")}`;
118419
+ function pathToHttpPath(path63) {
118420
+ return `/${path63.map(safeEncodeURIComponent).join("/")}`;
118285
118421
  }
118286
- function normalizeHttpPath(path61) {
118287
- const paths = path61.split("/");
118422
+ function normalizeHttpPath(path63) {
118423
+ const paths = path63.split("/");
118288
118424
  if (paths.at(0) === "") {
118289
118425
  paths.shift();
118290
118426
  }
@@ -118469,9 +118605,9 @@ function isPlainObject2(value2) {
118469
118605
  function getOwn(object3, key) {
118470
118606
  return Object.hasOwn(object3, key) ? object3[key] : void 0;
118471
118607
  }
118472
- function get(object3, path61) {
118608
+ function get(object3, path63) {
118473
118609
  let current = object3;
118474
- for (const key of path61) {
118610
+ for (const key of path63) {
118475
118611
  if (!isTypescriptObject(current)) {
118476
118612
  return void 0;
118477
118613
  }
@@ -119694,7 +119830,7 @@ function resolveClientRest(rest) {
119694
119830
  // rest[1] can be undefined if all fields of FriendlyClientOptions are optional
119695
119831
  ];
119696
119832
  }
119697
- function createORPCClient(link, { path: path61 = [], ...options } = {}) {
119833
+ function createORPCClient(link, { path: path63 = [], ...options } = {}) {
119698
119834
  const procedureClient = (...rest) => {
119699
119835
  const [input2, callOptions] = resolveClientRest(rest);
119700
119836
  const interceptors = [
@@ -119703,7 +119839,7 @@ function createORPCClient(link, { path: path61 = [], ...options } = {}) {
119703
119839
  ];
119704
119840
  return intercept(
119705
119841
  interceptors,
119706
- { ...callOptions, input: input2, path: path61 },
119842
+ { ...callOptions, input: input2, path: path63 },
119707
119843
  ({ path: path210, input: input22, ...callOptions2 }) => link.call(path210, input22, callOptions2)
119708
119844
  );
119709
119845
  };
@@ -119717,7 +119853,7 @@ function createORPCClient(link, { path: path61 = [], ...options } = {}) {
119717
119853
  if (client === void 0) {
119718
119854
  client = createORPCClient(link, {
119719
119855
  ...options,
119720
- path: [...path61, key],
119856
+ path: [...path63, key],
119721
119857
  scoped: options.scoped?.[key]
119722
119858
  });
119723
119859
  cache.set(key, client);
@@ -119739,24 +119875,24 @@ var BracketNotationSerializer = class {
119739
119875
  this.internalSerialize(data, "", true, result);
119740
119876
  return result;
119741
119877
  }
119742
- internalSerialize(data, path61, isRoot, result) {
119878
+ internalSerialize(data, path63, isRoot, result) {
119743
119879
  if (Array.isArray(data)) {
119744
119880
  data.forEach((item, i10) => {
119745
- this.internalSerialize(item, isRoot ? i10.toString() : `${path61}[${i10}]`, false, result);
119881
+ this.internalSerialize(item, isRoot ? i10.toString() : `${path63}[${i10}]`, false, result);
119746
119882
  });
119747
119883
  } else if (isPlainObject2(data)) {
119748
119884
  for (const key of Object.keys(data)) {
119749
- this.internalSerialize(data[key], isRoot ? key : `${path61}[${key}]`, false, result);
119885
+ this.internalSerialize(data[key], isRoot ? key : `${path63}[${key}]`, false, result);
119750
119886
  }
119751
119887
  } else {
119752
- result.push([path61, data]);
119888
+ result.push([path63, data]);
119753
119889
  }
119754
119890
  }
119755
119891
  deserialize(serialized) {
119756
119892
  const arrayPushStyles = /* @__PURE__ */ new WeakSet();
119757
119893
  const root = new NullProtoObj();
119758
- for (const [path61, value2] of serialized) {
119759
- const segments = this.parsePath(path61);
119894
+ for (const [path63, value2] of serialized) {
119895
+ const segments = this.parsePath(path63);
119760
119896
  let currentRef = root;
119761
119897
  let nextSegment = segments[0];
119762
119898
  for (let i10 = 1; i10 < segments.length; i10++) {
@@ -119807,13 +119943,13 @@ var BracketNotationSerializer = class {
119807
119943
  }
119808
119944
  return result;
119809
119945
  }
119810
- parsePath(path61) {
119946
+ parsePath(path63) {
119811
119947
  const segments = [];
119812
119948
  let inBrackets = false;
119813
119949
  let currentSegment = "";
119814
- for (let i10 = 0; i10 < path61.length; i10++) {
119815
- const char = path61[i10];
119816
- const nextChar = path61[i10 + 1];
119950
+ for (let i10 = 0; i10 < path63.length; i10++) {
119951
+ const char = path63[i10];
119952
+ const nextChar = path63[i10 + 1];
119817
119953
  if (inBrackets && char === "]" && (nextChar === void 0 || nextChar === "[")) {
119818
119954
  if (nextChar === void 0) {
119819
119955
  inBrackets = false;
@@ -119829,7 +119965,7 @@ var BracketNotationSerializer = class {
119829
119965
  currentSegment += char;
119830
119966
  }
119831
119967
  }
119832
- return inBrackets || segments.length === 0 ? [path61] : segments;
119968
+ return inBrackets || segments.length === 0 ? [path63] : segments;
119833
119969
  }
119834
119970
  };
119835
119971
  var INTEGER_PATTERN = /^0$|^[1-9]\d*$/;
@@ -120402,11 +120538,11 @@ var OpenAPISerializer = class {
120402
120538
  return json2;
120403
120539
  }
120404
120540
  const form = new FormData();
120405
- for (const [path61, value22] of this.bracketNotation.serialize(json2)) {
120541
+ for (const [path63, value22] of this.bracketNotation.serialize(json2)) {
120406
120542
  if (value22 instanceof Blob) {
120407
- form.append(path61, value22);
120543
+ form.append(path63, value22);
120408
120544
  } else if (value22 !== void 0 && value22 !== null) {
120409
- form.append(path61, String(value22));
120545
+ form.append(path63, String(value22));
120410
120546
  }
120411
120547
  }
120412
120548
  return form;
@@ -120444,30 +120580,30 @@ function isBodylessMethod(method) {
120444
120580
  return method === "GET" || method === "HEAD";
120445
120581
  }
120446
120582
  var PARAMETER_NAME_REGEX = /^[\w-]+$/;
120447
- function getDynamicPathParams(path61) {
120448
- if (!path61.includes("{")) {
120583
+ function getDynamicPathParams(path63) {
120584
+ if (!path63.includes("{")) {
120449
120585
  return void 0;
120450
120586
  }
120451
- const len = path61.length;
120587
+ const len = path63.length;
120452
120588
  let params;
120453
120589
  let index = 1;
120454
120590
  while (index < len) {
120455
120591
  const segmentStart = index;
120456
- const slashPos = path61.indexOf("/", index);
120592
+ const slashPos = path63.indexOf("/", index);
120457
120593
  const segmentEnd = slashPos === -1 ? len : slashPos;
120458
- if (segmentEnd > segmentStart && path61.charCodeAt(segmentStart) === 123 && path61.charCodeAt(segmentEnd - 1) === 125) {
120594
+ if (segmentEnd > segmentStart && path63.charCodeAt(segmentStart) === 123 && path63.charCodeAt(segmentEnd - 1) === 125) {
120459
120595
  let parameterStart = segmentStart + 1;
120460
120596
  let allowsSlash = false;
120461
- const operator = path61.charCodeAt(parameterStart);
120597
+ const operator = path63.charCodeAt(parameterStart);
120462
120598
  if (operator === 43) {
120463
120599
  allowsSlash = true;
120464
120600
  parameterStart++;
120465
120601
  }
120466
- const parameterName = path61.slice(parameterStart, segmentEnd - 1);
120602
+ const parameterName = path63.slice(parameterStart, segmentEnd - 1);
120467
120603
  if (PARAMETER_NAME_REGEX.test(parameterName)) {
120468
120604
  params ??= [];
120469
120605
  params.push({
120470
- segment: path61.slice(segmentStart, segmentEnd),
120606
+ segment: path63.slice(segmentStart, segmentEnd),
120471
120607
  startIndex: segmentStart,
120472
120608
  parameterName,
120473
120609
  allowsSlash
@@ -120510,8 +120646,8 @@ openapi.method = (method) => ({
120510
120646
  ...openapi({ method }),
120511
120647
  name: "~openapi/method"
120512
120648
  });
120513
- openapi.path = (path61) => ({
120514
- ...openapi({ path: path61 }),
120649
+ openapi.path = (path63) => ({
120650
+ ...openapi({ path: path63 }),
120515
120651
  name: "~openapi/path"
120516
120652
  });
120517
120653
  openapi.spec = (spec) => ({
@@ -121372,22 +121508,22 @@ function visitJsonSchemaRefs(value2, visit2, schemaLevel = true, seen = /* @__PU
121372
121508
  }
121373
121509
  }
121374
121510
  }
121375
- function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path61 = []) {
121511
+ function mapJsonSchemaRefs(value2, map2, schemaLevel = true, path63 = []) {
121376
121512
  if (!value2 || typeof value2 !== "object") {
121377
121513
  return value2;
121378
121514
  }
121379
121515
  if (Array.isArray(value2)) {
121380
- return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path61, index]));
121516
+ return value2.map((item, index) => mapJsonSchemaRefs(item, map2, schemaLevel, [...path63, index]));
121381
121517
  }
121382
121518
  const result = {};
121383
121519
  for (const key of Object.keys(value2)) {
121384
121520
  const val = value2[key];
121385
121521
  if (key === "$ref" && typeof val === "string") {
121386
- setOwn(result, key, map2(val, [...path61, key]));
121522
+ setOwn(result, key, map2(val, [...path63, key]));
121387
121523
  } else if (!schemaLevel) {
121388
- setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path61, key]));
121524
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, true, [...path63, key]));
121389
121525
  } else if (JSON_SCHEMA_LOGIC_KEYWORDS.has(key) || JSON_SCHEMA_RECORD_KEYWORDS.has(key)) {
121390
- setOwn(result, key, mapJsonSchemaRefs(val, map2, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path61, key]));
121526
+ setOwn(result, key, mapJsonSchemaRefs(val, map2, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path63, key]));
121391
121527
  } else {
121392
121528
  setOwn(result, key, val);
121393
121529
  }
@@ -121917,7 +122053,7 @@ function unlazy(maybeLazy) {
121917
122053
  function createProcedureClient(lazyableProcedure, ...rest) {
121918
122054
  const options = resolveMaybeOptionalOptions(rest);
121919
122055
  return async (...[input2, callerOptions]) => {
121920
- const path61 = toArray(options.path);
122056
+ const path63 = toArray(options.path);
121921
122057
  const { default: procedure } = await unlazy(lazyableProcedure);
121922
122058
  const clientContext = callerOptions?.context ?? {};
121923
122059
  const context = await value(options.context, clientContext) ?? {};
@@ -121930,7 +122066,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
121930
122066
  };
121931
122067
  try {
121932
122068
  const output2 = await runWithSpan("call_procedure", (span) => {
121933
- span?.setAttribute("procedure.path", path61);
122069
+ span?.setAttribute("procedure.path", path63);
121934
122070
  return intercept(
121935
122071
  options.interceptors,
121936
122072
  {
@@ -121938,7 +122074,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
121938
122074
  // input can be optional if it is undefinable
121939
122075
  input: input2,
121940
122076
  errors,
121941
- path: path61,
122077
+ path: path63,
121942
122078
  procedure,
121943
122079
  signal: callerOptions?.signal,
121944
122080
  lastEventId: callerOptions?.lastEventId
@@ -122189,10 +122325,10 @@ function augmentRouter(router, options) {
122189
122325
  }
122190
122326
  return enhanced;
122191
122327
  }
122192
- function getRouter(router, path61) {
122328
+ function getRouter(router, path63) {
122193
122329
  let current = router;
122194
- for (let i10 = 0; i10 < path61.length; i10++) {
122195
- const segment = path61[i10];
122330
+ for (let i10 = 0; i10 < path63.length; i10++) {
122331
+ const segment = path63[i10];
122196
122332
  if (!isTypescriptObject(current)) {
122197
122333
  return void 0;
122198
122334
  }
@@ -122204,7 +122340,7 @@ function getRouter(router, path61) {
122204
122340
  continue;
122205
122341
  }
122206
122342
  const lazied = current;
122207
- const rest = path61.slice(i10);
122343
+ const rest = path63.slice(i10);
122208
122344
  return new Lazy({
122209
122345
  ...lazied["~orpc"],
122210
122346
  async loader() {
@@ -122219,40 +122355,40 @@ function getRouter(router, path61) {
122219
122355
  }
122220
122356
  return current;
122221
122357
  }
122222
- function walkProcedureContractsSync(router, callback, path61 = []) {
122358
+ function walkProcedureContractsSync(router, callback, path63 = []) {
122223
122359
  const lazyResults = [];
122224
- walkProcedureContractsSyncInternal(router, callback, path61.slice(), lazyResults);
122360
+ walkProcedureContractsSyncInternal(router, callback, path63.slice(), lazyResults);
122225
122361
  return lazyResults;
122226
122362
  }
122227
- function walkProcedureContractsSyncInternal(router, callback, path61, lazyResults) {
122363
+ function walkProcedureContractsSyncInternal(router, callback, path63, lazyResults) {
122228
122364
  const hiddenContract = getHiddenRouterContract(router);
122229
122365
  if (hiddenContract !== void 0) {
122230
122366
  router = hiddenContract;
122231
122367
  }
122232
122368
  if (router instanceof ProcedureContract) {
122233
- callback(router, path61.slice());
122369
+ callback(router, path63.slice());
122234
122370
  return;
122235
122371
  }
122236
122372
  if (!isTypescriptObject(router)) {
122237
122373
  return;
122238
122374
  }
122239
122375
  for (const [key, value2] of Object.entries(router)) {
122240
- path61.push(key);
122376
+ path63.push(key);
122241
122377
  if (value2 instanceof Lazy) {
122242
- lazyResults.push({ router: value2, path: path61.slice() });
122378
+ lazyResults.push({ router: value2, path: path63.slice() });
122243
122379
  } else {
122244
- walkProcedureContractsSyncInternal(value2, callback, path61, lazyResults);
122380
+ walkProcedureContractsSyncInternal(value2, callback, path63, lazyResults);
122245
122381
  }
122246
- path61.pop();
122382
+ path63.pop();
122247
122383
  }
122248
122384
  }
122249
- async function walkProcedureContractsAsync(router, callback, path61 = []) {
122385
+ async function walkProcedureContractsAsync(router, callback, path63 = []) {
122250
122386
  const hiddenContract = getHiddenRouterContract(router);
122251
122387
  if (hiddenContract !== void 0) {
122252
122388
  router = hiddenContract;
122253
122389
  }
122254
122390
  if (router instanceof ProcedureContract) {
122255
- await callback(router, path61);
122391
+ await callback(router, path63);
122256
122392
  return;
122257
122393
  }
122258
122394
  if (!isTypescriptObject(router)) {
@@ -122261,9 +122397,9 @@ async function walkProcedureContractsAsync(router, callback, path61 = []) {
122261
122397
  for (const [key, value2] of Object.entries(router)) {
122262
122398
  if (value2 instanceof Lazy) {
122263
122399
  const { default: router2 } = await unlazy(value2);
122264
- await walkProcedureContractsAsync(router2, callback, [...path61, key]);
122400
+ await walkProcedureContractsAsync(router2, callback, [...path63, key]);
122265
122401
  } else {
122266
- await walkProcedureContractsAsync(value2, callback, [...path61, key]);
122402
+ await walkProcedureContractsAsync(value2, callback, [...path63, key]);
122267
122403
  }
122268
122404
  }
122269
122405
  }
@@ -122749,18 +122885,18 @@ function rewriteComponentSchemaRefs(schema, renameMap) {
122749
122885
  }
122750
122886
  var OpenAPIGeneratorError = class extends TypeError {
122751
122887
  };
122752
- function toOpenAPIPath(path61, dynamicPathParams) {
122888
+ function toOpenAPIPath(path63, dynamicPathParams) {
122753
122889
  if (!dynamicPathParams?.length) {
122754
- return path61;
122890
+ return path63;
122755
122891
  }
122756
122892
  let normalized = "";
122757
122893
  let currentIndex = 0;
122758
122894
  for (const param of dynamicPathParams) {
122759
- normalized += path61.slice(currentIndex, param.startIndex);
122895
+ normalized += path63.slice(currentIndex, param.startIndex);
122760
122896
  normalized += `{${param.parameterName}}`;
122761
122897
  currentIndex = param.startIndex + param.segment.length;
122762
122898
  }
122763
- normalized += path61.slice(currentIndex);
122899
+ normalized += path63.slice(currentIndex);
122764
122900
  return normalized;
122765
122901
  }
122766
122902
  function buildRequest(ctx, operation, def, meta3, dynamicPathParams) {
@@ -123194,8 +123330,8 @@ var OpenAPIGenerator = class {
123194
123330
  customErrorResponseBodySchema: options.customErrorResponseBodySchema
123195
123331
  };
123196
123332
  const errors = [];
123197
- await walkProcedureContractsAsync(router, (contract, path61) => {
123198
- if (value(options.filter, contract, path61) === false) {
123333
+ await walkProcedureContractsAsync(router, (contract, path63) => {
123334
+ if (value(options.filter, contract, path63) === false) {
123199
123335
  return;
123200
123336
  }
123201
123337
  try {
@@ -123207,7 +123343,7 @@ var OpenAPIGenerator = class {
123207
123343
  `QUERY operations require OpenAPI 3.2, but version "${version2}" was requested.`
123208
123344
  );
123209
123345
  }
123210
- const postPath = meta3?.path ?? pathToHttpPath(path61);
123346
+ const postPath = meta3?.path ?? pathToHttpPath(path63);
123211
123347
  const httpPath = meta3?.prefix ? mergeHttpPath(meta3.prefix, postPath) : postPath;
123212
123348
  const dynamicPathParams = getDynamicPathParams(httpPath);
123213
123349
  const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
@@ -123216,7 +123352,7 @@ var OpenAPIGenerator = class {
123216
123352
  operation = meta3.spec;
123217
123353
  } else {
123218
123354
  operation = {
123219
- operationId: meta3?.operationId ?? path61.join("."),
123355
+ operationId: meta3?.operationId ?? path63.join("."),
123220
123356
  summary: meta3?.summary,
123221
123357
  description: meta3?.description,
123222
123358
  deprecated: meta3?.deprecated,
@@ -123236,7 +123372,7 @@ var OpenAPIGenerator = class {
123236
123372
  if (!(e14 instanceof OpenAPIGeneratorError)) {
123237
123373
  throw e14;
123238
123374
  }
123239
- errors.push(`Procedure at ${path61.join(".") || "(root)"}: ${e14.message}`);
123375
+ errors.push(`Procedure at ${path63.join(".") || "(root)"}: ${e14.message}`);
123240
123376
  }
123241
123377
  });
123242
123378
  if (errors.length) {
@@ -124081,16 +124217,16 @@ var StandardLink = class {
124081
124217
  /**
124082
124218
  * @throws ORPCError, transport-level errors (network failures, timeouts, etc.)
124083
124219
  */
124084
- call(path61, input2, options) {
124085
- return runWithSpan(`${ORPC_NAME}.${path61.join("/")}`, (span) => {
124220
+ call(path63, input2, options) {
124221
+ return runWithSpan(`${ORPC_NAME}.${path63.join("/")}`, (span) => {
124086
124222
  span?.setAttribute("rpc.system", ORPC_NAME);
124087
- span?.setAttribute("rpc.method", path61.join("."));
124223
+ span?.setAttribute("rpc.method", path63.join("."));
124088
124224
  if (getTracer() && isAsyncIteratorObject(input2)) {
124089
124225
  input2 = override(input2, traceAsyncIterator("consume_async_iterator_object_input", input2));
124090
124226
  } else if (getTracer() && input2 instanceof ReadableStream) {
124091
124227
  input2 = override(input2, traceReadableStream("consume_octet_stream_input", input2));
124092
124228
  }
124093
- return intercept(this.interceptors, { ...options, path: path61, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
124229
+ return intercept(this.interceptors, { ...options, path: path63, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
124094
124230
  const tracer = getTracer();
124095
124231
  const activeSpan = tracer?.getActiveSpan() ?? span;
124096
124232
  let request7 = await runWithSpan(
@@ -124147,18 +124283,18 @@ var RPCLinkCodec = class {
124147
124283
  this.headers = options.headers ?? {};
124148
124284
  this.serializer = options.serializer ?? new RPCSerializer();
124149
124285
  }
124150
- async encodeInput(input2, path61, options) {
124151
- let headers = toResolvedStandardHeaders(await value(this.headers, options, path61, input2));
124286
+ async encodeInput(input2, path63, options) {
124287
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path63, input2));
124152
124288
  if (options.lastEventId !== void 0) {
124153
124289
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
124154
124290
  }
124155
- const expectedMethod = await value(this.expectedMethod, options, path61, input2);
124156
- const baseUrl = await value(this.baseUrl, options, path61, input2);
124291
+ const expectedMethod = await value(this.expectedMethod, options, path63, input2);
124292
+ const baseUrl = await value(this.baseUrl, options, path63, input2);
124157
124293
  const [pathname, search, hash2] = parseStandardUrl(baseUrl);
124158
- const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path61)}`;
124294
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path63)}`;
124159
124295
  const serialized = this.serializer.serialize(input2);
124160
124296
  if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
124161
- const maxUrlLength = await value(this.maxUrlLength, options, path61, input2);
124297
+ const maxUrlLength = await value(this.maxUrlLength, options, path63, input2);
124162
124298
  const mergedSearch = new URLSearchParams(search);
124163
124299
  mergedSearch.append("data", stringifyJSON(serialized) ?? "");
124164
124300
  const url22 = `${newPathname}?${mergedSearch}${hash2 ?? ""}`;
@@ -124243,8 +124379,8 @@ var FetchLinkTransport = class {
124243
124379
  this.fetch = options.fetch ?? ((url2, init) => globalThis.fetch(url2, init));
124244
124380
  this.toFetchRequestOptions = options.toFetchRequest;
124245
124381
  }
124246
- async send(standardRequest, path61, options) {
124247
- let origin = await value(this.origin, options, path61);
124382
+ async send(standardRequest, path63, options) {
124383
+ let origin = await value(this.origin, options, path63);
124248
124384
  if (origin?.endsWith("/")) {
124249
124385
  origin = origin.slice(0, -1);
124250
124386
  }
@@ -124264,7 +124400,7 @@ var FetchLinkTransport = class {
124264
124400
  }
124265
124401
  }
124266
124402
  const fetch3 = this.fetch;
124267
- const response = await fetch3(url2, init, options, path61);
124403
+ const response = await fetch3(url2, init, options, path63);
124268
124404
  const standardResponse = toStandardLazyResponse(response);
124269
124405
  return standardResponse;
124270
124406
  }
@@ -124655,14 +124791,14 @@ var StandardHandler = class {
124655
124791
  span?.setAttribute("url.path", request22.url);
124656
124792
  return { matched: false };
124657
124793
  }
124658
- const { path: path61, procedure, decodeInput } = matchedOrNot;
124659
- span?.updateName(`${ORPC_NAME}.${path61.join("/")}`);
124794
+ const { path: path63, procedure, decodeInput } = matchedOrNot;
124795
+ span?.updateName(`${ORPC_NAME}.${path63.join("/")}`);
124660
124796
  span?.setAttribute("rpc.system", ORPC_NAME);
124661
- span?.setAttribute("rpc.method", path61.join("."));
124797
+ span?.setAttribute("rpc.method", path63.join("."));
124662
124798
  try {
124663
124799
  const response = await intercept(
124664
124800
  this.interceptors,
124665
- { context: context2, prefix: prefix2, request: request22, path: path61, procedure, decodeInput },
124801
+ { context: context2, prefix: prefix2, request: request22, path: path63, procedure, decodeInput },
124666
124802
  async ({ context: context3, prefix: prefix3, request: request32, path: path210, procedure: procedure2, decodeInput: decodeInput2 }) => {
124667
124803
  step2 = "decode_input";
124668
124804
  let input2 = await runWithSpan("decode_input", decodeInput2);
@@ -124696,7 +124832,7 @@ var StandardHandler = class {
124696
124832
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
124697
124833
  cause: e14
124698
124834
  }) : toORPCError(e14);
124699
- const response = await this.codec.encodeError(error63, procedure, path61, { context: context2, prefix: prefix2 });
124835
+ const response = await this.codec.encodeError(error63, procedure, path63, { context: context2, prefix: prefix2 });
124700
124836
  return { matched: true, response };
124701
124837
  }
124702
124838
  }
@@ -124802,7 +124938,7 @@ var RPCMatcher = class {
124802
124938
  this.rootRouter = router;
124803
124939
  this.index(router);
124804
124940
  }
124805
- index(router, path61 = []) {
124941
+ index(router, path63 = []) {
124806
124942
  const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
124807
124943
  if (!value(this.filter, procedure, procedurePath)) {
124808
124944
  return;
@@ -124813,7 +124949,7 @@ var RPCMatcher = class {
124813
124949
  // contract-first entries have no implementation yet, resolveProcedure fills it in on demand
124814
124950
  procedure: procedure instanceof Procedure ? procedure : void 0
124815
124951
  });
124816
- }, path61);
124952
+ }, path63);
124817
124953
  for (const result of lazyResults) {
124818
124954
  this.pendingLazyRouters.set(pathToHttpPath(result.path), result);
124819
124955
  }
@@ -124945,10 +125081,10 @@ var RPCHandlerCodec = class {
124945
125081
  }
124946
125082
  };
124947
125083
  }
124948
- encodeOutput(output2, procedure, path61, options) {
125084
+ encodeOutput(output2, procedure, path63, options) {
124949
125085
  return {
124950
125086
  headers: {},
124951
- status: value(this.outputStatus, output2, procedure, path61, options) ?? DEFAULT_SUCCESS_STATUS,
125087
+ status: value(this.outputStatus, output2, procedure, path63, options) ?? DEFAULT_SUCCESS_STATUS,
124952
125088
  body: this.serializer.serialize(output2)
124953
125089
  };
124954
125090
  }
@@ -125002,39 +125138,39 @@ function createRouter() {
125002
125138
  static: new NullProtoObj2()
125003
125139
  };
125004
125140
  }
125005
- function scanFirstGroup(path61) {
125141
+ function scanFirstGroup(path63) {
125006
125142
  let i10 = 0;
125007
125143
  let depth = 0;
125008
- for (; i10 < path61.length; i10++) {
125009
- const c10 = path61.charCodeAt(i10);
125144
+ for (; i10 < path63.length; i10++) {
125145
+ const c10 = path63.charCodeAt(i10);
125010
125146
  if (c10 === 92) i10++;
125011
125147
  else if (c10 === 40) depth++;
125012
125148
  else if (c10 === 41 && depth > 0) depth--;
125013
125149
  else if (c10 === 123 && depth === 0) break;
125014
125150
  }
125015
- if (i10 >= path61.length) return;
125151
+ if (i10 >= path63.length) return;
125016
125152
  let j10 = i10 + 1;
125017
125153
  depth = 0;
125018
- for (; j10 < path61.length; j10++) {
125019
- const c10 = path61.charCodeAt(j10);
125154
+ for (; j10 < path63.length; j10++) {
125155
+ const c10 = path63.charCodeAt(j10);
125020
125156
  if (c10 === 92) j10++;
125021
125157
  else if (c10 === 40) depth++;
125022
125158
  else if (c10 === 41 && depth > 0) depth--;
125023
125159
  else if (c10 === 125 && depth === 0) break;
125024
125160
  }
125025
- if (j10 >= path61.length) return;
125026
- const mod = path61[j10 + 1];
125161
+ if (j10 >= path63.length) return;
125162
+ const mod = path63[j10 + 1];
125027
125163
  const hasMod = mod === "?" || mod === "+" || mod === "*";
125028
125164
  return [
125029
- path61.slice(0, i10),
125030
- path61.slice(i10 + 1, j10),
125031
- path61.slice(j10 + (hasMod ? 2 : 1)),
125165
+ path63.slice(0, i10),
125166
+ path63.slice(i10 + 1, j10),
125167
+ path63.slice(j10 + (hasMod ? 2 : 1)),
125032
125168
  hasMod ? mod : void 0
125033
125169
  ];
125034
125170
  }
125035
- function expandGroupDelimiters(path61) {
125036
- if (!path61.includes("{")) return;
125037
- const group = scanFirstGroup(path61);
125171
+ function expandGroupDelimiters(path63) {
125172
+ if (!path63.includes("{")) return;
125173
+ const group = scanFirstGroup(path63);
125038
125174
  if (!group) return;
125039
125175
  const [pre2, body, suf, mod] = group;
125040
125176
  if (!mod) return [pre2 + body + suf];
@@ -125104,9 +125240,9 @@ function replaceSegmentWildcards(segment, unnamedStart, toGroupKey = toUnnamedGr
125104
125240
  }
125105
125241
  return [replaced, nextIndex];
125106
125242
  }
125107
- function encodeEscapes(path61) {
125108
- if (!path61.includes("\\")) return path61;
125109
- return path61.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
125243
+ function encodeEscapes(path63) {
125244
+ if (!path63.includes("\\")) return path63;
125245
+ return path63.replace(/\\([:(){}])/g, (_, c10) => "\uFFFD" + "ABCDE"[":(){}".indexOf(c10)]);
125110
125246
  }
125111
125247
  function segmentKey(segment) {
125112
125248
  if (segment.startsWith("**")) return 2;
@@ -125135,22 +125271,22 @@ function expandModifiers(segments) {
125135
125271
  return m10[2] === "+" ? [wc2] : [wc2, without];
125136
125272
  }
125137
125273
  }
125138
- function normalizePath(path61) {
125139
- if (!path61.includes("/.")) return path61;
125274
+ function normalizePath(path63) {
125275
+ if (!path63.includes("/.")) return path63;
125140
125276
  const r10 = [];
125141
- for (const s of path61.split("/")) if (s === ".") continue;
125277
+ for (const s of path63.split("/")) if (s === ".") continue;
125142
125278
  else if (s === ".." && r10.length > 1) r10.pop();
125143
125279
  else r10.push(s);
125144
125280
  return r10.join("/") || "/";
125145
125281
  }
125146
- function splitPath(path61) {
125147
- const s = path61.split("/");
125282
+ function splitPath(path63) {
125283
+ const s = path63.split("/");
125148
125284
  s.shift();
125149
125285
  if (s[s.length - 1] === "") s.pop();
125150
125286
  return s;
125151
125287
  }
125152
- function splitRoute(path61) {
125153
- const s = splitPath(path61);
125288
+ function splitRoute(path63) {
125289
+ const s = splitPath(path63);
125154
125290
  while (s[s.length - 1] === "") s.pop();
125155
125291
  return s;
125156
125292
  }
@@ -125166,16 +125302,16 @@ function getMatchParams(segments, paramsMap) {
125166
125302
  }
125167
125303
  return params;
125168
125304
  }
125169
- function addRoute(ctx, method = "", path61, data) {
125305
+ function addRoute(ctx, method = "", path63, data) {
125170
125306
  method = method.toUpperCase();
125171
- if (path61.charCodeAt(0) !== 47) path61 = `/${path61}`;
125172
- const groupExpanded = expandGroupDelimiters(path61);
125307
+ if (path63.charCodeAt(0) !== 47) path63 = `/${path63}`;
125308
+ const groupExpanded = expandGroupDelimiters(path63);
125173
125309
  if (groupExpanded) {
125174
125310
  for (const expandedPath of groupExpanded) addRoute(ctx, method, expandedPath, data);
125175
125311
  return;
125176
125312
  }
125177
- path61 = encodeEscapes(path61);
125178
- const segments = splitRoute(path61);
125313
+ path63 = encodeEscapes(path63);
125314
+ const segments = splitRoute(path63);
125179
125315
  const expanded = expandModifiers(segments);
125180
125316
  if (expanded) {
125181
125317
  for (const p of expanded) addRoute(ctx, method, p, data);
@@ -125266,15 +125402,15 @@ function getParamRegexp(segment, unnamedStart = 0) {
125266
125402
  const regex = _s2.replace(/:([\w-]+)(?:\(([^)]*)\))?/g, (_, id2, p) => `(?<${toGroupName(id2)}>${p || "[^/]+"})`).replace(/\((?![?<])/g, () => `(?<${toUnnamedGroupKey(_i2++)}>`).replace(/\uFFFE(.)/g, (_, c10) => /[.*+?^${}()|[\]\\]/.test(c10) ? `\\${c10}` : c10);
125267
125403
  return [new RegExp(`^${regex}$`), _i2];
125268
125404
  }
125269
- function findRoute(ctx, method = "", path61, opts) {
125270
- if (opts?.normalize) path61 = normalizePath(path61);
125271
- if (path61.charCodeAt(path61.length - 1) === 47) path61 = path61.slice(0, -1);
125272
- const staticNode = ctx.static[path61];
125405
+ function findRoute(ctx, method = "", path63, opts) {
125406
+ if (opts?.normalize) path63 = normalizePath(path63);
125407
+ if (path63.charCodeAt(path63.length - 1) === 47) path63 = path63.slice(0, -1);
125408
+ const staticNode = ctx.static[path63];
125273
125409
  if (staticNode && staticNode.methods) {
125274
125410
  const staticMatch = staticNode.methods[method] || staticNode.methods[""];
125275
125411
  if (staticMatch !== void 0) return staticMatch[0];
125276
125412
  }
125277
- const segments = splitPath(path61);
125413
+ const segments = splitPath(path63);
125278
125414
  const match = _lookupTree(ctx.root, method, segments, 0);
125279
125415
  if (match === void 0) return;
125280
125416
  if (opts?.params === false) return match;
@@ -125474,7 +125610,7 @@ var OpenAPIMatcher = class {
125474
125610
  this.rootRouter = router;
125475
125611
  this.index(router);
125476
125612
  }
125477
- index(router, path61 = []) {
125613
+ index(router, path63 = []) {
125478
125614
  const lazyResults = walkProcedureContractsSync(router, (contract, path210) => {
125479
125615
  if (!value(this.filter, contract, path210)) {
125480
125616
  return;
@@ -125489,7 +125625,7 @@ var OpenAPIMatcher = class {
125489
125625
  contract,
125490
125626
  procedure: contract instanceof Procedure ? contract : void 0
125491
125627
  });
125492
- }, path61);
125628
+ }, path63);
125493
125629
  for (const result of lazyResults) {
125494
125630
  const prefix = getOpenAPIMeta(result.router)?.prefix;
125495
125631
  this.pendingLazyRouters.add({
@@ -125576,20 +125712,20 @@ var OpenAPIMatcher = class {
125576
125712
  return entry.procedure;
125577
125713
  }
125578
125714
  };
125579
- function toRou3Pattern(path61) {
125580
- const params = getDynamicPathParams(path61);
125715
+ function toRou3Pattern(path63) {
125716
+ const params = getDynamicPathParams(path63);
125581
125717
  if (!params?.length) {
125582
- return path61;
125718
+ return path63;
125583
125719
  }
125584
125720
  for (let i10 = params.length - 1; i10 >= 0; i10--) {
125585
125721
  const param = params[i10];
125586
125722
  const pattern = param.allowsSlash ? `**:${param.parameterName}` : `:${param.parameterName}`;
125587
- path61 = path61.slice(0, param.startIndex) + pattern + path61.slice(param.startIndex + param.segment.length);
125723
+ path63 = path63.slice(0, param.startIndex) + pattern + path63.slice(param.startIndex + param.segment.length);
125588
125724
  }
125589
- return path61;
125725
+ return path63;
125590
125726
  }
125591
- function toRou3PrefixMatcher(path61) {
125592
- const pattern = toRou3Pattern(path61);
125727
+ function toRou3PrefixMatcher(path63) {
125728
+ const pattern = toRou3Pattern(path63);
125593
125729
  return routeToRegExp(pattern === "/" ? "/**" : `${pattern}/**`);
125594
125730
  }
125595
125731
  function decodeParams(params) {
@@ -125668,7 +125804,7 @@ var OpenAPIHandlerCodecCore = class {
125668
125804
  /**
125669
125805
  * @throws {TypeError} If `outputStructure` is "detailed" and the output doesn't match the expected structure.
125670
125806
  */
125671
- encodeOutput(output2, procedure, path61) {
125807
+ encodeOutput(output2, procedure, path63) {
125672
125808
  const meta3 = getOpenAPIMeta(procedure);
125673
125809
  const successStatus = meta3?.successStatus ?? DEFAULT_SUCCESS_STATUS;
125674
125810
  const outputStructure = meta3?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
@@ -125681,7 +125817,7 @@ var OpenAPIHandlerCodecCore = class {
125681
125817
  }
125682
125818
  if (!isValidDetailedOutput(output2)) {
125683
125819
  throw new TypeError(`
125684
- Invalid "detailed" output structure returned by procedure (${path61.join(".")}):
125820
+ Invalid "detailed" output structure returned by procedure (${path63.join(".")}):
125685
125821
  \u2022 Expected an object with optional properties:
125686
125822
  - status (number <400)
125687
125823
  - headers (object)
@@ -126126,13 +126262,19 @@ var PoolMembersInputSchema = external_exports.array(external_exports.string().mi
126126
126262
  var ConfigPoolAddInputSchema = external_exports.strictObject({
126127
126263
  name: external_exports.string().min(1),
126128
126264
  identities: PoolMembersInputSchema,
126129
- preference: external_exports.enum(POOL_PREFERENCES).optional()
126265
+ preference: external_exports.enum(POOL_PREFERENCES).optional(),
126266
+ resumeOnLimit: external_exports.boolean().optional(),
126267
+ compactBeforeLimit: external_exports.boolean().optional(),
126268
+ compactAtUtilisation: CompactAtUtilisationSchema.optional()
126130
126269
  });
126131
126270
  var ConfigPoolAddOutputSchema = storedMutationOutput("pool", "created", PoolSchema);
126132
126271
  var ConfigPoolSetInputSchema = external_exports.strictObject({
126133
126272
  name: external_exports.string().min(1),
126134
126273
  identities: PoolMembersInputSchema.optional(),
126135
- preference: external_exports.union([external_exports.enum(POOL_PREFERENCES), external_exports.literal(false)]).optional()
126274
+ preference: external_exports.union([external_exports.enum(POOL_PREFERENCES), external_exports.literal(false)]).optional(),
126275
+ resumeOnLimit: external_exports.boolean().optional(),
126276
+ compactBeforeLimit: external_exports.boolean().optional(),
126277
+ compactAtUtilisation: external_exports.union([CompactAtUtilisationSchema, external_exports.literal(false)]).optional()
126136
126278
  });
126137
126279
  var ConfigPoolSetOutputSchema = storedMutationOutput("pool", "updated", PoolSchema);
126138
126280
  var ConfigPoolRemoveInputSchema = external_exports.strictObject({ name: external_exports.string().min(1), confirm: RemovalConfirmationSchema });
@@ -126234,7 +126376,7 @@ function profileValue(name, paths) {
126234
126376
  function createConfigApiRouter(deps) {
126235
126377
  const authed = doorApiAuth(deps.expectedToken);
126236
126378
  const { paths } = deps;
126237
- const route = (path61, summary) => authed.meta(openapi({ method: "POST", path: path61, summary, tags: [CONFIG_API_TAG] }));
126379
+ const route = (path63, summary) => authed.meta(openapi({ method: "POST", path: path63, summary, tags: [CONFIG_API_TAG] }));
126238
126380
  return {
126239
126381
  config: {
126240
126382
  identity: {
@@ -126343,20 +126485,19 @@ function createConfigApiRouter(deps) {
126343
126485
  add: route("/rest/config/pool/add", "Define a pool").input(ConfigPoolAddInputSchema).output(ConfigPoolAddOutputSchema).handler(
126344
126486
  ({ input: input2 }) => guarded(() => {
126345
126487
  requireIdentityNames(paths, input2.identities);
126346
- const created = addPool(paths, input2.name, input2.identities, input2.preference);
126488
+ const created = addPool(paths, input2.name, input2.identities, { preference: input2.preference, resumeOnLimit: input2.resumeOnLimit, compactBeforeLimit: input2.compactBeforeLimit, compactAtUtilisation: input2.compactAtUtilisation });
126347
126489
  return { action: "created", kind: "pool", name: input2.name, value: created };
126348
126490
  })
126349
126491
  ),
126350
- set: route("/rest/config/pool/set", "Replace a pool's members, its preference or both").input(ConfigPoolSetInputSchema).output(ConfigPoolSetOutputSchema).handler(
126492
+ set: route("/rest/config/pool/set", "Replace a pool's members, change its preference or whether it resumes on a spent quota").input(ConfigPoolSetInputSchema).output(ConfigPoolSetOutputSchema).handler(
126351
126493
  ({ input: input2 }) => guarded(() => {
126352
- requireChange(input2.identities !== void 0 || input2.preference !== void 0, "identities or preference");
126353
- const existing = requirePool(paths, input2.name);
126494
+ const change = { identities: input2.identities, preference: input2.preference, resumeOnLimit: input2.resumeOnLimit, compactBeforeLimit: input2.compactBeforeLimit, compactAtUtilisation: input2.compactAtUtilisation };
126495
+ requireChange(isPoolChange(change), "identities, preference, resumeOnLimit, compactBeforeLimit or compactAtUtilisation");
126496
+ requirePool(paths, input2.name);
126354
126497
  if (input2.identities !== void 0) {
126355
126498
  requireIdentityNames(paths, input2.identities);
126356
126499
  }
126357
- const members2 = input2.identities ?? existing.identities;
126358
- const preference = input2.preference === void 0 ? existing.preference : input2.preference === false ? void 0 : input2.preference;
126359
- return { action: "updated", kind: "pool", name: input2.name, value: setPool(paths, input2.name, members2, preference) };
126500
+ return { action: "updated", kind: "pool", name: input2.name, value: changePool(paths, input2.name, change) };
126360
126501
  })
126361
126502
  ),
126362
126503
  remove: route("/rest/config/pool/remove", "Delete a pool").input(ConfigPoolRemoveInputSchema).output(ConfigPoolRemoveOutputSchema).handler(({ input: input2 }) => {
@@ -129015,8 +129156,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
129015
129156
  request7.body.resume();
129016
129157
  return;
129017
129158
  }
129018
- const path61 = new URL(request7.url, "http://127.0.0.1").pathname;
129019
- const translated = { method: request7.method, path: path61, body, signal: request7.signal };
129159
+ const path63 = new URL(request7.url, "http://127.0.0.1").pathname;
129160
+ const translated = { method: request7.method, path: path63, body, signal: request7.signal };
129020
129161
  const routed = await route(translated);
129021
129162
  if (request7.signal.aborted) {
129022
129163
  return;
@@ -129630,8 +129771,8 @@ function createAntigravityRouteMount(ports, upstreamBase, provider) {
129630
129771
  request7.body.resume();
129631
129772
  return;
129632
129773
  }
129633
- const path61 = new URL(request7.url, "http://127.0.0.1").pathname;
129634
- const translated = { method: request7.method, path: path61, body, signal: request7.signal };
129774
+ const path63 = new URL(request7.url, "http://127.0.0.1").pathname;
129775
+ const translated = { method: request7.method, path: path63, body, signal: request7.signal };
129635
129776
  const routed = await route(translated);
129636
129777
  if (request7.signal.aborted) {
129637
129778
  return;
@@ -129665,7 +129806,7 @@ function createPassthroughRoute(name, target) {
129665
129806
  headroomUpstream: target.headroomUpstream,
129666
129807
  serve: async (request7, response) => {
129667
129808
  const incoming = new URL(request7.url, "http://127.0.0.1");
129668
- const path61 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
129809
+ const path63 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
129669
129810
  const headers = forwardableHeaders(request7.headers);
129670
129811
  delete headers.host;
129671
129812
  await new Promise((resolve2) => {
@@ -129673,7 +129814,7 @@ function createPassthroughRoute(name, target) {
129673
129814
  host: base.hostname,
129674
129815
  port: base.port === "" ? void 0 : Number(base.port),
129675
129816
  method: request7.method,
129676
- path: `${basePath}${path61}${incoming.search}`,
129817
+ path: `${basePath}${path63}${incoming.search}`,
129677
129818
  headers,
129678
129819
  agent
129679
129820
  };
@@ -129805,13 +129946,13 @@ async function scanRequestHead(request7, wholeBody = false) {
129805
129946
  }
129806
129947
 
129807
129948
  // src/frontdoor/providerRoute.ts
129808
- var isRcSelfHostPath = (path61) => path61 === "/v1/code/sessions" || path61.startsWith("/v1/code/sessions/") || path61 === "/v1/sessions" || path61.startsWith("/v1/sessions/");
129949
+ var isRcSelfHostPath = (path63) => path63 === "/v1/code/sessions" || path63.startsWith("/v1/code/sessions/") || path63 === "/v1/sessions" || path63.startsWith("/v1/sessions/");
129809
129950
  function scopeSessionProviderPath(request7) {
129810
129951
  if (request7.session.provider === void 0) {
129811
129952
  return request7;
129812
129953
  }
129813
- const path61 = new URL(request7.url, "http://127.0.0.1").pathname;
129814
- if (!path61.startsWith("/v1/") || isRcSelfHostPath(path61)) {
129954
+ const path63 = new URL(request7.url, "http://127.0.0.1").pathname;
129955
+ if (!path63.startsWith("/v1/") || isRcSelfHostPath(path63)) {
129815
129956
  return request7;
129816
129957
  }
129817
129958
  return { ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` };
@@ -129854,13 +129995,13 @@ function createProviderRouteResolver(deps) {
129854
129995
  return route;
129855
129996
  };
129856
129997
  const resolve2 = (request7) => {
129857
- const path61 = new URL(request7.url, "http://127.0.0.1").pathname;
129858
- const scoped = parseProviderPath(path61);
129998
+ const path63 = new URL(request7.url, "http://127.0.0.1").pathname;
129999
+ const scoped = parseProviderPath(path63);
129859
130000
  if (scoped === void 0) {
129860
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path61)) {
130001
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path63)) {
129861
130002
  return { ok: true, route: deps.rcSelfHostRoute };
129862
130003
  }
129863
- return path61.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path61}` };
130004
+ return path63.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path63}` };
129864
130005
  }
129865
130006
  const { provider } = scoped;
129866
130007
  let definition;
@@ -129946,8 +130087,8 @@ function createProviderRouteResolver(deps) {
129946
130087
  let replay;
129947
130088
  const visited = /* @__PURE__ */ new Set();
129948
130089
  for (; ; ) {
129949
- const path61 = new URL(current.url, "http://127.0.0.1").pathname;
129950
- const scoped = parseProviderPath(path61);
130090
+ const path63 = new URL(current.url, "http://127.0.0.1").pathname;
130091
+ const scoped = parseProviderPath(path63);
129951
130092
  const providerName = scoped?.provider ?? current.session.provider;
129952
130093
  if (providerName !== void 0 && visited.has(providerName)) {
129953
130094
  return { ok: false, status: HTTP_STATUS.internalServerError, message: `provider routing cycle: ${[...visited, providerName].join(" -> ")}` };
@@ -130005,7 +130146,7 @@ function createProviderRouteResolver(deps) {
130005
130146
  const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
130006
130147
  replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
130007
130148
  }
130008
- const rest = scoped === void 0 ? path61 : path61.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
130149
+ const rest = scoped === void 0 ? path63 : path63.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
130009
130150
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
130010
130151
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
130011
130152
  }
@@ -130228,8 +130369,8 @@ var SELF_HOST_SUBSCRIPTION_TYPE = "max";
130228
130369
  function isRecord14(value2) {
130229
130370
  return typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
130230
130371
  }
130231
- function readJsonObject(fs24, file2) {
130232
- const raw = fs24.readFileUtf8(file2);
130372
+ function readJsonObject(fs25, file2) {
130373
+ const raw = fs25.readFileUtf8(file2);
130233
130374
  if (raw === void 0) {
130234
130375
  return void 0;
130235
130376
  }
@@ -130241,8 +130382,8 @@ function readJsonObject(fs24, file2) {
130241
130382
  }
130242
130383
  return isRecord14(parsed) ? parsed : void 0;
130243
130384
  }
130244
- function readRcSelfHostRecord(fs24, frontdoorDir) {
130245
- const parsed = readJsonObject(fs24, import_node_path49.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
130385
+ function readRcSelfHostRecord(fs25, frontdoorDir) {
130386
+ const parsed = readJsonObject(fs25, import_node_path49.default.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
130246
130387
  if (parsed === void 0) {
130247
130388
  return void 0;
130248
130389
  }
@@ -130687,11 +130828,11 @@ function credentialOfJson(parsed) {
130687
130828
  function sequenceNumOfJson(value2) {
130688
130829
  return typeof value2 === "number" && Number.isInteger(value2) && value2 >= 0 ? value2 : void 0;
130689
130830
  }
130690
- function createRcCredentialStore(fs24, dir) {
130691
- fs24.mkdirPrivate(dir);
130831
+ function createRcCredentialStore(fs25, dir) {
130832
+ fs25.mkdirPrivate(dir);
130692
130833
  const fileFor = (sessionId) => import_node_path50.default.join(dir, `${sessionId}.json`);
130693
130834
  const readParsed = (sessionId) => {
130694
- const raw = fs24.readFileUtf8(fileFor(sessionId));
130835
+ const raw = fs25.readFileUtf8(fileFor(sessionId));
130695
130836
  if (raw === void 0) {
130696
130837
  return void 0;
130697
130838
  }
@@ -130716,7 +130857,7 @@ function createRcCredentialStore(fs24, dir) {
130716
130857
  }
130717
130858
  const cursor3 = sequenceNumOfJson(readParsed(sessionId)?.highestSequenceNum);
130718
130859
  const record2 = { ...credential, ...cursor3 === void 0 ? {} : { highestSequenceNum: cursor3 } };
130719
- fs24.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
130860
+ fs25.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
130720
130861
  `);
130721
130862
  },
130722
130863
  readCursor: (sessionId) => {
@@ -130731,14 +130872,14 @@ function createRcCredentialStore(fs24, dir) {
130731
130872
  }
130732
130873
  const credential = credentialOfJson(readParsed(sessionId));
130733
130874
  const record2 = credential === void 0 ? { highestSequenceNum } : { ...credential, highestSequenceNum };
130734
- fs24.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
130875
+ fs25.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record2, null, 2)}
130735
130876
  `);
130736
130877
  },
130737
130878
  remove: (sessionId) => {
130738
130879
  if (!isSafeSessionId(sessionId)) {
130739
130880
  return;
130740
130881
  }
130741
- fs24.removeRecursive(fileFor(sessionId));
130882
+ fs25.removeRecursive(fileFor(sessionId));
130742
130883
  }
130743
130884
  };
130744
130885
  }
@@ -133474,8 +133615,8 @@ function isAntigravityPayload(payload) {
133474
133615
  return typeof payload === "object" && payload !== null && "product" in payload && payload.product === "antigravity";
133475
133616
  }
133476
133617
  var ANTIGRAVITY_SETTINGS_SEGMENTS = [".gemini", "antigravity-cli", "settings.json"];
133477
- function antigravityStacksWithDefault(fs24, homeDir) {
133478
- const raw = fs24.readFileUtf8(import_node_path52.default.join(homeDir, ...ANTIGRAVITY_SETTINGS_SEGMENTS));
133618
+ function antigravityStacksWithDefault(fs25, homeDir) {
133619
+ const raw = fs25.readFileUtf8(import_node_path52.default.join(homeDir, ...ANTIGRAVITY_SETTINGS_SEGMENTS));
133479
133620
  if (raw === void 0) {
133480
133621
  return false;
133481
133622
  }
@@ -136247,8 +136388,8 @@ function getErrorMap2() {
136247
136388
 
136248
136389
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/helpers/parseUtil.js
136249
136390
  var makeIssue = (params) => {
136250
- const { data, path: path61, errorMaps, issueData } = params;
136251
- const fullPath = [...path61, ...issueData.path || []];
136391
+ const { data, path: path63, errorMaps, issueData } = params;
136392
+ const fullPath = [...path63, ...issueData.path || []];
136252
136393
  const fullIssue = {
136253
136394
  ...issueData,
136254
136395
  path: fullPath
@@ -136363,11 +136504,11 @@ var errorUtil;
136363
136504
 
136364
136505
  // node_modules/.pnpm/zod@4.6.5/node_modules/zod/v3/types.js
136365
136506
  var ParseInputLazyPath = class {
136366
- constructor(parent, value2, path61, key) {
136507
+ constructor(parent, value2, path63, key) {
136367
136508
  this._cachedPath = [];
136368
136509
  this.parent = parent;
136369
136510
  this.data = value2;
136370
- this._path = path61;
136511
+ this._path = path63;
136371
136512
  this._key = key;
136372
136513
  }
136373
136514
  get path() {
@@ -139930,11 +140071,11 @@ function normalizeObjectSchema(schema) {
139930
140071
  }
139931
140072
  return void 0;
139932
140073
  }
139933
- function getDotPath(path61) {
139934
- if (path61.length === 0) {
140074
+ function getDotPath(path63) {
140075
+ if (path63.length === 0) {
139935
140076
  return "object root";
139936
140077
  }
139937
- return path61.reduce((acc, seg, index) => {
140078
+ return path63.reduce((acc, seg, index) => {
139938
140079
  if (index === 0) {
139939
140080
  return String(seg);
139940
140081
  }
@@ -144842,11 +144983,177 @@ function registerHeadroomCommand(program2, deps) {
144842
144983
  });
144843
144984
  }
144844
144985
 
144986
+ // src/supervise/commands.ts
144987
+ init_realPorts();
144988
+
144989
+ // src/supervise/marks.ts
144990
+ init_resumeContext();
144991
+
144992
+ // src/supervise/registry.ts
144993
+ var import_node_path57 = __toESM(require("node:path"), 1);
144994
+ init_zod();
144995
+ var SupervisedSessionSchema = external_exports.strictObject({
144996
+ /** The launcher's process id, which is what tells a live entry from one a crashed launcher left behind. */
144997
+ pid: external_exports.number().int().positive(),
144998
+ sessionId: external_exports.string().min(1),
144999
+ pool: external_exports.string().min(1),
145000
+ /** The identity the session is running as now. */
145001
+ identity: external_exports.string().min(1),
145002
+ cwd: external_exports.string().min(1),
145003
+ /** When the session began running as `identity`: its launch, or the move that brought it there. */
145004
+ since: external_exports.iso.datetime(),
145005
+ /** The size in tokens of the context the session carried onto `identity` when it moved there; absent for a launch, which carries none. */
145006
+ carriedTokens: external_exports.number().int().nonnegative().optional()
145007
+ });
145008
+ var SessionStateSchema = external_exports.strictObject({
145009
+ /** `busy` from the moment a prompt is submitted until the turn ends, `idle` from then until the next prompt: the only times the child can be stopped without losing a turn. */
145010
+ mark: external_exports.enum(["busy", "idle"]),
145011
+ /** The size in tokens of the context as of the last turn that ended; absent until one has. */
145012
+ contextTokens: external_exports.number().int().nonnegative().optional(),
145013
+ /** Whether the session was compacted during its stay on the member it runs on now. Set by the supervisor, kept by later marks, and cleared when the session moves. */
145014
+ compacted: external_exports.boolean().optional(),
145015
+ at: external_exports.iso.datetime()
145016
+ });
145017
+ function superviseDirOf(paths, pool) {
145018
+ return import_node_path57.default.join(paths.superviseDir, pool);
145019
+ }
145020
+ function sessionsDirOf(paths, pool) {
145021
+ return import_node_path57.default.join(superviseDirOf(paths, pool), "sessions");
145022
+ }
145023
+ function sessionFileOf(paths, pool, sessionId) {
145024
+ return import_node_path57.default.join(sessionsDirOf(paths, pool), `${sessionId}.json`);
145025
+ }
145026
+ function stateDirOf(paths, pool) {
145027
+ return import_node_path57.default.join(superviseDirOf(paths, pool), "state");
145028
+ }
145029
+ function sessionStatePath(paths, pool, sessionId) {
145030
+ return import_node_path57.default.join(stateDirOf(paths, pool), `${sessionId}.json`);
145031
+ }
145032
+ function writeSessionState(fs25, paths, pool, sessionId, state) {
145033
+ fs25.mkdirPrivate(stateDirOf(paths, pool));
145034
+ fs25.writeFilePrivate(sessionStatePath(paths, pool, sessionId), `${JSON.stringify(SessionStateSchema.parse(state))}
145035
+ `);
145036
+ }
145037
+ function readSessionState(fs25, paths, pool, sessionId) {
145038
+ const raw = fs25.readFileUtf8(sessionStatePath(paths, pool, sessionId));
145039
+ if (raw === void 0) {
145040
+ return void 0;
145041
+ }
145042
+ try {
145043
+ const parsed = SessionStateSchema.safeParse(JSON.parse(raw));
145044
+ return parsed.success ? parsed.data : void 0;
145045
+ } catch {
145046
+ return void 0;
145047
+ }
145048
+ }
145049
+ function registerSupervised(fs25, paths, session) {
145050
+ fs25.mkdirPrivate(sessionsDirOf(paths, session.pool));
145051
+ fs25.writeFilePrivate(sessionFileOf(paths, session.pool, session.sessionId), `${JSON.stringify(SupervisedSessionSchema.parse(session))}
145052
+ `);
145053
+ }
145054
+ function unregisterSupervised(fs25, paths, pool, sessionId) {
145055
+ fs25.removeRecursive(sessionFileOf(paths, pool, sessionId));
145056
+ fs25.removeRecursive(sessionStatePath(paths, pool, sessionId));
145057
+ }
145058
+ function liveSupervised(fs25, paths, pool, isRunning) {
145059
+ const live = [];
145060
+ for (const name of fs25.readdir(sessionsDirOf(paths, pool))) {
145061
+ const file2 = import_node_path57.default.join(sessionsDirOf(paths, pool), name);
145062
+ const raw = fs25.readFileUtf8(file2);
145063
+ if (raw === void 0) {
145064
+ continue;
145065
+ }
145066
+ let parsed;
145067
+ try {
145068
+ parsed = SupervisedSessionSchema.safeParse(JSON.parse(raw));
145069
+ } catch {
145070
+ fs25.removeRecursive(file2);
145071
+ continue;
145072
+ }
145073
+ if (parsed.success && isRunning(parsed.data.pid)) {
145074
+ live.push(parsed.data);
145075
+ } else {
145076
+ fs25.removeRecursive(file2);
145077
+ }
145078
+ }
145079
+ return live;
145080
+ }
145081
+ function committedContextTokens(sessions, records) {
145082
+ const committed = {};
145083
+ for (const session of sessions) {
145084
+ if (session.carriedTokens === void 0) {
145085
+ continue;
145086
+ }
145087
+ const sinceMs = Date.parse(session.since);
145088
+ const written = records.some((record2) => record2.sessionId === session.sessionId && record2.identity === session.identity && Date.parse(record2.at) >= sinceMs);
145089
+ if (!written) {
145090
+ committed[session.identity] = (committed[session.identity] ?? 0) + session.carriedTokens;
145091
+ }
145092
+ }
145093
+ return committed;
145094
+ }
145095
+
145096
+ // src/supervise/marks.ts
145097
+ var MARK_HOOK_TIMEOUT_SECONDS = 10;
145098
+ var SUPERVISE_MARK_COMMAND = "__supervise-mark";
145099
+ function shellQuote(value2) {
145100
+ return `'${value2.replaceAll("'", `'\\''`)}'`;
145101
+ }
145102
+ function markHooksSettings(invocation, root, pool, sessionId) {
145103
+ const hook = (mark) => [
145104
+ {
145105
+ hooks: [
145106
+ {
145107
+ type: "command",
145108
+ command: `AGENT_SHIM_HOME=${shellQuote(root)} ${[invocation.command, ...invocation.args, SUPERVISE_MARK_COMMAND, pool, sessionId, mark].map(shellQuote).join(" ")}`,
145109
+ timeout: MARK_HOOK_TIMEOUT_SECONDS
145110
+ }
145111
+ ]
145112
+ }
145113
+ ];
145114
+ return JSON.stringify({ hooks: { UserPromptSubmit: hook("busy"), Stop: hook("idle"), StopFailure: hook("idle") } });
145115
+ }
145116
+ function recordMark(context, pool, sessionId, mark) {
145117
+ const previous = readSessionState(context.fs, context.paths, pool, sessionId);
145118
+ let contextTokens = previous?.contextTokens;
145119
+ if (mark === "idle") {
145120
+ if (context.configDir === void 0) {
145121
+ throw new Error("CLAUDE_CONFIG_DIR is not set, so the session's transcript cannot be found");
145122
+ }
145123
+ contextTokens = resumedContextTokens(context.fs, { claudeHome: context.configDir, cwd: context.cwd, passthrough: ["--resume", sessionId] }) ?? contextTokens;
145124
+ }
145125
+ writeSessionState(context.fs, context.paths, pool, sessionId, {
145126
+ mark,
145127
+ ...contextTokens === void 0 ? {} : { contextTokens },
145128
+ ...previous?.compacted === true ? { compacted: true } : {},
145129
+ at: new Date(context.now()).toISOString()
145130
+ });
145131
+ }
145132
+
145133
+ // src/supervise/commands.ts
145134
+ var MARKS = ["busy", "idle"];
145135
+ function isTurnMark(value2) {
145136
+ return MARKS.includes(value2);
145137
+ }
145138
+ function registerSuperviseMarkCommand(program2, deps) {
145139
+ program2.command(`${SUPERVISE_MARK_COMMAND} <pool> <session> <mark>`, { hidden: true }).description("Internal: record that a supervised session's turn began or ended. Run by the session's own hooks; never by hand.").action((pool, session, mark) => {
145140
+ try {
145141
+ if (!isTurnMark(mark)) {
145142
+ throw new Error(`"${mark}" is not a turn mark: use busy or idle`);
145143
+ }
145144
+ recordMark({ fs: realFarmFs, paths: deps.paths, now: Date.now, configDir: process.env.CLAUDE_CONFIG_DIR, cwd: process.cwd() }, pool, session, mark);
145145
+ } catch (error63) {
145146
+ console.error(`agent-shim: could not record the turn mark: ${error63 instanceof Error ? error63.message : String(error63)}`);
145147
+ deps.exit(1);
145148
+ }
145149
+ });
145150
+ }
145151
+
144845
145152
  // src/headlessCommands.ts
144846
145153
  init_realPorts();
144847
145154
 
144848
145155
  // src/usage/realJobRunner.ts
144849
- var import_node_path57 = __toESM(require("node:path"), 1);
145156
+ var import_node_path58 = __toESM(require("node:path"), 1);
144850
145157
  init_conditions();
144851
145158
  init_identityClaude();
144852
145159
  var JOB_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
@@ -144859,7 +145166,7 @@ ${outcome.trimEnd()}
144859
145166
  }
144860
145167
  function createRealJobRunner(params) {
144861
145168
  return async (name, identity, job) => {
144862
- const logFile = import_node_path57.default.join(params.paths.jobLogsDir, `${name}.log`);
145169
+ const logFile = import_node_path58.default.join(params.paths.jobLogsDir, `${name}.log`);
144863
145170
  const append = (outcome) => {
144864
145171
  params.fs.mkdirPrivate(params.paths.jobLogsDir);
144865
145172
  params.fs.appendFilePrivate(logFile, logEntry(name, identity, params.now(), outcome));
@@ -144913,7 +145220,7 @@ function registerHeadlessCommands(program2, deps) {
144913
145220
  }
144914
145221
 
144915
145222
  // src/jobs.ts
144916
- var import_node_path58 = __toESM(require("node:path"), 1);
145223
+ var import_node_path59 = __toESM(require("node:path"), 1);
144917
145224
  init_commandDeps();
144918
145225
  init_cliError();
144919
145226
  init_schema();
@@ -144938,7 +145245,7 @@ function jobOf(options) {
144938
145245
  target: options.identity === void 0 ? { pool: options.pool ?? "" } : { identity: options.identity },
144939
145246
  trigger: options.at === void 0 ? { beforeReset: options.beforeReset ?? "fiveHour", lead: options.lead ?? "" } : { at: options.at },
144940
145247
  prompt: options.prompt,
144941
- cwd: import_node_path58.default.resolve(options.cwd ?? process.cwd()),
145248
+ cwd: import_node_path59.default.resolve(options.cwd ?? process.cwd()),
144942
145249
  timeout: options.timeout,
144943
145250
  ...options.model === void 0 ? {} : { model: options.model },
144944
145251
  ...options.allowedTool === void 0 ? {} : { allowedTools: options.allowedTool }
@@ -145011,7 +145318,7 @@ function registerJobCommand(program2, deps) {
145011
145318
  console.log(`Allowed tools: ${entry.allowedTools.join(", ")}`);
145012
145319
  }
145013
145320
  console.log(`Prompt: ${entry.prompt}`);
145014
- console.log(`Results: ${import_node_path58.default.join(paths.jobLogsDir, `${name}.log`)}`);
145321
+ console.log(`Results: ${import_node_path59.default.join(paths.jobLogsDir, `${name}.log`)}`);
145015
145322
  }),
145016
145323
  ["agent-shim job show digest"]
145017
145324
  );
@@ -145034,7 +145341,7 @@ function registerJobCommand(program2, deps) {
145034
145341
  throw new UsageError(`No member of the job's pool can be picked right now.`);
145035
145342
  }
145036
145343
  await createRealJobRunner({ paths, spawnDaemon: spawnDetachedSupervisor, fs: realFarmFs, now: () => /* @__PURE__ */ new Date() })(name, identity, entry);
145037
- console.log(`Ran job "${name}" as ${identity}; the result is in ${import_node_path58.default.join(paths.jobLogsDir, `${name}.log`)}.`);
145344
+ console.log(`Ran job "${name}" as ${identity}; the result is in ${import_node_path59.default.join(paths.jobLogsDir, `${name}.log`)}.`);
145038
145345
  }),
145039
145346
  ["agent-shim job run digest"]
145040
145347
  );
@@ -145057,12 +145364,23 @@ function formatPoolPick(report, nowMs) {
145057
145364
  });
145058
145365
  return [head, ...rows, ...report.missing.map((name) => ` (skipped: ${name} is not an identity)`), ...report.stickyProblem === void 0 ? [] : [`Note: ${report.stickyProblem}; the last-pick record was ignored.`]];
145059
145366
  }
145367
+ function policyNotes(entry) {
145368
+ const notes = [
145369
+ ...entry?.preference === void 0 ? [] : [`preference: ${entry.preference}`],
145370
+ ...entry?.resumeOnLimit === true ? ["resumes on limit"] : [],
145371
+ ...entry?.compactBeforeLimit === true ? [entry.compactAtUtilisation === void 0 ? "compacts before the limit" : `compacts at ${String(entry.compactAtUtilisation)}%`] : []
145372
+ ];
145373
+ return notes.length === 0 ? "" : ` (${notes.join(", ")})`;
145374
+ }
145060
145375
  function membersOf(options) {
145061
145376
  if (options.identity === void 0 || options.identity.length === 0) {
145062
145377
  throw new UsageError("A pool needs at least one member: pass --identity <name> (repeatable).");
145063
145378
  }
145064
145379
  return options.identity;
145065
145380
  }
145381
+ var RESUME_ON_LIMIT_DESCRIPTION = "Keep an interactive session of this pool going when its identity runs out of quota: the launcher stops it and resumes the same conversation under the next ranked member, on the same terminal.";
145382
+ var COMPACT_BEFORE_LIMIT_DESCRIPTION = "Compact each supervised session's context while its member can still afford it, so the resume on the next member writes a small context instead of a large one. Needs --resume-on-limit.";
145383
+ var COMPACT_AT_UTILISATION_DESCRIPTION = "Compact when either quota window of the member passes this share, in whole percent. Without it, a session is compacted when compacting every session on its member would cost more than the five-hour window has left. Needs --compact-before-limit.";
145066
145384
  var PREFERENCE_DESCRIPTION = "How a launch picks a member: score (the default) picks the member whose remaining quota expires soonest; listed tries the members in the order the pool lists them, skipping any that is refused right now.";
145067
145385
  function registerPoolCommand(program2, deps) {
145068
145386
  const { paths } = deps;
@@ -145071,10 +145389,10 @@ function registerPoolCommand(program2, deps) {
145071
145389
  ["agent-shim pool add subs --identity work --identity personal", "agent-shim pool pick subs"]
145072
145390
  );
145073
145391
  withExamples(
145074
- pool.command("add <name>").description("Define a pool. Fails if one with this name already exists.").option("--identity <name>", "A member: an identity name, or pool:<name> to nest another pool with its own policy (repeatable).", collectRepeated).addOption(new Option("--preference <mode>", PREFERENCE_DESCRIPTION).choices(POOL_PREFERENCES)).option("--json", "Print the result as JSON.").action((name, options) => {
145392
+ pool.command("add <name>").description("Define a pool. Fails if one with this name already exists.").option("--identity <name>", "A member: an identity name, or pool:<name> to nest another pool with its own policy (repeatable).", collectRepeated).addOption(new Option("--preference <mode>", PREFERENCE_DESCRIPTION).choices(POOL_PREFERENCES)).option("--resume-on-limit", RESUME_ON_LIMIT_DESCRIPTION).option("--compact-before-limit", COMPACT_BEFORE_LIMIT_DESCRIPTION).option("--compact-at-utilisation <percent>", COMPACT_AT_UTILISATION_DESCRIPTION, parseUtilisationPercent).option("--json", "Print the result as JSON.").action((name, options) => {
145075
145393
  const members2 = membersOf(options);
145076
145394
  requireIdentityNames(paths, members2);
145077
- const created = addPool(paths, name, members2, options.preference);
145395
+ const created = addPool(paths, name, members2, { preference: options.preference, resumeOnLimit: options.resumeOnLimit, compactBeforeLimit: options.compactBeforeLimit, compactAtUtilisation: options.compactAtUtilisation });
145078
145396
  reportMutation(options.json, { action: "created", kind: "pool", name, value: created }, () => {
145079
145397
  console.log(`Created pool "${name}" with ${members2.join(", ")}.`);
145080
145398
  });
@@ -145082,29 +145400,28 @@ function registerPoolCommand(program2, deps) {
145082
145400
  ["agent-shim pool add subs --identity work --identity personal", "agent-shim pool add client --identity client-main --identity spare --preference listed"]
145083
145401
  );
145084
145402
  withExamples(
145085
- pool.command("set <name>").description("Replace a pool's members, its preference, or both.").option("--identity <name>", "A member: an identity name, or pool:<name> to nest another pool with its own policy (repeatable); the full new list. Kept as-is when this option is absent.", collectRepeated).addOption(new Option("--preference <mode>", PREFERENCE_DESCRIPTION).choices(POOL_PREFERENCES)).option("--no-preference", "Clear the preference back to the default, score.").option("--json", "Print the result as JSON.").action((name, options) => {
145086
- const existing = requirePool(paths, name);
145087
- if (options.identity === void 0 && options.preference === void 0) {
145088
- throw new UsageError("Nothing to change: pass --identity, --preference or --no-preference.");
145403
+ pool.command("set <name>").description("Replace a pool's members, change its preference or whether it resumes on a spent quota, or several.").option("--identity <name>", "A member: an identity name, or pool:<name> to nest another pool with its own policy (repeatable); the full new list. Kept as-is when this option is absent.", collectRepeated).addOption(new Option("--preference <mode>", PREFERENCE_DESCRIPTION).choices(POOL_PREFERENCES)).option("--no-preference", "Clear the preference back to the default, score.").option("--resume-on-limit", RESUME_ON_LIMIT_DESCRIPTION).option("--no-resume-on-limit", "Stop resuming sessions of this pool under another member when their identity runs out of quota.").option("--compact-before-limit", COMPACT_BEFORE_LIMIT_DESCRIPTION).option("--no-compact-before-limit", "Stop compacting sessions of this pool before their member's quota is spent.").option("--compact-at-utilisation <percent>", COMPACT_AT_UTILISATION_DESCRIPTION, parseUtilisationPercent).option("--no-compact-at-utilisation", "Clear the compaction threshold, so the launcher decides from what compacting would cost.").option("--json", "Print the result as JSON.").action((name, options) => {
145404
+ requirePool(paths, name);
145405
+ const change = { identities: options.identity, preference: options.preference, resumeOnLimit: options.resumeOnLimit, compactBeforeLimit: options.compactBeforeLimit, compactAtUtilisation: options.compactAtUtilisation };
145406
+ if (!isPoolChange(change)) {
145407
+ throw new UsageError("Nothing to change: pass a member with --identity, or a setting such as --preference, --resume-on-limit, --compact-before-limit or --compact-at-utilisation (each with a --no- form).");
145089
145408
  }
145090
- const members2 = options.identity === void 0 ? existing.identities : membersOf(options);
145091
145409
  if (options.identity !== void 0) {
145092
145410
  requireIdentityNames(paths, membersOf(options));
145093
145411
  }
145094
- const preference = options.preference === void 0 ? existing.preference : options.preference === false ? void 0 : options.preference;
145095
- const updated = setPool(paths, name, members2, preference);
145412
+ const updated = changePool(paths, name, change);
145096
145413
  reportMutation(options.json, { action: "updated", kind: "pool", name, value: updated }, () => {
145097
- console.log(`Pool "${name}" now has ${members2.map(poolMemberIdentity).join(", ")}.`);
145414
+ console.log(`Pool "${name}" now has ${updated.identities.map(poolMemberIdentity).join(", ")}.`);
145098
145415
  });
145099
145416
  }),
145100
- ["agent-shim pool set subs --identity work --identity personal --identity spare", "agent-shim pool set subs --preference listed"]
145417
+ ["agent-shim pool set subs --identity work --identity personal --identity spare", "agent-shim pool set subs --preference listed", "agent-shim pool set subs --resume-on-limit --compact-before-limit --compact-at-utilisation 85"]
145101
145418
  );
145102
145419
  withExamples(
145103
145420
  pool.command("list").description("List every pool and its members, marking the active selection with *.").option("--json", "Print the pools as JSON.").action((options) => {
145104
145421
  const pools = readPools(paths);
145105
145422
  const active = readActiveIdentity2(paths);
145106
145423
  if (options.json === true) {
145107
- printJson(Object.entries(pools).map(([name, entry]) => ({ name, identities: entry.identities, ...entry.preference === void 0 ? {} : { preference: entry.preference }, active: active === `${POOL_SELECTOR_PREFIX}${name}` })));
145424
+ printJson(Object.entries(pools).map(([name, entry]) => ({ name, identities: entry.identities, ...poolPolicyOf(entry), active: active === `${POOL_SELECTOR_PREFIX}${name}` })));
145108
145425
  return;
145109
145426
  }
145110
145427
  const names = Object.keys(pools).sort();
@@ -145114,7 +145431,7 @@ function registerPoolCommand(program2, deps) {
145114
145431
  }
145115
145432
  for (const name of names) {
145116
145433
  const entry = pools[name];
145117
- console.log(`${active === `${POOL_SELECTOR_PREFIX}${name}` ? "*" : " "} ${name}: ${(entry?.identities ?? []).map(poolMemberIdentity).join(", ")}${entry?.preference === void 0 ? "" : " (preference: listed)"}`);
145434
+ console.log(`${active === `${POOL_SELECTOR_PREFIX}${name}` ? "*" : " "} ${name}: ${(entry?.identities ?? []).map(poolMemberIdentity).join(", ")}${policyNotes(entry)}`);
145118
145435
  }
145119
145436
  }),
145120
145437
  ["agent-shim pool list", "agent-shim pool list --json"]
@@ -145123,7 +145440,7 @@ function registerPoolCommand(program2, deps) {
145123
145440
  pool.command("show <name>").description("Show one pool's members.").option("--json", "Print the pool as JSON.").action((name, options) => {
145124
145441
  const entry = requirePool(paths, name);
145125
145442
  if (options.json === true) {
145126
- printJson({ name, identities: entry.identities, ...entry.preference === void 0 ? {} : { preference: entry.preference } });
145443
+ printJson({ name, identities: entry.identities, ...poolPolicyOf(entry) });
145127
145444
  return;
145128
145445
  }
145129
145446
  console.log(`Pool: ${name}`);
@@ -145131,6 +145448,12 @@ function registerPoolCommand(program2, deps) {
145131
145448
  if (entry.preference !== void 0) {
145132
145449
  console.log(`Preference: ${entry.preference}`);
145133
145450
  }
145451
+ if (entry.resumeOnLimit === true) {
145452
+ console.log("Resume on limit: yes");
145453
+ }
145454
+ if (entry.compactBeforeLimit === true) {
145455
+ console.log(`Compact before limit: ${entry.compactAtUtilisation === void 0 ? "when compacting would cost more than the five-hour window has left" : `at ${String(entry.compactAtUtilisation)}% of a window`}`);
145456
+ }
145134
145457
  }),
145135
145458
  ["agent-shim pool show subs"]
145136
145459
  );
@@ -145565,7 +145888,7 @@ function registerSessionCommands(program2, deps) {
145565
145888
  }
145566
145889
 
145567
145890
  // src/usage/commands.ts
145568
- var import_node_path59 = __toESM(require("node:path"), 1);
145891
+ var import_node_path60 = __toESM(require("node:path"), 1);
145569
145892
  init_commandDeps();
145570
145893
  init_realPorts();
145571
145894
  init_account();
@@ -145581,14 +145904,14 @@ function requireIdentity(paths, name) {
145581
145904
  throw new IdentityNotFoundError(name);
145582
145905
  }
145583
145906
  }
145584
- function collectUsageReport(fs24, paths, filters) {
145907
+ function collectUsageReport(fs25, paths, filters) {
145585
145908
  const { identity, provider, sinceMs } = filters;
145586
145909
  if (identity !== void 0) {
145587
145910
  requireIdentity(paths, identity);
145588
145911
  }
145589
- const log = readUsageLog(fs24, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
145912
+ const log = readUsageLog(fs25, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
145590
145913
  const records = log.records.filter((record2) => (identity === void 0 || record2.identity === identity) && (provider === void 0 || record2.provider === provider));
145591
- const snapshots = (identity === void 0 ? listUsageSnapshots(fs24, paths.usageSnapshotsDir) : [readUsageSnapshot(fs24, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
145914
+ const snapshots = (identity === void 0 ? listUsageSnapshots(fs25, paths.usageSnapshotsDir) : [readUsageSnapshot(fs25, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
145592
145915
  return {
145593
145916
  since: sinceMs === void 0 ? void 0 : new Date(sinceMs).toISOString(),
145594
145917
  logDir: paths.usageLogDir,
@@ -145695,16 +146018,16 @@ function formatUsageReport(report) {
145695
146018
  }
145696
146019
  return lines;
145697
146020
  }
145698
- function collectAccounts(fs24, paths, identity, probe) {
146021
+ function collectAccounts(fs25, paths, identity, probe) {
145699
146022
  if (identity !== void 0) {
145700
146023
  requireIdentity(paths, identity);
145701
146024
  }
145702
146025
  const names = identity === void 0 ? listIdentities(paths).map((entry) => entry.name) : [identity];
145703
146026
  return names.map((name) => ({
145704
146027
  identity: name,
145705
- account: readAccountMetadata(fs24, paths.identitiesDir, name),
145706
- signIn: identitySignIn(fs24, probe, { farmRoot: import_node_path59.default.join(paths.identitiesDir, name), hasCredentialBlock: readIdentity(paths, name)?.credential !== void 0 }),
145707
- usage: readUsageSnapshot(fs24, paths.usageSnapshotsDir, name)
146028
+ account: readAccountMetadata(fs25, paths.identitiesDir, name),
146029
+ signIn: identitySignIn(fs25, probe, { farmRoot: import_node_path60.default.join(paths.identitiesDir, name), hasCredentialBlock: readIdentity(paths, name)?.credential !== void 0 }),
146030
+ usage: readUsageSnapshot(fs25, paths.usageSnapshotsDir, name)
145708
146031
  }));
145709
146032
  }
145710
146033
  function formatAccounts(views) {
@@ -145890,6 +146213,7 @@ function buildProgram(deps) {
145890
146213
  registerMcpCommand(program2, deps);
145891
146214
  registerUsageCommands(program2, deps);
145892
146215
  registerSessionCommands(program2, deps);
146216
+ registerSuperviseMarkCommand(program2, deps);
145893
146217
  registerRunCommand(program2, deps.runClaude);
145894
146218
  registerUpdateCommand(program2, deps, deps.updatePorts);
145895
146219
  registerCompletionCommand(program2);
@@ -145937,6 +146261,618 @@ async function realRefresher(params) {
145937
146261
  });
145938
146262
  }
145939
146263
 
146264
+ // src/supervise/launch.ts
146265
+ var import_node_crypto25 = require("node:crypto");
146266
+ init_claudeSession();
146267
+ init_pool();
146268
+ init_realPorts();
146269
+ init_resumeContext();
146270
+
146271
+ // src/supervise/compactionDeps.ts
146272
+ init_lock();
146273
+ init_pick();
146274
+ init_read();
146275
+
146276
+ // src/supervise/compaction.ts
146277
+ init_middleware();
146278
+ init_pick();
146279
+ init_preflight();
146280
+ var PERCENT6 = 100;
146281
+ var asPercent = (fraction) => `${String(Math.round(fraction * PERCENT6))}%`;
146282
+ function compactableTokens(state) {
146283
+ return state?.mark === "idle" && state.compacted !== true && state.contextTokens !== void 0 && state.contextTokens > 0 ? state.contextTokens : void 0;
146284
+ }
146285
+ function triggerReason(input2) {
146286
+ const unified = input2.snapshot?.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified;
146287
+ const five = unified?.fiveHour === void 0 ? void 0 : effectiveWindow(unified.fiveHour, input2.nowMs);
146288
+ if (input2.atUtilisation !== void 0) {
146289
+ const seven = unified?.sevenDay === void 0 ? void 0 : effectiveWindow(unified.sevenDay, input2.nowMs);
146290
+ for (const [name, window] of [["5h", five], ["7d", seven]]) {
146291
+ if (window?.utilization !== void 0 && window.utilization * PERCENT6 >= input2.atUtilisation) {
146292
+ return `the ${name} window is at ${asPercent(window.utilization)}, past ${String(input2.atUtilisation)}%`;
146293
+ }
146294
+ }
146295
+ return void 0;
146296
+ }
146297
+ const perToken = utilisationPerBilledToken(input2.records());
146298
+ if (five?.utilization === void 0 || perToken === void 0) {
146299
+ return void 0;
146300
+ }
146301
+ const remaining = Math.max(0, 1 - five.utilization);
146302
+ const cost = input2.sessions.reduce((sum, session) => sum + (session.state?.contextTokens ?? 0), 0) * perToken;
146303
+ return remaining < cost ? `the 5h window has ${asPercent(remaining)} left, and compacting every session on this member would use about ${asPercent(cost)}` : void 0;
146304
+ }
146305
+ function decideCompaction(input2) {
146306
+ const own2 = input2.sessions.find((session) => session.sessionId === input2.sessionId);
146307
+ const tokens = compactableTokens(own2?.state);
146308
+ if (tokens === void 0) {
146309
+ return { compact: false, reason: "the session is mid-turn, has no context recorded yet, or was already compacted on this member" };
146310
+ }
146311
+ const larger = input2.sessions.some((session) => {
146312
+ const other = compactableTokens(session.state);
146313
+ return session.sessionId !== input2.sessionId && other !== void 0 && (other > tokens || other === tokens && session.sessionId < input2.sessionId);
146314
+ });
146315
+ if (larger) {
146316
+ return { compact: false, reason: "a larger session on this member compacts first" };
146317
+ }
146318
+ const reason = triggerReason(input2);
146319
+ return reason === void 0 ? { compact: false, reason: "the member's quota has not reached the trigger" } : { compact: true, contextTokens: tokens, reason };
146320
+ }
146321
+
146322
+ // src/supervise/realCompact.ts
146323
+ init_identityClaude();
146324
+ var COMPACT_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
146325
+ var COMPACT_TIMEOUT_MS = 9e5;
146326
+ function boundarySizes(message) {
146327
+ if (!("compact_metadata" in message) || typeof message.compact_metadata !== "object" || message.compact_metadata === null) {
146328
+ return {};
146329
+ }
146330
+ const metadata = message.compact_metadata;
146331
+ const before = "pre_tokens" in metadata && typeof metadata.pre_tokens === "number" ? metadata.pre_tokens : void 0;
146332
+ const after = "post_tokens" in metadata && typeof metadata.post_tokens === "number" ? metadata.post_tokens : void 0;
146333
+ return { ...before === void 0 ? {} : { beforeTokens: before }, ...after === void 0 ? {} : { afterTokens: after } };
146334
+ }
146335
+ function createRealCompactor(params) {
146336
+ return async (request7, signal) => await withIdentityClaude({ paths: params.paths, spawnDaemon: params.spawnDaemon, cwd: request7.cwd, timeoutMs: COMPACT_TIMEOUT_MS }, request7.identity, COMPACT_LAUNCH_FLAGS, async ({ bin, env, cwd, abort }) => {
146337
+ signal.addEventListener("abort", () => {
146338
+ abort.abort();
146339
+ });
146340
+ const { query } = await Promise.resolve().then(() => (init_sdk(), sdk_exports));
146341
+ const session = query({
146342
+ prompt: "/compact",
146343
+ options: {
146344
+ pathToClaudeCodeExecutable: bin,
146345
+ env,
146346
+ cwd,
146347
+ abortController: abort,
146348
+ resume: request7.sessionId,
146349
+ settingSources: [...JOB_ISOLATION_OPTIONS.settingSources],
146350
+ mcpServers: JOB_ISOLATION_OPTIONS.mcpServers,
146351
+ strictMcpConfig: JOB_ISOLATION_OPTIONS.strictMcpConfig
146352
+ }
146353
+ });
146354
+ try {
146355
+ let sizes;
146356
+ for await (const message of session) {
146357
+ if (message.type === "system" && message.subtype === "compact_boundary") {
146358
+ sizes = boundarySizes(message);
146359
+ }
146360
+ if (message.type === "result") {
146361
+ const text2 = successfulResult(message);
146362
+ return sizes === void 0 ? { kind: "unchanged", reason: text2 === "" ? "nothing was compacted" : text2 } : { kind: "compacted", ...sizes };
146363
+ }
146364
+ }
146365
+ throw new Error("the compaction ended without a result");
146366
+ } finally {
146367
+ session.close();
146368
+ }
146369
+ });
146370
+ }
146371
+
146372
+ // src/supervise/compactionDeps.ts
146373
+ var COMPACT_SLOT_STALE_MS = COMPACT_TIMEOUT_MS * 2;
146374
+ function createCompactionDeps(wiring) {
146375
+ const { paths, fs: fs25, pool } = wiring;
146376
+ return {
146377
+ shouldCompact: (identity, sessionId) => {
146378
+ const nowMs = wiring.now();
146379
+ const sessions = liveSupervised(fs25, paths, pool, wiring.isRunning).filter((session) => session.identity === identity).map((session) => ({ sessionId: session.sessionId, state: readSessionState(fs25, paths, pool, session.sessionId) }));
146380
+ return decideCompaction({
146381
+ atUtilisation: wiring.policy.compactAtUtilisation,
146382
+ snapshot: readUsageSnapshot(fs25, paths.usageSnapshotsDir, identity),
146383
+ records: () => readUsageLog(fs25, paths.usageLogDir, { sinceMs: nowMs - FIVE_HOUR_WINDOW_MS }).records.filter((record2) => record2.identity === identity),
146384
+ sessions,
146385
+ sessionId,
146386
+ nowMs
146387
+ });
146388
+ },
146389
+ acquire: (identity) => {
146390
+ try {
146391
+ const lock = acquireIdentityLock({ identity: `compact-${identity}`, dir: superviseDirOf(paths, pool), fs: fs25, nowMs: wiring.now, pid: wiring.pid, isRunning: wiring.isRunning, sleep: wiring.sleep, maxAttempts: 1, staleAfterMs: COMPACT_SLOT_STALE_MS });
146392
+ return { release: lock.release };
146393
+ } catch (error63) {
146394
+ if (error63 instanceof IdentityLockBusyError) {
146395
+ return void 0;
146396
+ }
146397
+ throw error63;
146398
+ }
146399
+ },
146400
+ compact: wiring.compact,
146401
+ markCompacted: (sessionId, compacted) => {
146402
+ const previous = readSessionState(fs25, paths, pool, sessionId);
146403
+ writeSessionState(fs25, paths, pool, sessionId, {
146404
+ mark: previous?.mark ?? "idle",
146405
+ ...previous?.contextTokens === void 0 ? {} : { contextTokens: previous.contextTokens },
146406
+ ...compacted ? { compacted: true } : {},
146407
+ at: new Date(wiring.now()).toISOString()
146408
+ });
146409
+ }
146410
+ };
146411
+ }
146412
+
146413
+ // src/supervise/limit.ts
146414
+ init_read();
146415
+ function quotaHitOf(fs25, paths, identity, sessionId, sinceMs, nowMs) {
146416
+ const reason = refusalReason(identity, readUsageSnapshot(fs25, paths.usageSnapshotsDir, identity), nowMs);
146417
+ if (reason === void 0) {
146418
+ return void 0;
146419
+ }
146420
+ const { records } = readUsageLog(fs25, paths.usageLogDir, { sinceMs });
146421
+ for (let index = records.length - 1; index >= 0; index -= 1) {
146422
+ const record2 = records[index];
146423
+ if (record2?.sessionId === sessionId && record2.identity === identity && record2.limit?.kind === "quota-exhausted") {
146424
+ return { reason, ...record2.limit.resetAt === void 0 ? {} : { resetAt: record2.limit.resetAt } };
146425
+ }
146426
+ }
146427
+ return void 0;
146428
+ }
146429
+
146430
+ // src/supervise/move.ts
146431
+ var import_node_path61 = __toESM(require("node:path"), 1);
146432
+ init_lock();
146433
+ init_poolPick();
146434
+ init_read();
146435
+ init_resumeContext();
146436
+ function createMover(deps) {
146437
+ const { paths, farmFs, pool } = deps;
146438
+ return (request7) => {
146439
+ let lock;
146440
+ try {
146441
+ lock = acquireIdentityLock({ identity: "move", dir: superviseDirOf(paths, pool), fs: farmFs, nowMs: deps.now, pid: deps.pid, isRunning: deps.isRunning, sleep: deps.sleep });
146442
+ } catch (error63) {
146443
+ if (error63 instanceof IdentityLockBusyError) {
146444
+ return { kind: "stay", reason: error63.message };
146445
+ }
146446
+ throw error63;
146447
+ }
146448
+ try {
146449
+ const others = liveSupervised(farmFs, paths, pool, deps.isRunning).filter((session) => session.sessionId !== request7.sessionId);
146450
+ const carrying = others.filter((session) => session.carriedTokens !== void 0);
146451
+ const records = carrying.length === 0 ? [] : readUsageLog(farmFs, paths.usageLogDir, { sinceMs: Math.min(...carrying.map((session) => Date.parse(session.since))) }).records;
146452
+ const committed = committedContextTokens(others, records);
146453
+ const resolution = deps.pickMember({
146454
+ poolName: pool,
146455
+ selectedVia: "the supervising launcher",
146456
+ pools: deps.pools,
146457
+ paths,
146458
+ fs: deps.fs,
146459
+ usageFs: farmFs,
146460
+ cwd: deps.cwd,
146461
+ now: deps.now,
146462
+ sleep: deps.sleep,
146463
+ passthrough: ["--resume", request7.sessionId],
146464
+ ...request7.contextTokens === void 0 ? {} : { resumeContextTokens: request7.contextTokens },
146465
+ ...Object.keys(committed).length === 0 ? {} : { committedContextTokens: committed },
146466
+ wait: false,
146467
+ // Recorded below, once the member is known to be able to resume the conversation: a pick that is then refused must leave the directory's last pick as it was.
146468
+ recordPick: false,
146469
+ log: deps.log
146470
+ });
146471
+ if (!resolution.ok) {
146472
+ return { kind: "stay", reason: resolution.message };
146473
+ }
146474
+ if (resolution.identity === request7.from) {
146475
+ return { kind: "stay", reason: `no other member of pool "${pool}" can take it` };
146476
+ }
146477
+ const transcript = import_node_path61.default.join(paths.identitiesDir, resolution.identity, "projects", projectDirNameOf(deps.cwd), `${request7.sessionId}.jsonl`);
146478
+ if (farmFs.lstat(transcript)?.kind !== "file") {
146479
+ return { kind: "stay", reason: `${resolution.identity} does not share this conversation's history, so it could not resume it` };
146480
+ }
146481
+ const nowMs = deps.now();
146482
+ recordStickyPick(farmFs, paths.usagePicksFile, deps.cwd, resolution.identity, nowMs);
146483
+ registerSupervised(farmFs, paths, {
146484
+ pid: deps.pid,
146485
+ sessionId: request7.sessionId,
146486
+ pool,
146487
+ identity: resolution.identity,
146488
+ cwd: deps.cwd,
146489
+ since: new Date(nowMs).toISOString(),
146490
+ ...request7.contextTokens === void 0 ? {} : { carriedTokens: request7.contextTokens }
146491
+ });
146492
+ return { kind: "move", to: resolution.identity, explanation: resolution.explanation };
146493
+ } finally {
146494
+ lock.release();
146495
+ }
146496
+ };
146497
+ }
146498
+
146499
+ // src/supervise/realPorts.ts
146500
+ var import_node_child_process10 = require("node:child_process");
146501
+ var import_node_fs23 = __toESM(require("node:fs"), 1);
146502
+ init_realPorts();
146503
+ var realSupervisedSpawnPort = {
146504
+ spawn(command, args, options) {
146505
+ const child = (0, import_node_child_process10.spawn)(command, [...args], { stdio: options.stdio, env: { ...options.env } });
146506
+ const exit = new Promise((resolve2) => {
146507
+ child.once("error", (error63) => {
146508
+ resolve2({ status: null, signal: null, error: error63 });
146509
+ });
146510
+ child.once("close", (status, signal) => {
146511
+ resolve2({ status, signal });
146512
+ });
146513
+ });
146514
+ return {
146515
+ exit,
146516
+ signal: (signal) => {
146517
+ child.kill(signal);
146518
+ }
146519
+ };
146520
+ }
146521
+ };
146522
+ var realSignalPort = {
146523
+ on(signal, handler) {
146524
+ process.on(signal, handler);
146525
+ return () => {
146526
+ process.off(signal, handler);
146527
+ };
146528
+ }
146529
+ };
146530
+ var realTimerPort = {
146531
+ after(ms2) {
146532
+ let timer;
146533
+ const elapsed = new Promise((resolve2) => {
146534
+ timer = setTimeout(resolve2, ms2);
146535
+ });
146536
+ return {
146537
+ elapsed,
146538
+ cancel: () => {
146539
+ clearTimeout(timer);
146540
+ }
146541
+ };
146542
+ }
146543
+ };
146544
+ function realWatchDirectory(directory, accepts, what, log) {
146545
+ return (onChange) => {
146546
+ realFarmFs.mkdirPrivate(directory);
146547
+ const watcher = import_node_fs23.default.watch(directory, { persistent: false }, (_event, filename) => {
146548
+ if (filename === null || accepts(filename)) {
146549
+ onChange();
146550
+ }
146551
+ });
146552
+ watcher.on("error", (error63) => {
146553
+ log.warn(`agent-shim: the watch on ${what} stopped (${error63.message}); this session will not be moved or compacted when it changes`);
146554
+ watcher.close();
146555
+ });
146556
+ return () => {
146557
+ watcher.close();
146558
+ };
146559
+ };
146560
+ }
146561
+ var TERMINAL_RESET = "\x1B[?25h\x1B[?1006l\x1B[?1003l\x1B[?1002l\x1B[?1000l\x1B[?2004l\x1B[?1004l\x1B[<u\x1B[0m";
146562
+ function resetTerminal() {
146563
+ if (!process.stdout.isTTY) {
146564
+ return;
146565
+ }
146566
+ process.stdout.write(TERMINAL_RESET);
146567
+ (0, import_node_child_process10.spawnSync)("stty", ["sane"], { stdio: ["inherit", "ignore", "ignore"] });
146568
+ }
146569
+
146570
+ // src/supervise/supervise.ts
146571
+ init_spawn();
146572
+ var STOP_GRACE_MS = 5e3;
146573
+ function messageOf(error63) {
146574
+ return error63 instanceof Error ? error63.message : String(error63);
146575
+ }
146576
+ async function stopChild(deps, child) {
146577
+ child.signal("SIGTERM");
146578
+ const grace = deps.timer.after(STOP_GRACE_MS);
146579
+ const stopped = await Promise.race([child.exit.then((result2) => ({ result: result2 })), grace.elapsed.then(() => void 0)]);
146580
+ grace.cancel();
146581
+ if (stopped !== void 0) {
146582
+ return stopped.result;
146583
+ }
146584
+ child.signal("SIGKILL");
146585
+ const result = await child.exit;
146586
+ deps.resetTerminal();
146587
+ return result;
146588
+ }
146589
+ async function runChild2(deps, plan, identity, canCompact) {
146590
+ const startedMs = deps.now();
146591
+ const child = deps.spawn.spawn(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
146592
+ plan.markChildStarted();
146593
+ const state = { terminating: false, leaving: false, checking: false, wakes: 0, declined: false, lastWarning: "" };
146594
+ const stopHandlers = [
146595
+ ...["SIGHUP", "SIGTERM"].map(
146596
+ (signal) => deps.signals.on(signal, () => {
146597
+ state.terminating = true;
146598
+ child.signal(signal);
146599
+ })
146600
+ ),
146601
+ deps.signals.on("SIGINT", () => void 0)
146602
+ ];
146603
+ let depart = () => void 0;
146604
+ const departing = new Promise((resolve2) => {
146605
+ depart = resolve2;
146606
+ });
146607
+ const handleRefusal = async (hit) => {
146608
+ const outcome = await deps.decideMove({ sessionId: plan.sessionId, from: identity, contextTokens: deps.contextTokens(plan.sessionId) });
146609
+ if (outcome.kind === "move") {
146610
+ state.leaving = true;
146611
+ depart(outcome);
146612
+ } else {
146613
+ state.declined = true;
146614
+ deps.log.warn(`agent-shim: ${identity} is out of quota${hit.resetAt === void 0 ? "" : ` until ${hit.resetAt}`}, and this session stays on it: ${outcome.reason}`);
146615
+ }
146616
+ };
146617
+ const considerCompacting = (compaction) => {
146618
+ const decision = compaction.shouldCompact(identity, plan.sessionId);
146619
+ if (!decision.compact) {
146620
+ return;
146621
+ }
146622
+ const slot = compaction.acquire(identity);
146623
+ if (slot === void 0) {
146624
+ return;
146625
+ }
146626
+ if (compaction.shouldCompact(identity, plan.sessionId).compact) {
146627
+ state.leaving = true;
146628
+ depart({ kind: "compact", slot, contextTokens: decision.contextTokens, reason: decision.reason });
146629
+ } else {
146630
+ slot.release();
146631
+ }
146632
+ };
146633
+ const isLeaving = () => state.leaving;
146634
+ const check2 = async () => {
146635
+ state.wakes += 1;
146636
+ if (isLeaving() || state.checking) {
146637
+ return;
146638
+ }
146639
+ state.checking = true;
146640
+ try {
146641
+ let handled;
146642
+ do {
146643
+ handled = state.wakes;
146644
+ if (isLeaving()) {
146645
+ break;
146646
+ }
146647
+ const hit = deps.quotaHit(identity, plan.sessionId, startedMs);
146648
+ if (hit !== void 0) {
146649
+ if (!state.declined) {
146650
+ await handleRefusal(hit);
146651
+ }
146652
+ continue;
146653
+ }
146654
+ state.declined = false;
146655
+ if (canCompact && deps.compaction !== void 0) {
146656
+ considerCompacting(deps.compaction);
146657
+ }
146658
+ } while (handled !== state.wakes);
146659
+ } catch (error63) {
146660
+ const warning = `agent-shim: could not check whether ${identity} is out of quota: ${messageOf(error63)}`;
146661
+ if (warning !== state.lastWarning) {
146662
+ state.lastWarning = warning;
146663
+ deps.log.warn(warning);
146664
+ }
146665
+ } finally {
146666
+ state.checking = false;
146667
+ }
146668
+ };
146669
+ const stopWatching = deps.watchChanges(identity, () => {
146670
+ void check2();
146671
+ });
146672
+ try {
146673
+ const first = await Promise.race([child.exit.then((result2) => ({ kind: "exited", result: result2 })), departing]);
146674
+ stopWatching();
146675
+ if (first.kind === "exited") {
146676
+ return first;
146677
+ }
146678
+ deps.log.info(
146679
+ first.kind === "move" ? `agent-shim: ${identity} is out of quota; resuming session ${plan.sessionId} under ${first.to} (${first.explanation})` : `agent-shim: ${first.reason}; compacting the ${String(first.contextTokens)}-token context of session ${plan.sessionId} on ${identity}`
146680
+ );
146681
+ const result = await stopChild(deps, child);
146682
+ if (state.terminating) {
146683
+ if (first.kind === "compact") {
146684
+ first.slot.release();
146685
+ }
146686
+ return { kind: "exited", result };
146687
+ }
146688
+ return first;
146689
+ } finally {
146690
+ stopWatching();
146691
+ for (const stop of stopHandlers) {
146692
+ stop();
146693
+ }
146694
+ }
146695
+ }
146696
+ function signalExit(signal) {
146697
+ return childExitCode({ status: null, signal });
146698
+ }
146699
+ async function compactSession(deps, compaction, slot, identity, sessionId) {
146700
+ const abort = new AbortController();
146701
+ const interrupted = { signal: void 0 };
146702
+ const stopHandlers = ["SIGINT", "SIGHUP", "SIGTERM"].map(
146703
+ (signal) => deps.signals.on(signal, () => {
146704
+ interrupted.signal = signal;
146705
+ abort.abort();
146706
+ })
146707
+ );
146708
+ try {
146709
+ const result = await compaction.compact({ identity, sessionId, cwd: deps.cwd }, abort.signal);
146710
+ if (result.kind === "unchanged") {
146711
+ deps.log.info(`agent-shim: session ${sessionId} was left as it was: ${result.reason}`);
146712
+ } else {
146713
+ const sizes = result.beforeTokens === void 0 ? "" : `, ${String(result.beforeTokens)} tokens${result.afterTokens === void 0 ? "" : ` down to ${String(result.afterTokens)}`}`;
146714
+ deps.log.info(`agent-shim: compacted session ${sessionId} on ${identity}${sizes}`);
146715
+ }
146716
+ } catch (error63) {
146717
+ if (interrupted.signal === void 0) {
146718
+ deps.log.warn(`agent-shim: could not compact session ${sessionId} on ${identity}, which resumes as it was: ${messageOf(error63)}`);
146719
+ }
146720
+ } finally {
146721
+ for (const stop of stopHandlers) {
146722
+ stop();
146723
+ }
146724
+ slot.release();
146725
+ }
146726
+ compaction.markCompacted(sessionId, true);
146727
+ return interrupted.signal;
146728
+ }
146729
+ async function supervise(deps, first) {
146730
+ const { compaction } = deps;
146731
+ const base = { sessionId: first.sessionId, ...first.settings === void 0 ? {} : { settings: first.settings } };
146732
+ let launch = first;
146733
+ let compactedHere = false;
146734
+ try {
146735
+ for (let moved = false; ; moved = true) {
146736
+ const plan = deps.prepare(launch);
146737
+ const { identity } = plan.decision;
146738
+ if (identity === void 0) {
146739
+ plan.release();
146740
+ throw new Error("a supervised launch resolved no identity to supervise");
146741
+ }
146742
+ if (!moved) {
146743
+ deps.register({ pid: deps.pid, sessionId: plan.sessionId, pool: deps.pool, identity, cwd: deps.cwd, since: new Date(deps.now()).toISOString() });
146744
+ }
146745
+ let outcome;
146746
+ try {
146747
+ outcome = await runChild2(deps, plan, identity, compaction !== void 0 && !compactedHere);
146748
+ } finally {
146749
+ plan.release();
146750
+ }
146751
+ if (outcome.kind === "exited") {
146752
+ if (outcome.result.error !== void 0) {
146753
+ throw outcome.result.error;
146754
+ }
146755
+ return childExitCode(outcome.result);
146756
+ }
146757
+ if (outcome.kind === "compact") {
146758
+ const interrupted = compaction === void 0 ? void 0 : await compactSession(deps, compaction, outcome.slot, identity, plan.sessionId);
146759
+ compactedHere = true;
146760
+ if (interrupted !== void 0) {
146761
+ return signalExit(interrupted);
146762
+ }
146763
+ launch = { ...base, conversation: "resume", member: identity };
146764
+ continue;
146765
+ }
146766
+ launch = { ...base, conversation: "resume", member: outcome.to };
146767
+ const compactedOnOld = compactedHere;
146768
+ compactedHere = false;
146769
+ if (compaction !== void 0) {
146770
+ compaction.markCompacted(plan.sessionId, false);
146771
+ const slot = compactedOnOld ? void 0 : compaction.acquire(outcome.to);
146772
+ if (slot !== void 0) {
146773
+ const interrupted = await compactSession(deps, compaction, slot, outcome.to, plan.sessionId);
146774
+ compactedHere = true;
146775
+ if (interrupted !== void 0) {
146776
+ return signalExit(interrupted);
146777
+ }
146778
+ }
146779
+ }
146780
+ }
146781
+ } finally {
146782
+ deps.unregister(first.sessionId);
146783
+ }
146784
+ }
146785
+
146786
+ // src/supervise/launch.ts
146787
+ async function runSupervised(params) {
146788
+ const { paths, pool, farm, log } = params;
146789
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
146790
+ return void 0;
146791
+ }
146792
+ if (process.platform === "win32") {
146793
+ log.warn(`agent-shim: pool "${pool}" resumes on a spent quota, which needs a POSIX terminal; this launch runs unsupervised`);
146794
+ return void 0;
146795
+ }
146796
+ const first = initialConversationOf(params.passthrough, { newId: import_node_crypto25.randomUUID, latestId: () => latestConversationId(farm.fs, { claudeHome: farm.claudeHome, cwd: farm.cwd }) });
146797
+ if ("reason" in first) {
146798
+ log.warn(`agent-shim: pool "${pool}" resumes on a spent quota, but this launch runs unsupervised: ${first.reason}`);
146799
+ return void 0;
146800
+ }
146801
+ let launch = first;
146802
+ let compaction;
146803
+ const policy = params.pools[pool];
146804
+ if (policy?.compactBeforeLimit === true) {
146805
+ if (hasSettingsArgument(params.passthrough)) {
146806
+ log.warn(`agent-shim: pool "${pool}" compacts before its quota is spent, which needs --settings for its turn hooks; this launch passes its own, so it moves without compacting`);
146807
+ } else {
146808
+ launch = { ...first, settings: markHooksSettings(selfInvocation([]), paths.root, pool, first.sessionId) };
146809
+ compaction = createCompactionDeps({
146810
+ paths,
146811
+ fs: realFarmFs,
146812
+ pool,
146813
+ policy,
146814
+ pid: farm.lock.pid,
146815
+ now: farm.now,
146816
+ isRunning: farm.lock.isRunning,
146817
+ sleep: farm.lock.sleep,
146818
+ compact: createRealCompactor({ paths, spawnDaemon: params.spawnDaemon })
146819
+ });
146820
+ }
146821
+ }
146822
+ const mover = createMover({
146823
+ paths,
146824
+ fs: realFsPort,
146825
+ farmFs: realFarmFs,
146826
+ pool,
146827
+ pools: params.pools,
146828
+ cwd: farm.cwd,
146829
+ pid: farm.lock.pid,
146830
+ now: farm.now,
146831
+ isRunning: farm.lock.isRunning,
146832
+ sleep: farm.lock.sleep,
146833
+ pickMember: resolvePoolLaunch,
146834
+ log
146835
+ });
146836
+ return await supervise(
146837
+ {
146838
+ pool,
146839
+ cwd: farm.cwd,
146840
+ pid: farm.lock.pid,
146841
+ prepare: params.prepare,
146842
+ spawn: realSupervisedSpawnPort,
146843
+ signals: realSignalPort,
146844
+ timer: realTimerPort,
146845
+ watchChanges: (identity, onChange) => {
146846
+ const stopSnapshot = realWatchDirectory(paths.usageSnapshotsDir, (filename) => filename === `${identity}.json`, `${identity}'s usage`, log)(onChange);
146847
+ const stopState = compaction === void 0 ? void 0 : realWatchDirectory(stateDirOf(paths, pool), (filename) => filename.endsWith(".json"), "the pool's sessions", log)(onChange);
146848
+ return () => {
146849
+ stopSnapshot();
146850
+ stopState?.();
146851
+ };
146852
+ },
146853
+ quotaHit: (identity, sessionId, sinceMs) => quotaHitOf(realFarmFs, paths, identity, sessionId, sinceMs, farm.now()),
146854
+ decideMove: async (request7) => {
146855
+ await refreshPools({ paths, cwd: farm.cwd, poolNames: [pool], spawnDaemon: params.spawnDaemon, log: (line) => {
146856
+ log.warn(line);
146857
+ } });
146858
+ return mover(request7);
146859
+ },
146860
+ contextTokens: (sessionId) => resumedContextTokens(farm.fs, { claudeHome: farm.claudeHome, cwd: farm.cwd, passthrough: ["--resume", sessionId] }),
146861
+ ...compaction === void 0 ? {} : { compaction },
146862
+ register: (session) => {
146863
+ registerSupervised(realFarmFs, paths, session);
146864
+ },
146865
+ unregister: (sessionId) => {
146866
+ unregisterSupervised(realFarmFs, paths, pool, sessionId);
146867
+ },
146868
+ resetTerminal,
146869
+ now: farm.now,
146870
+ log
146871
+ },
146872
+ launch
146873
+ );
146874
+ }
146875
+
145940
146876
  // src/runClaude.ts
145941
146877
  init_launcher();
145942
146878
  init_argv();
@@ -146035,7 +146971,7 @@ async function runClaude(argvOverride) {
146035
146971
  spawnDaemon: spawnDetachedSupervisor,
146036
146972
  log: realLogPort.warn
146037
146973
  });
146038
- runLauncher({
146974
+ const prepareParams = {
146039
146975
  ...realPrepareLaunchParams(paths, {
146040
146976
  proc: argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride },
146041
146977
  log: realLogPort,
@@ -146044,15 +146980,32 @@ async function runClaude(argvOverride) {
146044
146980
  allowMissingConfigProfile
146045
146981
  }),
146046
146982
  // Wired here rather than in realPrepareLaunchParams because the port re-invokes this very binary: correct for the agent-shim command line, wrong for a library host whose own executable is not agent-shim.
146047
- update: realLaunchUpdatePort(paths),
146048
- spawn: realSpawnPort
146049
- });
146983
+ update: realLaunchUpdatePort(paths)
146984
+ };
146985
+ const poolName = identityDecision.pool;
146986
+ if (poolName !== void 0 && farm.pools?.[poolName]?.resumeOnLimit === true) {
146987
+ const code = await runSupervised({
146988
+ paths,
146989
+ pool: poolName,
146990
+ pools: farm.pools,
146991
+ farm: farm.runtime,
146992
+ passthrough: nativeArgv.rest,
146993
+ // The launch-time update check runs for the first launch only: its notice must not land on the terminal between a stopped child and its relaunch.
146994
+ prepare: (launch) => prepareLaunch(launch.member === void 0 ? { ...prepareParams, supervised: launch } : { ...prepareParams, update: void 0, supervised: launch }),
146995
+ spawnDaemon: spawnDetachedSupervisor,
146996
+ log: realLogPort
146997
+ });
146998
+ if (code !== void 0) {
146999
+ process.exit(code);
147000
+ }
147001
+ }
147002
+ runLauncher({ ...prepareParams, spawn: realSpawnPort });
146050
147003
  }
146051
147004
 
146052
147005
  // src/cli.ts
146053
147006
  async function main() {
146054
147007
  aliasLegacyEnv(process.env);
146055
- const invokedName = import_node_path60.default.basename(process.argv[1] ?? "agent-shim");
147008
+ const invokedName = import_node_path62.default.basename(process.argv[1] ?? "agent-shim");
146056
147009
  if (isInvokedAsClaude(invokedName)) {
146057
147010
  await runClaude();
146058
147011
  return;