claude-use 11.87.2 → 11.87.4

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
@@ -319,10 +319,10 @@ function mergeDefs(...defs) {
319
319
  function cloneDef(schema) {
320
320
  return mergeDefs(schema._zod.def);
321
321
  }
322
- function getElementAtPath(obj, path92) {
323
- if (!path92)
322
+ function getElementAtPath(obj, path98) {
323
+ if (!path98)
324
324
  return obj;
325
- return path92.reduce((acc, key) => acc?.[key], obj);
325
+ return path98.reduce((acc, key) => acc?.[key], obj);
326
326
  }
327
327
  function promiseAllObject(promisesObj) {
328
328
  const keys = Object.keys(promisesObj);
@@ -581,11 +581,11 @@ function explicitlyAborted(x3, startIndex = 0) {
581
581
  }
582
582
  return false;
583
583
  }
584
- function prefixIssues(path92, issues) {
584
+ function prefixIssues(path98, issues) {
585
585
  return issues.map((iss) => {
586
586
  var _a4;
587
587
  (_a4 = iss).path ?? (_a4.path = []);
588
- iss.path.unshift(path92);
588
+ iss.path.unshift(path98);
589
589
  return iss;
590
590
  });
591
591
  }
@@ -1118,16 +1118,16 @@ function flattenError(error63, mapper = (issue2) => issue2.message) {
1118
1118
  }
1119
1119
  function formatError(error63, mapper = (issue2) => issue2.message) {
1120
1120
  const fieldErrors = { _errors: [] };
1121
- const processError = (error64, path92 = []) => {
1121
+ const processError = (error64, path98 = []) => {
1122
1122
  for (const issue2 of error64.issues) {
1123
1123
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1124
- issue2.errors.map((issues) => processError({ issues }, [...path92, ...issue2.path]));
1124
+ issue2.errors.map((issues) => processError({ issues }, [...path98, ...issue2.path]));
1125
1125
  } else if (issue2.code === "invalid_key") {
1126
- processError({ issues: issue2.issues }, [...path92, ...issue2.path]);
1126
+ processError({ issues: issue2.issues }, [...path98, ...issue2.path]);
1127
1127
  } else if (issue2.code === "invalid_element") {
1128
- processError({ issues: issue2.issues }, [...path92, ...issue2.path]);
1128
+ processError({ issues: issue2.issues }, [...path98, ...issue2.path]);
1129
1129
  } else {
1130
- const fullpath = [...path92, ...issue2.path];
1130
+ const fullpath = [...path98, ...issue2.path];
1131
1131
  if (fullpath.length === 0) {
1132
1132
  fieldErrors._errors.push(mapper(issue2));
1133
1133
  } else {
@@ -1166,17 +1166,17 @@ function formatError(error63, mapper = (issue2) => issue2.message) {
1166
1166
  }
1167
1167
  function treeifyError(error63, mapper = (issue2) => issue2.message) {
1168
1168
  const result = { errors: [] };
1169
- const processError = (error64, path92 = []) => {
1169
+ const processError = (error64, path98 = []) => {
1170
1170
  var _a4;
1171
1171
  for (const issue2 of error64.issues) {
1172
1172
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1173
- issue2.errors.map((issues) => processError({ issues }, [...path92, ...issue2.path]));
1173
+ issue2.errors.map((issues) => processError({ issues }, [...path98, ...issue2.path]));
1174
1174
  } else if (issue2.code === "invalid_key") {
1175
- processError({ issues: issue2.issues }, [...path92, ...issue2.path]);
1175
+ processError({ issues: issue2.issues }, [...path98, ...issue2.path]);
1176
1176
  } else if (issue2.code === "invalid_element") {
1177
- processError({ issues: issue2.issues }, [...path92, ...issue2.path]);
1177
+ processError({ issues: issue2.issues }, [...path98, ...issue2.path]);
1178
1178
  } else {
1179
- const fullpath = [...path92, ...issue2.path];
1179
+ const fullpath = [...path98, ...issue2.path];
1180
1180
  if (fullpath.length === 0) {
1181
1181
  result.errors.push(mapper(issue2));
1182
1182
  continue;
@@ -1215,8 +1215,8 @@ function treeifyError(error63, mapper = (issue2) => issue2.message) {
1215
1215
  }
1216
1216
  function toDotPath(_path) {
1217
1217
  const segs = [];
1218
- const path92 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1219
- for (const seg of path92) {
1218
+ const path98 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1219
+ for (const seg of path98) {
1220
1220
  if (typeof seg === "number")
1221
1221
  segs.push(`[${seg}]`);
1222
1222
  else if (typeof seg === "symbol")
@@ -19248,13 +19248,13 @@ function resolveRef(ref, ctx) {
19248
19248
  if (!ref.startsWith("#")) {
19249
19249
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
19250
19250
  }
19251
- const path92 = ref.slice(1).split("/").filter(Boolean);
19252
- if (path92.length === 0) {
19251
+ const path98 = ref.slice(1).split("/").filter(Boolean);
19252
+ if (path98.length === 0) {
19253
19253
  return ctx.rootSchema;
19254
19254
  }
19255
19255
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
19256
- if (path92[0] === defsKey) {
19257
- const key = path92[1] === void 0 ? void 0 : decodeJSONPointerSegment(path92[1]);
19256
+ if (path98[0] === defsKey) {
19257
+ const key = path98[1] === void 0 ? void 0 : decodeJSONPointerSegment(path98[1]);
19258
19258
  if (!key || !ctx.defs[key]) {
19259
19259
  throw new Error(`Reference not found: ${ref}`);
19260
19260
  }
@@ -23761,42 +23761,42 @@ var require_defaults = __commonJS({
23761
23761
  var require_env_paths = __commonJS({
23762
23762
  "node_modules/.pnpm/env-paths@2.2.1/node_modules/env-paths/index.js"(exports2, module2) {
23763
23763
  "use strict";
23764
- var path92 = require("path");
23764
+ var path98 = require("path");
23765
23765
  var os24 = require("os");
23766
23766
  var homedir = os24.homedir();
23767
- var tmpdir = os24.tmpdir();
23767
+ var tmpdir2 = os24.tmpdir();
23768
23768
  var { env } = process;
23769
23769
  var macos = (name) => {
23770
- const library = path92.join(homedir, "Library");
23770
+ const library = path98.join(homedir, "Library");
23771
23771
  return {
23772
- data: path92.join(library, "Application Support", name),
23773
- config: path92.join(library, "Preferences", name),
23774
- cache: path92.join(library, "Caches", name),
23775
- log: path92.join(library, "Logs", name),
23776
- temp: path92.join(tmpdir, name)
23772
+ data: path98.join(library, "Application Support", name),
23773
+ config: path98.join(library, "Preferences", name),
23774
+ cache: path98.join(library, "Caches", name),
23775
+ log: path98.join(library, "Logs", name),
23776
+ temp: path98.join(tmpdir2, name)
23777
23777
  };
23778
23778
  };
23779
23779
  var windows = (name) => {
23780
- const appData = env.APPDATA || path92.join(homedir, "AppData", "Roaming");
23781
- const localAppData = env.LOCALAPPDATA || path92.join(homedir, "AppData", "Local");
23780
+ const appData = env.APPDATA || path98.join(homedir, "AppData", "Roaming");
23781
+ const localAppData = env.LOCALAPPDATA || path98.join(homedir, "AppData", "Local");
23782
23782
  return {
23783
23783
  // Data/config/cache/log are invented by me as Windows isn't opinionated about this
23784
- data: path92.join(localAppData, name, "Data"),
23785
- config: path92.join(appData, name, "Config"),
23786
- cache: path92.join(localAppData, name, "Cache"),
23787
- log: path92.join(localAppData, name, "Log"),
23788
- temp: path92.join(tmpdir, name)
23784
+ data: path98.join(localAppData, name, "Data"),
23785
+ config: path98.join(appData, name, "Config"),
23786
+ cache: path98.join(localAppData, name, "Cache"),
23787
+ log: path98.join(localAppData, name, "Log"),
23788
+ temp: path98.join(tmpdir2, name)
23789
23789
  };
23790
23790
  };
23791
23791
  var linux = (name) => {
23792
- const username = path92.basename(homedir);
23792
+ const username = path98.basename(homedir);
23793
23793
  return {
23794
- data: path92.join(env.XDG_DATA_HOME || path92.join(homedir, ".local", "share"), name),
23795
- config: path92.join(env.XDG_CONFIG_HOME || path92.join(homedir, ".config"), name),
23796
- cache: path92.join(env.XDG_CACHE_HOME || path92.join(homedir, ".cache"), name),
23794
+ data: path98.join(env.XDG_DATA_HOME || path98.join(homedir, ".local", "share"), name),
23795
+ config: path98.join(env.XDG_CONFIG_HOME || path98.join(homedir, ".config"), name),
23796
+ cache: path98.join(env.XDG_CACHE_HOME || path98.join(homedir, ".cache"), name),
23797
23797
  // https://wiki.debian.org/XDGBaseDirectorySpecification#state
23798
- log: path92.join(env.XDG_STATE_HOME || path92.join(homedir, ".local", "state"), name),
23799
- temp: path92.join(tmpdir, username, name)
23798
+ log: path98.join(env.XDG_STATE_HOME || path98.join(homedir, ".local", "state"), name),
23799
+ temp: path98.join(tmpdir2, username, name)
23800
23800
  };
23801
23801
  };
23802
23802
  var envPaths = (name, options) => {
@@ -23864,11 +23864,11 @@ var require_util = __commonJS({
23864
23864
  return result;
23865
23865
  }
23866
23866
  exports2.emplace = emplace;
23867
- function getPropertyByPath(source, path92) {
23868
- if (typeof path92 === "string" && Object.prototype.hasOwnProperty.call(source, path92)) {
23869
- return source[path92];
23867
+ function getPropertyByPath(source, path98) {
23868
+ if (typeof path98 === "string" && Object.prototype.hasOwnProperty.call(source, path98)) {
23869
+ return source[path98];
23870
23870
  }
23871
- const parsedPath = typeof path92 === "string" ? path92.split(".") : path92;
23871
+ const parsedPath = typeof path98 === "string" ? path98.split(".") : path98;
23872
23872
  return parsedPath.reduce((previous, key) => {
23873
23873
  if (previous === void 0) {
23874
23874
  return previous;
@@ -23891,9 +23891,9 @@ var require_util = __commonJS({
23891
23891
  return Object.fromEntries(Object.entries(options).filter(([, value3]) => value3 !== void 0));
23892
23892
  }
23893
23893
  exports2.removeUndefinedValuesFromObject = removeUndefinedValuesFromObject;
23894
- async function isDirectory(path92) {
23894
+ async function isDirectory(path98) {
23895
23895
  try {
23896
- const stat = await fs_1.promises.stat(path92);
23896
+ const stat = await fs_1.promises.stat(path98);
23897
23897
  return stat.isDirectory();
23898
23898
  } catch (e10) {
23899
23899
  if (e10.code === "ENOENT") {
@@ -23903,9 +23903,9 @@ var require_util = __commonJS({
23903
23903
  }
23904
23904
  }
23905
23905
  exports2.isDirectory = isDirectory;
23906
- function isDirectorySync(path92) {
23906
+ function isDirectorySync(path98) {
23907
23907
  try {
23908
- const stat = fs_1.default.statSync(path92);
23908
+ const stat = fs_1.default.statSync(path98);
23909
23909
  return stat.isDirectory();
23910
23910
  } catch (e10) {
23911
23911
  if (e10.code === "ENOENT") {
@@ -24003,7 +24003,7 @@ var require_ExplorerBase = __commonJS({
24003
24003
  const idx = importStack.indexOf(fullPath);
24004
24004
  if (idx !== -1) {
24005
24005
  throw new Error(`Circular import detected:
24006
- ${[...importStack, fullPath].map((path92, i10) => `${i10 + 1}. ${path92}`).join("\n")} (same as ${idx + 1}.)`);
24006
+ ${[...importStack, fullPath].map((path98, i10) => `${i10 + 1}. ${path98}`).join("\n")} (same as ${idx + 1}.)`);
24007
24007
  }
24008
24008
  }
24009
24009
  }
@@ -24191,9 +24191,9 @@ var require_Explorer = __commonJS({
24191
24191
  throw error63;
24192
24192
  }
24193
24193
  }
24194
- async #fileExists(path92) {
24194
+ async #fileExists(path98) {
24195
24195
  try {
24196
- await promises_1.default.stat(path92);
24196
+ await promises_1.default.stat(path98);
24197
24197
  return true;
24198
24198
  } catch (e10) {
24199
24199
  return false;
@@ -24353,9 +24353,9 @@ var require_ExplorerSync = __commonJS({
24353
24353
  throw error63;
24354
24354
  }
24355
24355
  }
24356
- #fileExists(path92) {
24356
+ #fileExists(path98) {
24357
24357
  try {
24358
- fs_1.default.statSync(path92);
24358
+ fs_1.default.statSync(path98);
24359
24359
  return true;
24360
24360
  } catch (e10) {
24361
24361
  return false;
@@ -24479,7 +24479,7 @@ var require_dist = __commonJS({
24479
24479
  };
24480
24480
  }
24481
24481
  function getResolvedSearchPlaces(moduleName, toolDefinedSearchPlaces, userConfiguredOptions) {
24482
- const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path92) => path92.replace("{name}", moduleName));
24482
+ const userConfiguredSearchPlaces = userConfiguredOptions.searchPlaces?.map((path98) => path98.replace("{name}", moduleName));
24483
24483
  if (userConfiguredOptions.mergeSearchPlaces) {
24484
24484
  return [...userConfiguredSearchPlaces ?? [], ...toolDefinedSearchPlaces];
24485
24485
  }
@@ -24609,7 +24609,7 @@ function parseIgnoringUnrecognisedKeys(schema, raw) {
24609
24609
  return second.success ? { success: true, data: second.data, ignored } : { success: false, issues: second.error.issues };
24610
24610
  }
24611
24611
  function describeIgnoredKeys(filePath, ignored) {
24612
- const places = ignored.map(({ path: path92, keys }) => `${path92.length === 0 ? "" : `${path92.map(String).join(".")}.`}${keys.join(", ")}`);
24612
+ const places = ignored.map(({ path: path98, keys }) => `${path98.length === 0 ? "" : `${path98.map(String).join(".")}.`}${keys.join(", ")}`);
24613
24613
  return `${filePath} has settings this version of agent-shim does not know and ignores: ${places.join("; ")}. A newer release may read them.`;
24614
24614
  }
24615
24615
  function noteIgnoredKeys(filePath, ignored) {
@@ -24631,9 +24631,9 @@ function restoreIgnoredKeys(filePath, value3) {
24631
24631
  return value3;
24632
24632
  }
24633
24633
  const restored2 = structuredClone(value3);
24634
- for (const { path: path92, values } of ignored) {
24634
+ for (const { path: path98, values } of ignored) {
24635
24635
  let holder = restored2;
24636
- for (const step2 of path92) {
24636
+ for (const step2 of path98) {
24637
24637
  holder = isRecord(holder) ? holder[step2] : void 0;
24638
24638
  }
24639
24639
  if (isRecord(holder)) {
@@ -28811,8 +28811,8 @@ var require_utils = __commonJS({
28811
28811
  }
28812
28812
  return output2;
28813
28813
  };
28814
- exports2.basename = (path92, { windows } = {}) => {
28815
- const segs = path92.split(windows ? /[\\/]/ : "/");
28814
+ exports2.basename = (path98, { windows } = {}) => {
28815
+ const segs = path98.split(windows ? /[\\/]/ : "/");
28816
28816
  const last = segs[segs.length - 1];
28817
28817
  if (last === "") {
28818
28818
  return segs[segs.length - 2];
@@ -32968,11 +32968,30 @@ var init_categories_default = __esm({
32968
32968
  });
32969
32969
 
32970
32970
  // src/config/classify.ts
32971
- function isExactPattern(pattern) {
32972
- return !GLOB_METACHARACTERS.test(pattern);
32971
+ function literalClassificationPattern(name) {
32972
+ return GLOB_METACHARACTERS.test(name) ? name.replace(/[\\*?[\]{}!()]/g, "\\$&") : name;
32973
+ }
32974
+ function literalOf(pattern) {
32975
+ if (!GLOB_METACHARACTERS.test(pattern)) return pattern;
32976
+ let literal3 = "";
32977
+ for (let index = 0; index < pattern.length; index += 1) {
32978
+ const character = pattern[index];
32979
+ if (character === void 0) continue;
32980
+ const next = pattern[index + 1];
32981
+ if (character === "\\" && next !== void 0 && (next === "\\" || GLOB_METACHARACTERS.test(next))) {
32982
+ literal3 += next;
32983
+ index += 1;
32984
+ } else if (GLOB_METACHARACTERS.test(character)) {
32985
+ return void 0;
32986
+ } else {
32987
+ literal3 += character;
32988
+ }
32989
+ }
32990
+ return literal3;
32973
32991
  }
32974
32992
  function compile2(pattern, category, source, ordinal) {
32975
- const isExact = isExactPattern(pattern);
32993
+ const literal3 = literalOf(pattern);
32994
+ const isExact = literal3 !== void 0;
32976
32995
  const matcher = (0, import_picomatch2.default)(pattern, { dot: true, nocase: false });
32977
32996
  return {
32978
32997
  pattern,
@@ -32980,7 +32999,7 @@ function compile2(pattern, category, source, ordinal) {
32980
32999
  source,
32981
33000
  isExact,
32982
33001
  ordinal,
32983
- matches: isExact ? (name) => name === pattern : (name) => matcher(name)
33002
+ matches: isExact ? (name) => name === literal3 : (name) => matcher(name)
32984
33003
  };
32985
33004
  }
32986
33005
  function compileClassificationPatterns(defaults, overlay2) {
@@ -33384,9 +33403,9 @@ var init_identity = __esm({
33384
33403
  });
33385
33404
 
33386
33405
  // src/statusline/keys.ts
33387
- function valueAt(source, path92) {
33406
+ function valueAt(source, path98) {
33388
33407
  let current = source;
33389
- for (const part of path92) {
33408
+ for (const part of path98) {
33390
33409
  if (!isPlainObject2(current)) {
33391
33410
  return void 0;
33392
33411
  }
@@ -33394,14 +33413,14 @@ function valueAt(source, path92) {
33394
33413
  }
33395
33414
  return current;
33396
33415
  }
33397
- function acceptsNull(path92) {
33398
- const layer = path92.reduceRight((inner, part) => ({ [part]: inner }), null);
33416
+ function acceptsNull(path98) {
33417
+ const layer = path98.reduceRight((inner, part) => ({ [part]: inner }), null);
33399
33418
  return StatuslineSchema.safeParse(layer).success;
33400
33419
  }
33401
- function keyOf(path92, declared) {
33420
+ function keyOf(path98, declared) {
33402
33421
  const optional2 = declared instanceof external_exports.ZodOptional;
33403
33422
  const leaf = optional2 ? declared.unwrap() : declared;
33404
- const common = { path: path92.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path92), optional: optional2, unsettable: acceptsNull(path92) };
33423
+ const common = { path: path98.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path98), optional: optional2, unsettable: acceptsNull(path98) };
33405
33424
  if (leaf instanceof external_exports.ZodNumber) {
33406
33425
  return { ...common, kind: "integer", choices: [] };
33407
33426
  }
@@ -33426,7 +33445,7 @@ function keyOf(path92, declared) {
33426
33445
  if (leaf instanceof external_exports.ZodArray && leaf.element instanceof external_exports.ZodString) {
33427
33446
  return { ...common, kind: "textList", choices: [] };
33428
33447
  }
33429
- throw new TypeError(`statusline setting ${path92.join(".")} has a kind the key listing does not describe`);
33448
+ throw new TypeError(`statusline setting ${path98.join(".")} has a kind the key listing does not describe`);
33430
33449
  }
33431
33450
  function walk(shape, prefix) {
33432
33451
  return Object.entries(shape).flatMap(([name, schema]) => schema instanceof external_exports.ZodObject ? walk(schema.shape, [...prefix, name]) : [keyOf([...prefix, name], schema)]);
@@ -33457,14 +33476,14 @@ var init_keys = __esm({
33457
33476
  });
33458
33477
 
33459
33478
  // src/statusline/change.ts
33460
- function keyNamed(path92) {
33461
- const found = statuslineKeys().find((key) => key.path === path92);
33479
+ function keyNamed(path98) {
33480
+ const found = statuslineKeys().find((key) => key.path === path98);
33462
33481
  if (found === void 0) {
33463
- throw new UsageError(`"${path92}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
33482
+ throw new UsageError(`"${path98}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
33464
33483
  }
33465
33484
  return found;
33466
33485
  }
33467
- function textListOf(path92, raw) {
33486
+ function textListOf(path98, raw) {
33468
33487
  if (raw === "") {
33469
33488
  return [];
33470
33489
  }
@@ -33472,10 +33491,10 @@ function textListOf(path92, raw) {
33472
33491
  try {
33473
33492
  parsed = JSON.parse(raw);
33474
33493
  } catch {
33475
- throw new UsageError(`${path92}: "${raw}" is not a JSON array of strings such as ["git","describe"].`);
33494
+ throw new UsageError(`${path98}: "${raw}" is not a JSON array of strings such as ["git","describe"].`);
33476
33495
  }
33477
33496
  if (!Array.isArray(parsed) || parsed.some((item) => typeof item !== "string")) {
33478
- throw new UsageError(`${path92}: "${raw}" is not a JSON array of strings such as ["git","describe"].`);
33497
+ throw new UsageError(`${path98}: "${raw}" is not a JSON array of strings such as ["git","describe"].`);
33479
33498
  }
33480
33499
  return parsed;
33481
33500
  }
@@ -33484,42 +33503,42 @@ function parseStatuslineAssignment(text5) {
33484
33503
  if (split < 1) {
33485
33504
  throw new UsageError(`"${text5}" is not <setting>=<value>.`);
33486
33505
  }
33487
- const path92 = text5.slice(0, split);
33506
+ const path98 = text5.slice(0, split);
33488
33507
  const raw = text5.slice(split + 1);
33489
- const key = keyNamed(path92);
33508
+ const key = keyNamed(path98);
33490
33509
  if (key.unsettable && raw === UNSET_WORD) {
33491
- return { path: path92, value: null };
33510
+ return { path: path98, value: null };
33492
33511
  }
33493
33512
  switch (key.kind) {
33494
33513
  case "integer": {
33495
33514
  const number6 = Number(raw);
33496
33515
  if (raw.trim() === "" || !Number.isFinite(number6)) {
33497
- throw new UsageError(`${path92}: "${raw}" is not a number.`);
33516
+ throw new UsageError(`${path98}: "${raw}" is not a number.`);
33498
33517
  }
33499
- return { path: path92, value: number6 };
33518
+ return { path: path98, value: number6 };
33500
33519
  }
33501
33520
  case "boolean":
33502
33521
  if (raw !== "true" && raw !== "false") {
33503
- throw new UsageError(`${path92}: "${raw}" is not true or false.`);
33522
+ throw new UsageError(`${path98}: "${raw}" is not true or false.`);
33504
33523
  }
33505
- return { path: path92, value: raw === "true" };
33524
+ return { path: path98, value: raw === "true" };
33506
33525
  case "text":
33507
33526
  case "choice":
33508
- return { path: path92, value: raw };
33527
+ return { path: path98, value: raw };
33509
33528
  case "colour":
33510
- return { path: path92, value: /^\d+$/.test(raw) ? Number(raw) : raw };
33529
+ return { path: path98, value: /^\d+$/.test(raw) ? Number(raw) : raw };
33511
33530
  case "list":
33512
- return { path: path92, value: raw === "" ? [] : raw.split(",") };
33531
+ return { path: path98, value: raw === "" ? [] : raw.split(",") };
33513
33532
  case "groups":
33514
- return { path: path92, value: raw === "" ? [] : raw.split(";").map((group) => group.split(",")) };
33533
+ return { path: path98, value: raw === "" ? [] : raw.split(";").map((group) => group.split(",")) };
33515
33534
  case "textList":
33516
- return { path: path92, value: textListOf(path92, raw) };
33535
+ return { path: path98, value: textListOf(path98, raw) };
33517
33536
  default:
33518
33537
  return key.kind;
33519
33538
  }
33520
33539
  }
33521
- function setAt(target, path92, value3) {
33522
- const [head, ...rest] = path92;
33540
+ function setAt(target, path98, value3) {
33541
+ const [head, ...rest] = path98;
33523
33542
  if (head === void 0) {
33524
33543
  return;
33525
33544
  }
@@ -33532,8 +33551,8 @@ function setAt(target, path92, value3) {
33532
33551
  target[head] = next;
33533
33552
  setAt(next, rest, value3);
33534
33553
  }
33535
- function removeAt(target, path92) {
33536
- const [head, ...rest] = path92;
33554
+ function removeAt(target, path98) {
33555
+ const [head, ...rest] = path98;
33537
33556
  if (head === void 0) {
33538
33557
  return;
33539
33558
  }
@@ -33551,13 +33570,13 @@ function removeAt(target, path92) {
33551
33570
  }
33552
33571
  function applyStatuslineChange(existing, change) {
33553
33572
  const draft = structuredClone(existing ?? {});
33554
- for (const [path92, value3] of Object.entries(change.set ?? {})) {
33555
- keyNamed(path92);
33556
- setAt(draft, path92.split("."), value3);
33573
+ for (const [path98, value3] of Object.entries(change.set ?? {})) {
33574
+ keyNamed(path98);
33575
+ setAt(draft, path98.split("."), value3);
33557
33576
  }
33558
- for (const path92 of change.unset ?? []) {
33559
- keyNamed(path92);
33560
- removeAt(draft, path92.split("."));
33577
+ for (const path98 of change.unset ?? []) {
33578
+ keyNamed(path98);
33579
+ removeAt(draft, path98.split("."));
33561
33580
  }
33562
33581
  const result = StatuslineSchema.safeParse(draft);
33563
33582
  if (!result.success) {
@@ -33795,19 +33814,19 @@ function writePools(paths, pools) {
33795
33814
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
33796
33815
  }
33797
33816
  function poolCycleOf(pools, name) {
33798
- const walk3 = (current, path92) => {
33817
+ const walk3 = (current, path98) => {
33799
33818
  for (const entry of pools[current]?.identities ?? []) {
33800
33819
  const nested = poolNameOf(poolMemberIdentity(entry));
33801
33820
  if (nested === void 0) {
33802
33821
  continue;
33803
33822
  }
33804
33823
  if (nested === name) {
33805
- return [...path92, nested];
33824
+ return [...path98, nested];
33806
33825
  }
33807
- if (path92.includes(nested)) {
33826
+ if (path98.includes(nested)) {
33808
33827
  continue;
33809
33828
  }
33810
- const found = walk3(nested, [...path92, nested]);
33829
+ const found = walk3(nested, [...path98, nested]);
33811
33830
  if (found !== void 0) {
33812
33831
  return found;
33813
33832
  }
@@ -33978,7 +33997,7 @@ var init_schema2 = __esm({
33978
33997
  endpoint: external_exports.string(),
33979
33998
  /** The model the response named. */
33980
33999
  model: external_exports.string().optional(),
33981
- /** The model name the session asked for, when a routing layer chose among alternatives for it (a virtual model's or a tier alias's selection) and served the request under a different name. Absent when the session's own name reached the provider unchanged. */
34000
+ /** The model the session requested when a routing layer chose a different model, or when no response model was available to compare it with. Absent when the response confirms that the requested name was served unchanged. */
33982
34001
  requestedModel: external_exports.string().optional(),
33983
34002
  /** The distinct providers the choice could have landed on, present only when there was more than one, so a reader can tell a choice that crossed providers from one that stayed inside a single provider's lineup. */
33984
34003
  candidateProviders: external_exports.array(external_exports.string()).optional(),
@@ -36198,11 +36217,11 @@ function identifyRequest(headers) {
36198
36217
  function directOrigin2(port) {
36199
36218
  return `http://127.0.0.1:${String(port)}`;
36200
36219
  }
36201
- function parseProviderPath(path92) {
36202
- if (!path92.startsWith(PROVIDER_PATH_PREFIX)) {
36220
+ function parseProviderPath(path98) {
36221
+ if (!path98.startsWith(PROVIDER_PATH_PREFIX)) {
36203
36222
  return void 0;
36204
36223
  }
36205
- const tail = path92.slice(PROVIDER_PATH_PREFIX.length);
36224
+ const tail = path98.slice(PROVIDER_PATH_PREFIX.length);
36206
36225
  const slash = tail.indexOf("/");
36207
36226
  if (slash <= 0) {
36208
36227
  return void 0;
@@ -36538,12 +36557,12 @@ function decoderFor(encoding) {
36538
36557
  return void 0;
36539
36558
  }
36540
36559
  }
36541
- function destinationOf(path92, sessionProvider) {
36542
- const scoped = parseProviderPath(path92);
36560
+ function destinationOf(path98, sessionProvider) {
36561
+ const scoped = parseProviderPath(path98);
36543
36562
  if (scoped !== void 0) {
36544
36563
  return { provider: scoped.provider, endpoint: scoped.rest };
36545
36564
  }
36546
- return { provider: sessionProvider ?? ANTHROPIC_PROVIDER, endpoint: path92 };
36565
+ return { provider: sessionProvider ?? ANTHROPIC_PROVIDER, endpoint: path98 };
36547
36566
  }
36548
36567
  function modelChoiceOf(event, servedModel, provider) {
36549
36568
  if (event.modelChoice !== void 0) return event.modelChoice;
@@ -36554,6 +36573,7 @@ function buildRecord(event, context) {
36554
36573
  const { scan } = context;
36555
36574
  const { provider, endpoint } = destinationOf(event.servedPath, event.session.provider);
36556
36575
  const choice = modelChoiceOf(event, scan?.model, provider);
36576
+ const requestedModel = choice?.requested ?? (scan?.model === void 0 ? event.requestedModel : void 0);
36557
36577
  const rateLimitHeaders = rateLimitHeadersOf(event.headers);
36558
36578
  const limit = classifyLimit({ status: event.status, headers: rateLimitHeaders ?? {}, error: scan?.error, nowMs: context.endedAt });
36559
36579
  const requestId = headerValue(event.headers, "request-id");
@@ -36571,7 +36591,7 @@ function buildRecord(event, context) {
36571
36591
  method: event.method,
36572
36592
  endpoint,
36573
36593
  ...scan?.model === void 0 ? {} : { model: scan.model },
36574
- ...choice === void 0 ? {} : { requestedModel: choice.requested },
36594
+ ...requestedModel === void 0 ? {} : { requestedModel },
36575
36595
  ...choice !== void 0 && choice.providers.length > 1 ? { candidateProviders: [...choice.providers] } : {},
36576
36596
  status: event.status,
36577
36597
  latencyMs: Math.max(0, Math.round(context.headAt - event.receivedAt)),
@@ -38709,7 +38729,7 @@ var init_projects = __esm({
38709
38729
  });
38710
38730
 
38711
38731
  // src/resolve/match.ts
38712
- function isExactPattern2(pattern) {
38732
+ function isExactPattern(pattern) {
38713
38733
  return !GLOB_METACHARACTERS2.test(pattern);
38714
38734
  }
38715
38735
  function literalPrefixOf(pattern) {
@@ -38936,7 +38956,7 @@ function flattenLayers(layers, options) {
38936
38956
  ...unpacked.when === void 0 ? {} : { when: unpacked.when },
38937
38957
  layer: layer.id,
38938
38958
  ordinal,
38939
- isExact: isExactPattern2(pattern),
38959
+ isExact: isExactPattern(pattern),
38940
38960
  literalPrefix: literalPrefixOf(pattern),
38941
38961
  segmentCount: pattern.split("/").filter((segment) => segment !== "").length,
38942
38962
  matches: compileMatcher(pattern)
@@ -40739,8 +40759,8 @@ function parseConnectTarget(authority) {
40739
40759
  }
40740
40760
  return { host, port };
40741
40761
  }
40742
- function servedByPipeline(path92) {
40743
- return path92?.startsWith(ROUTED_PATH_PREFIX) === true;
40762
+ function servedByPipeline(path98) {
40763
+ return path98?.startsWith(ROUTED_PATH_PREFIX) === true;
40744
40764
  }
40745
40765
  function forwardableHeaders(headers) {
40746
40766
  const connectionTokens = new Set(
@@ -41960,7 +41980,7 @@ var init_package = __esm({
41960
41980
  "package.json"() {
41961
41981
  package_default = {
41962
41982
  name: "claude-use",
41963
- version: "11.87.2",
41983
+ version: "11.87.4",
41964
41984
  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.",
41965
41985
  license: "MIT",
41966
41986
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -43295,14 +43315,14 @@ var require_util2 = __commonJS({
43295
43315
  }
43296
43316
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
43297
43317
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
43298
- let path92 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
43318
+ let path98 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
43299
43319
  if (origin[origin.length - 1] === "/") {
43300
43320
  origin = origin.slice(0, origin.length - 1);
43301
43321
  }
43302
- if (path92 && path92[0] !== "/") {
43303
- path92 = `/${path92}`;
43322
+ if (path98 && path98[0] !== "/") {
43323
+ path98 = `/${path98}`;
43304
43324
  }
43305
- return new URL(`${origin}${path92}`);
43325
+ return new URL(`${origin}${path98}`);
43306
43326
  }
43307
43327
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
43308
43328
  throw new InvalidArgumentError2("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -44123,9 +44143,9 @@ var require_diagnostics = __commonJS({
44123
44143
  "undici:client:sendHeaders",
44124
44144
  (evt) => {
44125
44145
  const {
44126
- request: { method, path: path92, origin }
44146
+ request: { method, path: path98, origin }
44127
44147
  } = evt;
44128
- debugLog("sending request to %s %s%s", method, origin, path92);
44148
+ debugLog("sending request to %s %s%s", method, origin, path98);
44129
44149
  }
44130
44150
  );
44131
44151
  }
@@ -44143,14 +44163,14 @@ var require_diagnostics = __commonJS({
44143
44163
  "undici:request:headers",
44144
44164
  (evt) => {
44145
44165
  const {
44146
- request: { method, path: path92, origin },
44166
+ request: { method, path: path98, origin },
44147
44167
  response: { statusCode }
44148
44168
  } = evt;
44149
44169
  debugLog(
44150
44170
  "received response to %s %s%s - HTTP %d",
44151
44171
  method,
44152
44172
  origin,
44153
- path92,
44173
+ path98,
44154
44174
  statusCode
44155
44175
  );
44156
44176
  }
@@ -44159,23 +44179,23 @@ var require_diagnostics = __commonJS({
44159
44179
  "undici:request:trailers",
44160
44180
  (evt) => {
44161
44181
  const {
44162
- request: { method, path: path92, origin }
44182
+ request: { method, path: path98, origin }
44163
44183
  } = evt;
44164
- debugLog("trailers received from %s %s%s", method, origin, path92);
44184
+ debugLog("trailers received from %s %s%s", method, origin, path98);
44165
44185
  }
44166
44186
  );
44167
44187
  diagnosticsChannel.subscribe(
44168
44188
  "undici:request:error",
44169
44189
  (evt) => {
44170
44190
  const {
44171
- request: { method, path: path92, origin },
44191
+ request: { method, path: path98, origin },
44172
44192
  error: error63
44173
44193
  } = evt;
44174
44194
  debugLog(
44175
44195
  "request to %s %s%s errored - %s",
44176
44196
  method,
44177
44197
  origin,
44178
- path92,
44198
+ path98,
44179
44199
  error63.message
44180
44200
  );
44181
44201
  }
@@ -44290,7 +44310,7 @@ var require_request = __commonJS({
44290
44310
  var kHandler = /* @__PURE__ */ Symbol("handler");
44291
44311
  var Request2 = class {
44292
44312
  constructor(origin, {
44293
- path: path92,
44313
+ path: path98,
44294
44314
  method,
44295
44315
  body,
44296
44316
  headers,
@@ -44307,11 +44327,11 @@ var require_request = __commonJS({
44307
44327
  maxRedirections,
44308
44328
  typeOfService
44309
44329
  }, handler) {
44310
- if (typeof path92 !== "string") {
44330
+ if (typeof path98 !== "string") {
44311
44331
  throw new InvalidArgumentError2("path must be a string");
44312
- } else if (path92[0] !== "/" && !(path92.startsWith("http://") || path92.startsWith("https://")) && method !== "CONNECT") {
44332
+ } else if (path98[0] !== "/" && !(path98.startsWith("http://") || path98.startsWith("https://")) && method !== "CONNECT") {
44313
44333
  throw new InvalidArgumentError2("path must be an absolute URL or start with a slash");
44314
- } else if (invalidPathRegex.test(path92)) {
44334
+ } else if (invalidPathRegex.test(path98)) {
44315
44335
  throw new InvalidArgumentError2("invalid request path");
44316
44336
  }
44317
44337
  if (typeof method !== "string") {
@@ -44386,7 +44406,7 @@ var require_request = __commonJS({
44386
44406
  this.completed = false;
44387
44407
  this.aborted = false;
44388
44408
  this.upgrade = upgrade || null;
44389
- this.path = query ? serializePathWithQuery(path92, query) : path92;
44409
+ this.path = query ? serializePathWithQuery(path98, query) : path98;
44390
44410
  this.origin = origin;
44391
44411
  this.protocol = getProtocolFromUrlString(origin);
44392
44412
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
@@ -49611,7 +49631,7 @@ var require_client_h1 = __commonJS({
49611
49631
  return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT";
49612
49632
  }
49613
49633
  function writeH1(client, request7) {
49614
- const { method, path: path92, host, upgrade, blocking, reset } = request7;
49634
+ const { method, path: path98, host, upgrade, blocking, reset } = request7;
49615
49635
  let { body, headers, contentLength } = request7;
49616
49636
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
49617
49637
  if (util2.isFormDataLike(body)) {
@@ -49689,7 +49709,7 @@ var require_client_h1 = __commonJS({
49689
49709
  if (socket.setTypeOfService) {
49690
49710
  socket.setTypeOfService(request7.typeOfService);
49691
49711
  }
49692
- let header = `${method} ${path92} HTTP/1.1\r
49712
+ let header = `${method} ${path98} HTTP/1.1\r
49693
49713
  `;
49694
49714
  if (typeof host === "string") {
49695
49715
  header += `host: ${host}\r
@@ -50040,7 +50060,7 @@ var require_client_h2 = __commonJS({
50040
50060
  "node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/dispatcher/client-h2.js"(exports2, module2) {
50041
50061
  "use strict";
50042
50062
  var assert2 = require("node:assert");
50043
- var { pipeline } = require("node:stream");
50063
+ var { pipeline: pipeline2 } = require("node:stream");
50044
50064
  var util2 = require_util2();
50045
50065
  var {
50046
50066
  RequestContentLengthMismatchError,
@@ -50366,7 +50386,7 @@ var require_client_h2 = __commonJS({
50366
50386
  const headersTimeout = request7.headersTimeout ?? client[kHeadersTimeout];
50367
50387
  const bodyTimeout = request7.bodyTimeout ?? client[kBodyTimeout];
50368
50388
  const session = client[kHTTP2Session];
50369
- const { method, path: path92, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
50389
+ const { method, path: path98, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request7;
50370
50390
  let { body } = request7;
50371
50391
  if (upgrade != null && upgrade !== "websocket") {
50372
50392
  util2.errorRequest(client, request7, new InvalidArgumentError2(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
@@ -50435,7 +50455,7 @@ var require_client_h2 = __commonJS({
50435
50455
  }
50436
50456
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
50437
50457
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
50438
- headers[HTTP2_HEADER_PATH] = path92;
50458
+ headers[HTTP2_HEADER_PATH] = path98;
50439
50459
  if (protocol === "ws:" || protocol === "wss:") {
50440
50460
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
50441
50461
  } else {
@@ -50487,7 +50507,7 @@ var require_client_h2 = __commonJS({
50487
50507
  stream.setTimeout(headersTimeout);
50488
50508
  return true;
50489
50509
  }
50490
- headers[HTTP2_HEADER_PATH] = path92;
50510
+ headers[HTTP2_HEADER_PATH] = path98;
50491
50511
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
50492
50512
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
50493
50513
  if (body && typeof body.read === "function") {
@@ -50712,7 +50732,7 @@ var require_client_h2 = __commonJS({
50712
50732
  }
50713
50733
  function writeStream(abort, socket, expectsPayload, h2stream, body, client, request7, contentLength) {
50714
50734
  assert2(contentLength !== 0 || client[kRunning] === 0, "stream body cannot be pipelined");
50715
- const pipe2 = pipeline(
50735
+ const pipe2 = pipeline2(
50716
50736
  body,
50717
50737
  h2stream,
50718
50738
  (err) => {
@@ -52843,10 +52863,10 @@ var require_proxy_agent = __commonJS({
52843
52863
  };
52844
52864
  const {
52845
52865
  origin,
52846
- path: path92 = "/",
52866
+ path: path98 = "/",
52847
52867
  headers = {}
52848
52868
  } = opts;
52849
- opts.path = origin + path92;
52869
+ opts.path = origin + path98;
52850
52870
  if (!("host" in headers) && !("Host" in headers)) {
52851
52871
  const { host } = new URL(origin);
52852
52872
  headers.host = host;
@@ -54626,7 +54646,7 @@ var require_api_pipeline = __commonJS({
54626
54646
  util2.destroy(ret, err);
54627
54647
  }
54628
54648
  };
54629
- function pipeline(opts, handler) {
54649
+ function pipeline2(opts, handler) {
54630
54650
  try {
54631
54651
  const pipelineHandler = new PipelineHandler(opts, handler);
54632
54652
  this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler);
@@ -54635,7 +54655,7 @@ var require_api_pipeline = __commonJS({
54635
54655
  return new PassThrough2().destroy(err);
54636
54656
  }
54637
54657
  }
54638
- module2.exports = pipeline;
54658
+ module2.exports = pipeline2;
54639
54659
  }
54640
54660
  });
54641
54661
 
@@ -55006,20 +55026,20 @@ var require_mock_utils = __commonJS({
55006
55026
  }
55007
55027
  return normalizedQp;
55008
55028
  }
55009
- function safeUrl(path92) {
55010
- if (typeof path92 !== "string") {
55011
- return path92;
55029
+ function safeUrl(path98) {
55030
+ if (typeof path98 !== "string") {
55031
+ return path98;
55012
55032
  }
55013
- const pathSegments = path92.split("?", 3);
55033
+ const pathSegments = path98.split("?", 3);
55014
55034
  if (pathSegments.length !== 2) {
55015
- return path92;
55035
+ return path98;
55016
55036
  }
55017
55037
  const qp2 = new URLSearchParams(pathSegments.pop());
55018
55038
  qp2.sort();
55019
55039
  return [...pathSegments, qp2.toString()].join("?");
55020
55040
  }
55021
- function matchKey(mockDispatch2, { path: path92, method, body, headers }) {
55022
- const pathMatch = matchValue(mockDispatch2.path, path92);
55041
+ function matchKey(mockDispatch2, { path: path98, method, body, headers }) {
55042
+ const pathMatch = matchValue(mockDispatch2.path, path98);
55023
55043
  const methodMatch = matchValue(mockDispatch2.method, method);
55024
55044
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
55025
55045
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -55044,8 +55064,8 @@ var require_mock_utils = __commonJS({
55044
55064
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
55045
55065
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
55046
55066
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
55047
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path92, ignoreTrailingSlash }) => {
55048
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path92)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path92), resolvedPath);
55067
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path98, ignoreTrailingSlash }) => {
55068
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path98)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path98), resolvedPath);
55049
55069
  });
55050
55070
  if (matchedMockDispatches.length === 0) {
55051
55071
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -55084,19 +55104,19 @@ var require_mock_utils = __commonJS({
55084
55104
  mockDispatches.splice(index, 1);
55085
55105
  }
55086
55106
  }
55087
- function removeTrailingSlash(path92) {
55088
- while (path92.endsWith("/")) {
55089
- path92 = path92.slice(0, -1);
55107
+ function removeTrailingSlash(path98) {
55108
+ while (path98.endsWith("/")) {
55109
+ path98 = path98.slice(0, -1);
55090
55110
  }
55091
- if (path92.length === 0) {
55092
- path92 = "/";
55111
+ if (path98.length === 0) {
55112
+ path98 = "/";
55093
55113
  }
55094
- return path92;
55114
+ return path98;
55095
55115
  }
55096
55116
  function buildKey(opts) {
55097
- const { path: path92, method, body, headers, query } = opts;
55117
+ const { path: path98, method, body, headers, query } = opts;
55098
55118
  return {
55099
- path: path92,
55119
+ path: path98,
55100
55120
  method,
55101
55121
  body,
55102
55122
  headers,
@@ -55786,10 +55806,10 @@ var require_pending_interceptors_formatter = __commonJS({
55786
55806
  }
55787
55807
  format(pendingInterceptors) {
55788
55808
  const withPrettyHeaders = pendingInterceptors.map(
55789
- ({ method, path: path92, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
55809
+ ({ method, path: path98, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
55790
55810
  Method: method,
55791
55811
  Origin: origin,
55792
- Path: path92,
55812
+ Path: path98,
55793
55813
  "Status code": statusCode,
55794
55814
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
55795
55815
  Invocations: timesInvoked,
@@ -55871,9 +55891,9 @@ var require_mock_agent = __commonJS({
55871
55891
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
55872
55892
  const dispatchOpts = { ...opts };
55873
55893
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
55874
- const [path92, searchParams] = dispatchOpts.path.split("?");
55894
+ const [path98, searchParams] = dispatchOpts.path.split("?");
55875
55895
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
55876
- dispatchOpts.path = `${path92}?${normalizedSearchParams}`;
55896
+ dispatchOpts.path = `${path98}?${normalizedSearchParams}`;
55877
55897
  }
55878
55898
  return this[kAgent].dispatch(dispatchOpts, handler);
55879
55899
  }
@@ -56274,12 +56294,12 @@ var require_snapshot_recorder = __commonJS({
56274
56294
  * @return {Promise<void>} - Resolves when snapshots are loaded
56275
56295
  */
56276
56296
  async loadSnapshots(filePath) {
56277
- const path92 = filePath || this.#snapshotPath;
56278
- if (!path92) {
56297
+ const path98 = filePath || this.#snapshotPath;
56298
+ if (!path98) {
56279
56299
  throw new InvalidArgumentError2("Snapshot path is required");
56280
56300
  }
56281
56301
  try {
56282
- const data = await readFile(resolve3(path92), "utf8");
56302
+ const data = await readFile(resolve3(path98), "utf8");
56283
56303
  const parsed = JSON.parse(data);
56284
56304
  if (Array.isArray(parsed)) {
56285
56305
  this.#snapshots.clear();
@@ -56293,7 +56313,7 @@ var require_snapshot_recorder = __commonJS({
56293
56313
  if (error63.code === "ENOENT") {
56294
56314
  this.#snapshots.clear();
56295
56315
  } else {
56296
- throw new UndiciError(`Failed to load snapshots from ${path92}`, { cause: error63 });
56316
+ throw new UndiciError(`Failed to load snapshots from ${path98}`, { cause: error63 });
56297
56317
  }
56298
56318
  }
56299
56319
  }
@@ -56304,11 +56324,11 @@ var require_snapshot_recorder = __commonJS({
56304
56324
  * @returns {Promise<void>} - Resolves when snapshots are saved
56305
56325
  */
56306
56326
  async saveSnapshots(filePath) {
56307
- const path92 = filePath || this.#snapshotPath;
56308
- if (!path92) {
56327
+ const path98 = filePath || this.#snapshotPath;
56328
+ if (!path98) {
56309
56329
  throw new InvalidArgumentError2("Snapshot path is required");
56310
56330
  }
56311
- const resolvedPath = resolve3(path92);
56331
+ const resolvedPath = resolve3(path98);
56312
56332
  await mkdir(dirname3(resolvedPath), { recursive: true });
56313
56333
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
56314
56334
  hash: hash2,
@@ -56945,15 +56965,15 @@ var require_redirect_handler = __commonJS({
56945
56965
  }
56946
56966
  this.history[kRedirectCacheControl].push(headers["cache-control"]);
56947
56967
  const { origin, pathname, search } = util2.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
56948
- const path92 = search ? `${pathname}${search}` : pathname;
56949
- const redirectUrlString = `${origin}${path92}`;
56968
+ const path98 = search ? `${pathname}${search}` : pathname;
56969
+ const redirectUrlString = `${origin}${path98}`;
56950
56970
  for (const historyUrl of this.history) {
56951
56971
  if (historyUrl.toString() === redirectUrlString) {
56952
56972
  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.`);
56953
56973
  }
56954
56974
  }
56955
56975
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
56956
- this.opts.path = path92;
56976
+ this.opts.path = path98;
56957
56977
  this.opts.origin = origin;
56958
56978
  this.opts.query = null;
56959
56979
  }
@@ -58721,10 +58741,10 @@ var require_cache_handler = __commonJS({
58721
58741
  }
58722
58742
  return locationUrl.pathname + locationUrl.search;
58723
58743
  }
58724
- function deleteCachedUri(store, cacheKey, path92) {
58744
+ function deleteCachedUri(store, cacheKey, path98) {
58725
58745
  deleteCachedValue(store, {
58726
58746
  ...cacheKey,
58727
- path: path92
58747
+ path: path98
58728
58748
  });
58729
58749
  for (let i10 = 0; i10 < util2.safeHTTPMethods.length; i10++) {
58730
58750
  const method = util2.safeHTTPMethods[i10];
@@ -58732,7 +58752,7 @@ var require_cache_handler = __commonJS({
58732
58752
  deleteCachedValue(store, {
58733
58753
  ...cacheKey,
58734
58754
  method,
58735
- path: path92
58755
+ path: path98
58736
58756
  });
58737
58757
  }
58738
58758
  }
@@ -58743,9 +58763,9 @@ var require_cache_handler = __commonJS({
58743
58763
  }
58744
58764
  const values = Array.isArray(headerValue2) ? headerValue2 : [headerValue2];
58745
58765
  for (let i10 = 0; i10 < values.length; i10++) {
58746
- const path92 = getSameOriginPath(cacheKey, values[i10]);
58747
- if (path92 !== void 0) {
58748
- deleteCachedUri(store, cacheKey, path92);
58766
+ const path98 = getSameOriginPath(cacheKey, values[i10]);
58767
+ if (path98 !== void 0) {
58768
+ deleteCachedUri(store, cacheKey, path98);
58749
58769
  }
58750
58770
  }
58751
58771
  }
@@ -59912,7 +59932,7 @@ var require_decompress = __commonJS({
59912
59932
  "node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/interceptor/decompress.js"(exports2, module2) {
59913
59933
  "use strict";
59914
59934
  var { createInflate: createInflate2, createGunzip: createGunzip2, createBrotliDecompress: createBrotliDecompress2, createZstdDecompress } = require("node:zlib");
59915
- var { pipeline, Transform: TransformStream2 } = require("node:stream");
59935
+ var { pipeline: pipeline2, Transform: TransformStream2 } = require("node:stream");
59916
59936
  var { InvalidArgumentError: InvalidArgumentError2, ResponseExceededMaxSizeError } = require_errors();
59917
59937
  var DecoratorHandler = require_decorator_handler();
59918
59938
  var { runtimeFeatures } = require_runtime_features();
@@ -60229,7 +60249,7 @@ var require_decompress = __commonJS({
60229
60249
  #setupMultipleDecompressors() {
60230
60250
  const lastDecompressor = this.#decompressors[this.#decompressors.length - 1];
60231
60251
  this.#setupDecompressorEvents(lastDecompressor);
60232
- pipeline(this.#decompressors, (err) => {
60252
+ pipeline2(this.#decompressors, (err) => {
60233
60253
  if (this.#terminated) {
60234
60254
  return;
60235
60255
  }
@@ -63059,7 +63079,7 @@ var require_fetch = __commonJS({
63059
63079
  subresourceSet
63060
63080
  } = require_constants4();
63061
63081
  var EE2 = require("node:events");
63062
- var { Readable: Readable3, pipeline, finished, isErrored, isReadable } = require("node:stream");
63082
+ var { Readable: Readable3, pipeline: pipeline2, finished, isErrored, isReadable } = require("node:stream");
63063
63083
  var { addAbortListener, bufferToLowerCasedHeaderName } = require_util2();
63064
63084
  var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url();
63065
63085
  var { getGlobalDispatcher } = require_global2();
@@ -63956,11 +63976,11 @@ var require_fetch = __commonJS({
63956
63976
  function dispatch({ body }) {
63957
63977
  const url2 = requestCurrentURL(request7);
63958
63978
  const agent = fetchParams.controller.dispatcher;
63959
- const path92 = url2.pathname + url2.search;
63979
+ const path98 = url2.pathname + url2.search;
63960
63980
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
63961
63981
  return new Promise((resolve3, reject) => agent.dispatch(
63962
63982
  {
63963
- path: hasTrailingQuestionMark ? `${path92}?` : path92,
63983
+ path: hasTrailingQuestionMark ? `${path98}?` : path98,
63964
63984
  origin: url2.origin,
63965
63985
  method: request7.method,
63966
63986
  body: agent.isMockActive ? request7.body && (request7.body.source || request7.body.stream) : body,
@@ -64050,7 +64070,7 @@ var require_fetch = __commonJS({
64050
64070
  status,
64051
64071
  statusText,
64052
64072
  headersList,
64053
- body: decoders.length ? pipeline(this.body, ...decoders, (err) => {
64073
+ body: decoders.length ? pipeline2(this.body, ...decoders, (err) => {
64054
64074
  if (err) {
64055
64075
  this.onError(err);
64056
64076
  }
@@ -64907,9 +64927,9 @@ var require_util5 = __commonJS({
64907
64927
  }
64908
64928
  }
64909
64929
  }
64910
- function validateCookiePath(path92) {
64911
- for (let i10 = 0; i10 < path92.length; ++i10) {
64912
- const code = path92.charCodeAt(i10);
64930
+ function validateCookiePath(path98) {
64931
+ for (let i10 = 0; i10 < path98.length; ++i10) {
64932
+ const code = path98.charCodeAt(i10);
64913
64933
  if (code < 32 || // exclude CTLs (0-31)
64914
64934
  code > 126 || // exclude DEL and non-ascii
64915
64935
  code === 59) {
@@ -67947,7 +67967,7 @@ ${value3}`;
67947
67967
  var require_eventsource = __commonJS({
67948
67968
  "node_modules/.pnpm/undici@7.30.1/node_modules/undici/lib/web/eventsource/eventsource.js"(exports2, module2) {
67949
67969
  "use strict";
67950
- var { pipeline } = require("node:stream");
67970
+ var { pipeline: pipeline2 } = require("node:stream");
67951
67971
  var { fetching } = require_fetch();
67952
67972
  var { makeRequest } = require_request2();
67953
67973
  var { webidl } = require_webidl();
@@ -68107,7 +68127,7 @@ var require_eventsource = __commonJS({
68107
68127
  ));
68108
68128
  }
68109
68129
  });
68110
- pipeline(
68130
+ pipeline2(
68111
68131
  response.body.stream,
68112
68132
  eventSourceStream,
68113
68133
  (error63) => {
@@ -68345,11 +68365,11 @@ var require_undici = __commonJS({
68345
68365
  if (typeof opts.path !== "string") {
68346
68366
  throw new InvalidArgumentError2("invalid opts.path");
68347
68367
  }
68348
- let path92 = opts.path;
68368
+ let path98 = opts.path;
68349
68369
  if (!opts.path.startsWith("/")) {
68350
- path92 = `/${path92}`;
68370
+ path98 = `/${path98}`;
68351
68371
  }
68352
- url2 = new URL(util2.parseOrigin(url2).origin + path92);
68372
+ url2 = new URL(util2.parseOrigin(url2).origin + path98);
68353
68373
  } else {
68354
68374
  if (!opts) {
68355
68375
  opts = typeof url2 === "object" ? url2 : {};
@@ -70493,7 +70513,7 @@ function withSupervision(passthrough, supervised) {
70493
70513
  if (supervised.conversation === "as-given") {
70494
70514
  return passthrough;
70495
70515
  }
70496
- const conversed = withConversation(passthrough, supervised.conversation, supervised.sessionId);
70516
+ const conversed = withConversation(passthrough, supervised.conversation, supervised.conversationId ?? supervised.sessionId);
70497
70517
  if (supervised.model === void 0) {
70498
70518
  return conversed;
70499
70519
  }
@@ -70518,11 +70538,64 @@ function withLauncherSettings(passthrough, settings2) {
70518
70538
  return passthrough;
70519
70539
  }
70520
70540
  const end = passthrough.indexOf(TERMINATOR2);
70521
- return end === -1 ? [...passthrough, "--settings", settings2] : [...passthrough.slice(0, end), "--settings", settings2, ...passthrough.slice(end)];
70541
+ const head = end === -1 ? passthrough : passthrough.slice(0, end);
70542
+ const tail = end === -1 ? [] : passthrough.slice(end);
70543
+ const kept = [];
70544
+ for (let index = 0; index < head.length; index += 1) {
70545
+ const token = head[index];
70546
+ if (token === "--settings") {
70547
+ index += 1;
70548
+ } else if (token !== void 0 && !token.startsWith("--settings=")) {
70549
+ kept.push(token);
70550
+ }
70551
+ }
70552
+ return [...kept, "--settings", settings2, ...tail];
70522
70553
  }
70523
70554
  function isRecord6(value3) {
70524
70555
  return typeof value3 === "object" && value3 !== null && !Array.isArray(value3);
70525
70556
  }
70557
+ function isUnknownArray(value3) {
70558
+ return Array.isArray(value3);
70559
+ }
70560
+ function combineCallerSettings(passthrough, launcherSettings, read) {
70561
+ const end = passthrough.indexOf(TERMINATOR2);
70562
+ const head = end === -1 ? passthrough : passthrough.slice(0, end);
70563
+ let argument;
70564
+ for (let index = 0; index < head.length; index += 1) {
70565
+ const token = head[index];
70566
+ if (token === "--settings") {
70567
+ argument = head[index + 1];
70568
+ index += 1;
70569
+ } else if (token?.startsWith("--settings=") === true) {
70570
+ argument = token.slice("--settings=".length);
70571
+ }
70572
+ }
70573
+ if (argument === void 0 || argument === "") {
70574
+ throw new Error("--settings requires a JSON object or settings file");
70575
+ }
70576
+ const contents = argument.trimStart().startsWith("{") ? argument : read(argument);
70577
+ if (contents === void 0) {
70578
+ throw new Error(`cannot read settings file ${argument}`);
70579
+ }
70580
+ const caller = JSON.parse(contents);
70581
+ const added = JSON.parse(launcherSettings);
70582
+ if (!isRecord6(caller) || !isRecord6(added) || !isRecord6(added.hooks)) {
70583
+ throw new Error("settings must be JSON objects with launcher hooks");
70584
+ }
70585
+ const callerHooks = caller.hooks;
70586
+ if (callerHooks !== void 0 && !isRecord6(callerHooks)) {
70587
+ throw new Error("settings hooks must be an object");
70588
+ }
70589
+ const hooks = { ...callerHooks };
70590
+ for (const [event, value3] of Object.entries(added.hooks)) {
70591
+ const existing = hooks[event];
70592
+ if (!isUnknownArray(value3) || existing !== void 0 && !isUnknownArray(existing)) {
70593
+ throw new Error(`settings hooks for ${event} must be arrays`);
70594
+ }
70595
+ hooks[event] = existing === void 0 ? value3 : [...existing, ...value3];
70596
+ }
70597
+ return JSON.stringify({ ...caller, ...added, hooks });
70598
+ }
70526
70599
  function mergeSettings(parts) {
70527
70600
  const merged = {};
70528
70601
  let any2 = false;
@@ -72999,7 +73072,8 @@ function decideLaunch(params, readOnly, onRecorded) {
72999
73072
  const flags = loginlessProvider === void 0 ? requestedFlags : { ...requestedFlags, remoteControl: false };
73000
73073
  const globalModels = loadConfigFile(paths.globalConfigFile, GlobalConfigSchema, params.fs.readConfigFile)?.config.models;
73001
73074
  const models = launchCascade !== void 0 && params.farm !== void 0 ? cascadeModels : globalModels;
73002
- const callerSettings = hasSettingsArgument(parsedArgv.rest);
73075
+ const extraFlags = splitExtraFlags(env.CLAUDE_EXTRA_FLAGS);
73076
+ const callerSettings = hasSettingsArgument([...extraFlags, ...parsedArgv.rest]);
73003
73077
  const startsSession = !isClaudeSubcommand(parsedArgv.rest);
73004
73078
  const argsForSupervisor = (supervisorPid) => {
73005
73079
  const door = readFrontDoorState(params.fs, paths.frontdoorStateFile);
@@ -73033,10 +73107,10 @@ function decideLaunch(params, readOnly, onRecorded) {
73033
73107
  }
73034
73108
  });
73035
73109
  const pickerSettings = modelPickerSettingsFromRows(routedModelRows(models ?? {}, listedProviders), selectedProvider !== void 0);
73036
- const launcherSettings = mergeSettings([params.supervised?.settings, callerSettings ? void 0 : pickerSettings]);
73110
+ const launcherSettings = params.supervised?.settingsFile ?? mergeSettings([params.supervised?.settings, callerSettings ? void 0 : pickerSettings]);
73037
73111
  const args2 = startsSession ? buildArgv({
73038
73112
  toolFlags: buildFlagArgs(flags),
73039
- extraFlags: splitExtraFlags(env.CLAUDE_EXTRA_FLAGS),
73113
+ extraFlags,
73040
73114
  passthrough: withLauncherSettings(params.supervised === void 0 ? parsedArgv.rest : withSupervision(parsedArgv.rest, params.supervised), launcherSettings)
73041
73115
  }) : [...parsedArgv.rest];
73042
73116
  return { args: args2, pickerSuppressed: startsSession && pickerSettings !== void 0 && callerSettings };
@@ -112992,8 +113066,8 @@ var require_utils3 = __commonJS({
112992
113066
  }
112993
113067
  return ind;
112994
113068
  }
112995
- function removeDotSegments(path92) {
112996
- let input2 = path92;
113069
+ function removeDotSegments(path98) {
113070
+ let input2 = path98;
112997
113071
  const output2 = [];
112998
113072
  let nextSlash = -1;
112999
113073
  let len = 0;
@@ -113067,11 +113141,11 @@ var require_utils3 = __commonJS({
113067
113141
  }
113068
113142
  return output2.join("");
113069
113143
  }
113070
- function removeDotSegmentsRelative(path92) {
113071
- if (path92 === "" || path92[0] === "/") {
113072
- return removeDotSegments(path92);
113144
+ function removeDotSegmentsRelative(path98) {
113145
+ if (path98 === "" || path98[0] === "/") {
113146
+ return removeDotSegments(path98);
113073
113147
  }
113074
- const segments = path92.split("/");
113148
+ const segments = path98.split("/");
113075
113149
  const last = segments.length - 1;
113076
113150
  const output2 = [];
113077
113151
  let trailingDirectory = false;
@@ -113434,8 +113508,8 @@ var require_schemes = __commonJS({
113434
113508
  }
113435
113509
  if (wsComponent.resourceName) {
113436
113510
  const queryIndex = wsComponent.resourceName.indexOf("?");
113437
- const path92 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
113438
- wsComponent.path = path92 && path92 !== "/" ? path92 : void 0;
113511
+ const path98 = queryIndex === -1 ? wsComponent.resourceName : wsComponent.resourceName.slice(0, queryIndex);
113512
+ wsComponent.path = path98 && path98 !== "/" ? path98 : void 0;
113439
113513
  wsComponent.query = queryIndex === -1 ? void 0 : wsComponent.resourceName.slice(queryIndex + 1);
113440
113514
  wsComponent.resourceName = void 0;
113441
113515
  }
@@ -116986,7 +117060,7 @@ var require_dist2 = __commonJS({
116986
117060
  });
116987
117061
 
116988
117062
  // src/cli.ts
116989
- var import_node_path91 = __toESM(require("node:path"), 1);
117063
+ var import_node_path97 = __toESM(require("node:path"), 1);
116990
117064
 
116991
117065
  // node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
116992
117066
  var CommanderError = class extends Error {
@@ -120099,9 +120173,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
120099
120173
  * @param {string} [path]
120100
120174
  * @return {(string|null|Command)}
120101
120175
  */
120102
- executableDir(path92) {
120103
- if (path92 === void 0) return this._executableDir;
120104
- this._executableDir = path92;
120176
+ executableDir(path98) {
120177
+ if (path98 === void 0) return this._executableDir;
120178
+ this._executableDir = path98;
120105
120179
  return this;
120106
120180
  }
120107
120181
  /**
@@ -121696,6 +121770,39 @@ function writeEntriesPatch(paths, target, patch) {
121696
121770
  return;
121697
121771
  }
121698
121772
  }
121773
+ async function configureClassifications(deps, claudeHome) {
121774
+ const names = classifyEntries([...realFarmFs.readdir(claudeHome)].sort(), loadClassification(deps.paths)).unclassified;
121775
+ const categories = ["secret", ...OVERRIDABLE_CATEGORIES];
121776
+ const additions = { secret: [], runtime: [], history: [], knowledge: [], settings: [] };
121777
+ for (const name of names) {
121778
+ const chosen = await deps.prompts.select({
121779
+ message: `Classify "${name}"`,
121780
+ options: [
121781
+ { value: "skip", label: "Leave unclassified", hint: "excluded until classified" },
121782
+ ...categories.map((category) => ({ value: category, label: category, ...category === "secret" ? { hint: "never shared" } : {} }))
121783
+ ],
121784
+ initialValue: "skip"
121785
+ });
121786
+ if (deps.prompts.isCancel(chosen)) {
121787
+ deps.prompts.cancel("Cancelled.");
121788
+ return false;
121789
+ }
121790
+ if (chosen !== "skip") {
121791
+ additions[chosen].push(literalClassificationPattern(name));
121792
+ }
121793
+ }
121794
+ if (categories.some((category) => additions[category].length > 0)) {
121795
+ const overlay2 = readJson(deps.paths.categoriesLocalFile, CategoryClassificationOverlaySchema) ?? {};
121796
+ for (const category of categories) {
121797
+ if (additions[category].length > 0) {
121798
+ overlay2[category] = [...overlay2[category] ?? [], ...additions[category]];
121799
+ }
121800
+ }
121801
+ applyPatch(deps.paths.categoriesLocalFile, CategoryClassificationOverlaySchema, overlay2, { defaults: {} });
121802
+ deps.log.info("Updated the local category map.");
121803
+ }
121804
+ return true;
121805
+ }
121699
121806
  function parentOf3(relPath) {
121700
121807
  const index = relPath.lastIndexOf("/");
121701
121808
  return index === -1 ? "" : relPath.slice(0, index);
@@ -122012,26 +122119,31 @@ async function runConfigure(deps, params) {
122012
122119
  function registerConfigureCommand(program2, deps) {
122013
122120
  const { paths } = deps;
122014
122121
  const command = program2.command("configure [path]").description(
122015
- "Interactively toggle an identity's shared categories, or the entries under one ~/.claude-relative path, writing to whichever file the 3-tier precedence selects."
122122
+ "Classify unknown top-level entries, then interactively configure an identity's shared categories or entries."
122016
122123
  ).option("--identity <name>", "Identity to configure (defaults to the identity a launch here would resolve).").action(async (pathArg, options) => {
122017
122124
  const cwd = process.cwd();
122018
122125
  if (!deps.isInteractive()) {
122019
122126
  throw new ConfigureNeedsTerminalError();
122020
122127
  }
122128
+ const configureDeps = { paths, prompts: deps.prompts, log: { info: (message) => {
122129
+ console.log(message);
122130
+ } } };
122131
+ const claudeHome = resolveClaudeHome();
122132
+ if (!await configureClassifications(configureDeps, claudeHome)) {
122133
+ return;
122134
+ }
122021
122135
  const identityName = options.identity ?? resolveLaunchIdentity(paths, cwd);
122022
122136
  if (identityName === void 0) {
122023
122137
  throw new NoIdentityResolvedError(cwd);
122024
122138
  }
122025
122139
  await runConfigure(
122026
- { paths, prompts: deps.prompts, log: { info: (message) => {
122027
- console.log(message);
122028
- } } },
122140
+ configureDeps,
122029
122141
  {
122030
122142
  identityName,
122031
122143
  ...pathArg === void 0 ? {} : { path: pathArg },
122032
122144
  cwd,
122033
122145
  home: import_node_os4.default.homedir(),
122034
- claudeHome: resolveClaudeHome()
122146
+ claudeHome
122035
122147
  }
122036
122148
  );
122037
122149
  });
@@ -122391,7 +122503,7 @@ function statuslineChangeOf(options) {
122391
122503
  return void 0;
122392
122504
  }
122393
122505
  const assignments = (options.statusline ?? []).map(parseStatuslineAssignment);
122394
- return { set: Object.fromEntries(assignments.map(({ path: path92, value: value3 }) => [path92, value3])), unset: options.unsetStatusline ?? [] };
122506
+ return { set: Object.fromEntries(assignments.map(({ path: path98, value: value3 }) => [path98, value3])), unset: options.unsetStatusline ?? [] };
122395
122507
  }
122396
122508
  function registerProfileCommand(program2, deps) {
122397
122509
  const { paths } = deps;
@@ -125800,6 +125912,14 @@ var SupervisedSessionSchema = external_exports.strictObject({
125800
125912
  var SessionStateSchema = external_exports.strictObject({
125801
125913
  /** `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. */
125802
125914
  mark: external_exports.enum(["busy", "idle"]),
125915
+ /** The current Claude conversation when it differs from the launch id, for example after /clear. */
125916
+ conversationId: external_exports.uuid().optional(),
125917
+ /** Claude's own path for the current conversation transcript. */
125918
+ transcriptPath: external_exports.string().min(1).optional(),
125919
+ /** Claude's identifier for the most recently submitted prompt. */
125920
+ promptId: external_exports.uuid().optional(),
125921
+ /** A hook failed to establish the current conversation, so the saved id must not be used for a move. */
125922
+ unavailable: external_exports.literal(true).optional(),
125803
125923
  /** The size in tokens of the context as of the last turn that ended; absent until one has. */
125804
125924
  contextTokens: external_exports.number().int().nonnegative().optional(),
125805
125925
  /** 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. */
@@ -126945,8 +127065,8 @@ function pathnameOf(url2) {
126945
127065
  return new URL(url2 ?? "/", "http://127.0.0.1").pathname;
126946
127066
  }
126947
127067
  function isRcSessionExchange(url2) {
126948
- const path92 = pathnameOf(url2);
126949
- return path92 === RC_SESSIONS_PATH_PREFIX || path92.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
127068
+ const path98 = pathnameOf(url2);
127069
+ return path98 === RC_SESSIONS_PATH_PREFIX || path98.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
126950
127070
  }
126951
127071
  var RC_SESSION_ID_PREFIX = "cse_";
126952
127072
  var RC_IDLE_EXPIRY_MS = 45e3;
@@ -127484,8 +127604,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
127484
127604
  function isRcReadFileEncoding(value3) {
127485
127605
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value3);
127486
127606
  }
127487
- function buildRcReadFilePayload(requestId, path92, options) {
127488
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path92, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
127607
+ function buildRcReadFilePayload(requestId, path98, options) {
127608
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path98, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
127489
127609
  }
127490
127610
  function buildRcFileSuggestionsPayload(requestId, query) {
127491
127611
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -127587,15 +127707,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
127587
127707
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
127588
127708
  return result.ok ? { ...result, requestId } : result;
127589
127709
  }
127590
- async function readRcSessionFile(deps, sessionId, path92, options) {
127591
- if (path92 === "") {
127710
+ async function readRcSessionFile(deps, sessionId, path98, options) {
127711
+ if (path98 === "") {
127592
127712
  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" };
127593
127713
  }
127594
127714
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
127595
127715
  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" };
127596
127716
  }
127597
127717
  const requestId = deps.newUuid();
127598
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path92, options), `read ${path92} from session ${sessionId}`);
127718
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path98, options), `read ${path98} from session ${sessionId}`);
127599
127719
  return result.ok ? { ...result, requestId } : result;
127600
127720
  }
127601
127721
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -127778,11 +127898,11 @@ function createRcControlHandler(deps) {
127778
127898
  path: "read-file",
127779
127899
  read: (body) => {
127780
127900
  const session = bodyString(body, "session");
127781
- const path92 = bodyString(body, "path");
127901
+ const path98 = bodyString(body, "path");
127782
127902
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
127783
127903
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
127784
- const refused2 = session === void 0 || path92 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
127785
- 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, path92, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
127904
+ const refused2 = session === void 0 || path98 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
127905
+ 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, path98, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
127786
127906
  }
127787
127907
  },
127788
127908
  {
@@ -128092,9 +128212,9 @@ function requestIdOfBody(body) {
128092
128212
  }
128093
128213
  function frontDoorRcControl(transport, token) {
128094
128214
  const headers = { authorization: `Bearer ${token}` };
128095
- const listAnswerOf = async (path92, what) => {
128215
+ const listAnswerOf = async (path98, what) => {
128096
128216
  try {
128097
- return await transport.request({ method: "GET", path: path92, headers });
128217
+ return await transport.request({ method: "GET", path: path98, headers });
128098
128218
  } catch (error63) {
128099
128219
  throw new Error(`${what}: could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}`, { cause: error63 });
128100
128220
  }
@@ -128166,10 +128286,10 @@ function frontDoorRcControl(transport, token) {
128166
128286
  }
128167
128287
  return pending;
128168
128288
  };
128169
- const writeOf = async (path92, body, describeFailure2) => {
128289
+ const writeOf = async (path98, body, describeFailure2) => {
128170
128290
  let answer;
128171
128291
  try {
128172
- answer = await transport.request({ method: "POST", path: path92, headers: { ...headers, "content-type": "application/json" }, body });
128292
+ answer = await transport.request({ method: "POST", path: path98, headers: { ...headers, "content-type": "application/json" }, body });
128173
128293
  } catch (error63) {
128174
128294
  return { ok: false, message: `could not reach the front door's control listener: ${error63 instanceof Error ? error63.message : String(error63)}` };
128175
128295
  }
@@ -128200,10 +128320,10 @@ function frontDoorRcControl(transport, token) {
128200
128320
  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}`),
128201
128321
  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}`),
128202
128322
  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}`),
128203
- readFile: async (sessionId, path92, options) => await writeOf(
128323
+ readFile: async (sessionId, path98, options) => await writeOf(
128204
128324
  `${CONTROL_PATH_PREFIX}/read-file`,
128205
- JSON.stringify({ session: sessionId, path: path92, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
128206
- (status, message) => `reading ${path92} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
128325
+ JSON.stringify({ session: sessionId, path: path98, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
128326
+ (status, message) => `reading ${path98} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
128207
128327
  ),
128208
128328
  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}`),
128209
128329
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -128221,7 +128341,7 @@ var HEALTH_START_BUDGET_MS = 5e3;
128221
128341
  var HEALTH_RETRY_MS = 50;
128222
128342
  var PREFERRED_PORT_MAX_ATTEMPTS = 6;
128223
128343
  var PREFERRED_PORT_RETRY_MS = 50;
128224
- function createFrontDoorServer(pipeline, log, tls2, control, apis) {
128344
+ function createFrontDoorServer(pipeline2, log, tls2, control, apis) {
128225
128345
  const handler = (request7, response) => {
128226
128346
  if (request7.method === "GET" && request7.url === "/healthz") {
128227
128347
  response.writeHead(HTTP_STATUS.ok, { "Content-Type": "text/plain" });
@@ -128257,7 +128377,7 @@ function createFrontDoorServer(pipeline, log, tls2, control, apis) {
128257
128377
  }
128258
128378
  });
128259
128379
  const handle = async () => {
128260
- await pipeline({ method: request7.method ?? "GET", url: request7.url ?? "/", headers: aliasLegacyWireHeaders(request7.headers), body: request7, signal: abort.signal, response });
128380
+ await pipeline2({ method: request7.method ?? "GET", url: request7.url ?? "/", headers: aliasLegacyWireHeaders(request7.headers), body: request7, signal: abort.signal, response });
128261
128381
  if (!request7.readableEnded) {
128262
128382
  request7.resume();
128263
128383
  }
@@ -128609,12 +128729,12 @@ function tlsFacts(options) {
128609
128729
  }
128610
128730
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
128611
128731
  const agent = new ExemptTlsAgent();
128612
- const post = async (path92, headers, body) => await new Promise((resolve3, reject) => {
128732
+ const post = async (path98, headers, body) => await new Promise((resolve3, reject) => {
128613
128733
  const options = {
128614
128734
  host: target.host,
128615
128735
  port: target.port,
128616
128736
  method: "POST",
128617
- path: path92,
128737
+ path: path98,
128618
128738
  // 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.
128619
128739
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
128620
128740
  agent
@@ -128679,12 +128799,12 @@ function lateRcStreamDial(resolve3) {
128679
128799
  }
128680
128800
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
128681
128801
  const agent = new ExemptTlsAgent();
128682
- const request7 = async (method, path92, headers, body, signal) => await new Promise((resolve3, reject) => {
128802
+ const request7 = async (method, path98, headers, body, signal) => await new Promise((resolve3, reject) => {
128683
128803
  const options = {
128684
128804
  host: target.host,
128685
128805
  port: target.port,
128686
128806
  method,
128687
- path: path92,
128807
+ path: path98,
128688
128808
  // 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.
128689
128809
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
128690
128810
  agent,
@@ -128726,9 +128846,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
128726
128846
  return { status, body: await readAll(response) };
128727
128847
  },
128728
128848
  openStream: async (sessionId, headers, resume, signal) => {
128729
- const path92 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
128849
+ const path98 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
128730
128850
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
128731
- const { status, response } = await request7("GET", path92, streamHeaders, void 0, signal);
128851
+ const { status, response } = await request7("GET", path98, streamHeaders, void 0, signal);
128732
128852
  if (!isSuccessful2(status)) {
128733
128853
  await readAll(response);
128734
128854
  return { status, chunks: NO_CHUNKS };
@@ -130408,8 +130528,8 @@ function once(fn) {
130408
130528
  return result;
130409
130529
  };
130410
130530
  }
130411
- function pathToHttpPath(path92) {
130412
- return `/${path92.map(safeEncodeURIComponent).join("/")}`;
130531
+ function pathToHttpPath(path98) {
130532
+ return `/${path98.map(safeEncodeURIComponent).join("/")}`;
130413
130533
  }
130414
130534
  var TRACER_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_TRACER");
130415
130535
  function getTracer() {
@@ -131688,7 +131808,7 @@ function resolveClientRest(rest) {
131688
131808
  // rest[1] can be undefined if all fields of FriendlyClientOptions are optional
131689
131809
  ];
131690
131810
  }
131691
- function createORPCClient(link, { path: path92 = [], ...options } = {}) {
131811
+ function createORPCClient(link, { path: path98 = [], ...options } = {}) {
131692
131812
  const procedureClient = (...rest) => {
131693
131813
  const [input2, callOptions] = resolveClientRest(rest);
131694
131814
  const interceptors = [
@@ -131697,7 +131817,7 @@ function createORPCClient(link, { path: path92 = [], ...options } = {}) {
131697
131817
  ];
131698
131818
  return intercept(
131699
131819
  interceptors,
131700
- { ...callOptions, input: input2, path: path92 },
131820
+ { ...callOptions, input: input2, path: path98 },
131701
131821
  ({ path: path210, input: input22, ...callOptions2 }) => link.call(path210, input22, callOptions2)
131702
131822
  );
131703
131823
  };
@@ -131711,7 +131831,7 @@ function createORPCClient(link, { path: path92 = [], ...options } = {}) {
131711
131831
  if (client === void 0) {
131712
131832
  client = createORPCClient(link, {
131713
131833
  ...options,
131714
- path: [...path92, key],
131834
+ path: [...path98, key],
131715
131835
  scoped: options.scoped?.[key]
131716
131836
  });
131717
131837
  cache.set(key, client);
@@ -131952,11 +132072,11 @@ function tryOrUndefined(fn) {
131952
132072
  return void 0;
131953
132073
  }
131954
132074
  }
131955
- function pathToHttpPath2(path92) {
131956
- return `/${path92.map(safeEncodeURIComponent2).join("/")}`;
132075
+ function pathToHttpPath2(path98) {
132076
+ return `/${path98.map(safeEncodeURIComponent2).join("/")}`;
131957
132077
  }
131958
- function normalizeHttpPath(path92) {
131959
- const paths = path92.split("/");
132078
+ function normalizeHttpPath(path98) {
132079
+ const paths = path98.split("/");
131960
132080
  if (paths.at(0) === "") {
131961
132081
  paths.shift();
131962
132082
  }
@@ -132141,9 +132261,9 @@ function isPlainObject4(value3) {
132141
132261
  function getOwn(object3, key) {
132142
132262
  return Object.hasOwn(object3, key) ? object3[key] : void 0;
132143
132263
  }
132144
- function get(object3, path92) {
132264
+ function get(object3, path98) {
132145
132265
  let current = object3;
132146
- for (const key of path92) {
132266
+ for (const key of path98) {
132147
132267
  if (!isTypescriptObject2(current)) {
132148
132268
  return void 0;
132149
132269
  }
@@ -132384,25 +132504,25 @@ var BracketNotationSerializer = class {
132384
132504
  this.internalSerialize(data, "", true, result);
132385
132505
  return result;
132386
132506
  }
132387
- internalSerialize(data, path92, isRoot, result) {
132507
+ internalSerialize(data, path98, isRoot, result) {
132388
132508
  if (Array.isArray(data)) {
132389
132509
  data.forEach((item, i10) => {
132390
- this.internalSerialize(item, isRoot ? i10.toString() : `${path92}[${i10}]`, false, result);
132510
+ this.internalSerialize(item, isRoot ? i10.toString() : `${path98}[${i10}]`, false, result);
132391
132511
  });
132392
132512
  } else if (isPlainObject4(data)) {
132393
132513
  for (const key of Object.keys(data)) {
132394
- this.internalSerialize(data[key], isRoot ? key : `${path92}[${key}]`, false, result);
132514
+ this.internalSerialize(data[key], isRoot ? key : `${path98}[${key}]`, false, result);
132395
132515
  }
132396
132516
  } else {
132397
- result.push([path92, data]);
132517
+ result.push([path98, data]);
132398
132518
  }
132399
132519
  }
132400
132520
  deserialize(serialized) {
132401
132521
  let arrayPushStyles;
132402
132522
  const root = new NullProtoObj2();
132403
132523
  let emptySlotsLeft = this.maxDeserializingEmptySlots;
132404
- for (const [path92, value3] of serialized) {
132405
- const segments = this.parsePath(path92);
132524
+ for (const [path98, value3] of serialized) {
132525
+ const segments = this.parsePath(path98);
132406
132526
  let currentRef = root;
132407
132527
  let nextSegment = segments[0];
132408
132528
  for (let i10 = 1; i10 < segments.length; i10++) {
@@ -132462,20 +132582,20 @@ var BracketNotationSerializer = class {
132462
132582
  }
132463
132583
  return result;
132464
132584
  }
132465
- parsePath(path92) {
132466
- const start = path92.indexOf("[");
132467
- if (start === -1 || path92[path92.length - 1] !== "]") {
132468
- return [path92];
132585
+ parsePath(path98) {
132586
+ const start = path98.indexOf("[");
132587
+ if (start === -1 || path98[path98.length - 1] !== "]") {
132588
+ return [path98];
132469
132589
  }
132470
- const segments = [path92.slice(0, start)];
132590
+ const segments = [path98.slice(0, start)];
132471
132591
  let from = start + 1;
132472
- let to2 = path92.indexOf("][", from);
132592
+ let to2 = path98.indexOf("][", from);
132473
132593
  while (to2 !== -1) {
132474
- segments.push(path92.slice(from, to2));
132594
+ segments.push(path98.slice(from, to2));
132475
132595
  from = to2 + 2;
132476
- to2 = path92.indexOf("][", from);
132596
+ to2 = path98.indexOf("][", from);
132477
132597
  }
132478
- segments.push(path92.slice(from, -1));
132598
+ segments.push(path98.slice(from, -1));
132479
132599
  return segments;
132480
132600
  }
132481
132601
  };
@@ -133973,11 +134093,11 @@ var OpenAPISerializer = class {
133973
134093
  return json2;
133974
134094
  }
133975
134095
  const form = new FormData();
133976
- for (const [path92, value22] of this.bracketNotation.serialize(json2)) {
134096
+ for (const [path98, value22] of this.bracketNotation.serialize(json2)) {
133977
134097
  if (value22 instanceof Blob) {
133978
- form.append(path92, value22);
134098
+ form.append(path98, value22);
133979
134099
  } else if (value22 !== void 0 && value22 !== null) {
133980
- form.append(path92, String(value22));
134100
+ form.append(path98, String(value22));
133981
134101
  }
133982
134102
  }
133983
134103
  return form;
@@ -134015,30 +134135,30 @@ function isBodylessMethod(method) {
134015
134135
  return method === "GET" || method === "HEAD";
134016
134136
  }
134017
134137
  var PARAMETER_NAME_REGEX = /^[\w-]+$/;
134018
- function getDynamicPathParams(path92) {
134019
- if (!path92.includes("{")) {
134138
+ function getDynamicPathParams(path98) {
134139
+ if (!path98.includes("{")) {
134020
134140
  return void 0;
134021
134141
  }
134022
- const len = path92.length;
134142
+ const len = path98.length;
134023
134143
  let params;
134024
134144
  let index = 1;
134025
134145
  while (index < len) {
134026
134146
  const segmentStart = index;
134027
- const slashPos = path92.indexOf("/", index);
134147
+ const slashPos = path98.indexOf("/", index);
134028
134148
  const segmentEnd = slashPos === -1 ? len : slashPos;
134029
- if (segmentEnd > segmentStart && path92.charCodeAt(segmentStart) === 123 && path92.charCodeAt(segmentEnd - 1) === 125) {
134149
+ if (segmentEnd > segmentStart && path98.charCodeAt(segmentStart) === 123 && path98.charCodeAt(segmentEnd - 1) === 125) {
134030
134150
  let parameterStart = segmentStart + 1;
134031
134151
  let allowsSlash = false;
134032
- const operator = path92.charCodeAt(parameterStart);
134152
+ const operator = path98.charCodeAt(parameterStart);
134033
134153
  if (operator === 43) {
134034
134154
  allowsSlash = true;
134035
134155
  parameterStart++;
134036
134156
  }
134037
- const parameterName = path92.slice(parameterStart, segmentEnd - 1);
134157
+ const parameterName = path98.slice(parameterStart, segmentEnd - 1);
134038
134158
  if (PARAMETER_NAME_REGEX.test(parameterName)) {
134039
134159
  params ??= [];
134040
134160
  params.push({
134041
- segment: path92.slice(segmentStart, segmentEnd),
134161
+ segment: path98.slice(segmentStart, segmentEnd),
134042
134162
  startIndex: segmentStart,
134043
134163
  parameterName,
134044
134164
  allowsSlash
@@ -134081,8 +134201,8 @@ openapi.method = (method) => ({
134081
134201
  ...openapi({ method }),
134082
134202
  name: "~openapi/method"
134083
134203
  });
134084
- openapi.path = (path92) => ({
134085
- ...openapi({ path: path92 }),
134204
+ openapi.path = (path98) => ({
134205
+ ...openapi({ path: path98 }),
134086
134206
  name: "~openapi/path"
134087
134207
  });
134088
134208
  openapi.spec = (spec) => ({
@@ -135001,22 +135121,22 @@ function visitJsonSchemaRefs(value3, visit2, schemaLevel = true, seen = /* @__PU
135001
135121
  }
135002
135122
  }
135003
135123
  }
135004
- function mapJsonSchemaRefs(value3, map3, schemaLevel = true, path92 = []) {
135124
+ function mapJsonSchemaRefs(value3, map3, schemaLevel = true, path98 = []) {
135005
135125
  if (!value3 || typeof value3 !== "object") {
135006
135126
  return value3;
135007
135127
  }
135008
135128
  if (Array.isArray(value3)) {
135009
- return value3.map((item, index) => mapJsonSchemaRefs(item, map3, schemaLevel, [...path92, index]));
135129
+ return value3.map((item, index) => mapJsonSchemaRefs(item, map3, schemaLevel, [...path98, index]));
135010
135130
  }
135011
135131
  const result = {};
135012
135132
  for (const key of Object.keys(value3)) {
135013
135133
  const val = value3[key];
135014
135134
  if (key === "$ref" && typeof val === "string") {
135015
- setOwn2(result, key, map3(val, [...path92, key]));
135135
+ setOwn2(result, key, map3(val, [...path98, key]));
135016
135136
  } else if (!schemaLevel) {
135017
- setOwn2(result, key, mapJsonSchemaRefs(val, map3, true, [...path92, key]));
135137
+ setOwn2(result, key, mapJsonSchemaRefs(val, map3, true, [...path98, key]));
135018
135138
  } else if (JSON_SCHEMA_LOGIC_KEYWORDS.has(key) || JSON_SCHEMA_RECORD_KEYWORDS.has(key)) {
135019
- setOwn2(result, key, mapJsonSchemaRefs(val, map3, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path92, key]));
135139
+ setOwn2(result, key, mapJsonSchemaRefs(val, map3, !JSON_SCHEMA_RECORD_KEYWORDS.has(key), [...path98, key]));
135020
135140
  } else {
135021
135141
  setOwn2(result, key, val);
135022
135142
  }
@@ -135546,7 +135666,7 @@ function unlazy(maybeLazy) {
135546
135666
  function createProcedureClient(lazyableProcedure, ...rest) {
135547
135667
  const options = resolveMaybeOptionalOptions2(rest);
135548
135668
  return async (...[input2, callerOptions]) => {
135549
- const path92 = toArray2(options.path);
135669
+ const path98 = toArray2(options.path);
135550
135670
  const { default: procedure } = await unlazy(lazyableProcedure);
135551
135671
  const clientContext = callerOptions?.context ?? {};
135552
135672
  const context = await value2(options.context, clientContext) ?? {};
@@ -135559,7 +135679,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
135559
135679
  };
135560
135680
  try {
135561
135681
  const output2 = await runWithSpan2("call_procedure", (span) => {
135562
- span?.setAttribute("procedure.path", path92);
135682
+ span?.setAttribute("procedure.path", path98);
135563
135683
  return intercept2(
135564
135684
  options.interceptors,
135565
135685
  {
@@ -135567,7 +135687,7 @@ function createProcedureClient(lazyableProcedure, ...rest) {
135567
135687
  // input can be optional if it is undefinable
135568
135688
  input: input2,
135569
135689
  errors,
135570
- path: path92,
135690
+ path: path98,
135571
135691
  procedure,
135572
135692
  signal: callerOptions?.signal,
135573
135693
  lastEventId: callerOptions?.lastEventId
@@ -135818,10 +135938,10 @@ function augmentRouter(router, options) {
135818
135938
  }
135819
135939
  return enhanced;
135820
135940
  }
135821
- function getRouter(router, path92) {
135941
+ function getRouter(router, path98) {
135822
135942
  let current = router;
135823
- for (let i10 = 0; i10 < path92.length; i10++) {
135824
- const segment = path92[i10];
135943
+ for (let i10 = 0; i10 < path98.length; i10++) {
135944
+ const segment = path98[i10];
135825
135945
  if (!isTypescriptObject2(current)) {
135826
135946
  return void 0;
135827
135947
  }
@@ -135833,7 +135953,7 @@ function getRouter(router, path92) {
135833
135953
  continue;
135834
135954
  }
135835
135955
  const lazied = current;
135836
- const rest = path92.slice(i10);
135956
+ const rest = path98.slice(i10);
135837
135957
  return new Lazy({
135838
135958
  ...lazied["~orpc"],
135839
135959
  async loader() {
@@ -135848,40 +135968,40 @@ function getRouter(router, path92) {
135848
135968
  }
135849
135969
  return current;
135850
135970
  }
135851
- function walkProcedureContractsSync(router, callback, path92 = []) {
135971
+ function walkProcedureContractsSync(router, callback, path98 = []) {
135852
135972
  const lazyResults = [];
135853
- walkProcedureContractsSyncInternal(router, callback, path92.slice(), lazyResults);
135973
+ walkProcedureContractsSyncInternal(router, callback, path98.slice(), lazyResults);
135854
135974
  return lazyResults;
135855
135975
  }
135856
- function walkProcedureContractsSyncInternal(router, callback, path92, lazyResults) {
135976
+ function walkProcedureContractsSyncInternal(router, callback, path98, lazyResults) {
135857
135977
  const hiddenContract = getHiddenRouterContract(router);
135858
135978
  if (hiddenContract !== void 0) {
135859
135979
  router = hiddenContract;
135860
135980
  }
135861
135981
  if (router instanceof ProcedureContract) {
135862
- callback(router, path92.slice());
135982
+ callback(router, path98.slice());
135863
135983
  return;
135864
135984
  }
135865
135985
  if (!isTypescriptObject2(router)) {
135866
135986
  return;
135867
135987
  }
135868
135988
  for (const [key, value3] of Object.entries(router)) {
135869
- path92.push(key);
135989
+ path98.push(key);
135870
135990
  if (value3 instanceof Lazy) {
135871
- lazyResults.push({ router: value3, path: path92.slice() });
135991
+ lazyResults.push({ router: value3, path: path98.slice() });
135872
135992
  } else {
135873
- walkProcedureContractsSyncInternal(value3, callback, path92, lazyResults);
135993
+ walkProcedureContractsSyncInternal(value3, callback, path98, lazyResults);
135874
135994
  }
135875
- path92.pop();
135995
+ path98.pop();
135876
135996
  }
135877
135997
  }
135878
- async function walkProcedureContractsAsync(router, callback, path92 = []) {
135998
+ async function walkProcedureContractsAsync(router, callback, path98 = []) {
135879
135999
  const hiddenContract = getHiddenRouterContract(router);
135880
136000
  if (hiddenContract !== void 0) {
135881
136001
  router = hiddenContract;
135882
136002
  }
135883
136003
  if (router instanceof ProcedureContract) {
135884
- await callback(router, path92);
136004
+ await callback(router, path98);
135885
136005
  return;
135886
136006
  }
135887
136007
  if (!isTypescriptObject2(router)) {
@@ -135890,9 +136010,9 @@ async function walkProcedureContractsAsync(router, callback, path92 = []) {
135890
136010
  for (const [key, value3] of Object.entries(router)) {
135891
136011
  if (value3 instanceof Lazy) {
135892
136012
  const { default: router2 } = await unlazy(value3);
135893
- await walkProcedureContractsAsync(router2, callback, [...path92, key]);
136013
+ await walkProcedureContractsAsync(router2, callback, [...path98, key]);
135894
136014
  } else {
135895
- await walkProcedureContractsAsync(value3, callback, [...path92, key]);
136015
+ await walkProcedureContractsAsync(value3, callback, [...path98, key]);
135896
136016
  }
135897
136017
  }
135898
136018
  }
@@ -136378,18 +136498,18 @@ function rewriteComponentSchemaRefs(schema, renameMap) {
136378
136498
  }
136379
136499
  var OpenAPIGeneratorError = class extends TypeError {
136380
136500
  };
136381
- function toOpenAPIPath(path92, dynamicPathParams) {
136501
+ function toOpenAPIPath(path98, dynamicPathParams) {
136382
136502
  if (!dynamicPathParams?.length) {
136383
- return path92;
136503
+ return path98;
136384
136504
  }
136385
136505
  let normalized = "";
136386
136506
  let currentIndex = 0;
136387
136507
  for (const param of dynamicPathParams) {
136388
- normalized += path92.slice(currentIndex, param.startIndex);
136508
+ normalized += path98.slice(currentIndex, param.startIndex);
136389
136509
  normalized += `{${param.parameterName}}`;
136390
136510
  currentIndex = param.startIndex + param.segment.length;
136391
136511
  }
136392
- normalized += path92.slice(currentIndex);
136512
+ normalized += path98.slice(currentIndex);
136393
136513
  return normalized;
136394
136514
  }
136395
136515
  function buildRequest(ctx, operation, def, meta3, dynamicPathParams) {
@@ -136846,8 +136966,8 @@ var OpenAPIGenerator = class {
136846
136966
  customErrorResponseBodySchema: options.customErrorResponseBodySchema
136847
136967
  };
136848
136968
  const errors = [];
136849
- await walkProcedureContractsAsync(router, (contract, path92) => {
136850
- if (value2(options.filter, contract, path92) === false) {
136969
+ await walkProcedureContractsAsync(router, (contract, path98) => {
136970
+ if (value2(options.filter, contract, path98) === false) {
136851
136971
  return;
136852
136972
  }
136853
136973
  try {
@@ -136859,7 +136979,7 @@ var OpenAPIGenerator = class {
136859
136979
  `QUERY operations require OpenAPI 3.2, but version "${version2}" was requested.`
136860
136980
  );
136861
136981
  }
136862
- const postPath = meta3?.path ?? pathToHttpPath2(path92);
136982
+ const postPath = meta3?.path ?? pathToHttpPath2(path98);
136863
136983
  const httpPath = meta3?.prefix ? mergeHttpPath(meta3.prefix, postPath) : postPath;
136864
136984
  const dynamicPathParams = getDynamicPathParams(httpPath);
136865
136985
  const openApiPath = toOpenAPIPath(httpPath, dynamicPathParams);
@@ -136868,7 +136988,7 @@ var OpenAPIGenerator = class {
136868
136988
  operation = meta3.spec;
136869
136989
  } else {
136870
136990
  operation = {
136871
- operationId: meta3?.operationId ?? path92.join("."),
136991
+ operationId: meta3?.operationId ?? path98.join("."),
136872
136992
  summary: meta3?.summary,
136873
136993
  description: meta3?.description,
136874
136994
  deprecated: meta3?.deprecated,
@@ -136888,7 +137008,7 @@ var OpenAPIGenerator = class {
136888
137008
  if (!(e10 instanceof OpenAPIGeneratorError)) {
136889
137009
  throw e10;
136890
137010
  }
136891
- errors.push(`Procedure at ${path92.join(".") || "(root)"}: ${e10.message}`);
137011
+ errors.push(`Procedure at ${path98.join(".") || "(root)"}: ${e10.message}`);
136892
137012
  }
136893
137013
  });
136894
137014
  if (errors.length) {
@@ -137674,16 +137794,16 @@ var StandardLink = class {
137674
137794
  /**
137675
137795
  * @throws ORPCError, MalformedResponseError, transport-level errors (network failures, timeouts, etc.)
137676
137796
  */
137677
- call(path92, input2, options) {
137678
- return runWithSpan(`${ORPC_NAME}.${path92.join("/")}`, (span) => {
137797
+ call(path98, input2, options) {
137798
+ return runWithSpan(`${ORPC_NAME}.${path98.join("/")}`, (span) => {
137679
137799
  span?.setAttribute("rpc.system", ORPC_NAME);
137680
- span?.setAttribute("rpc.method", path92.join("."));
137800
+ span?.setAttribute("rpc.method", path98.join("."));
137681
137801
  if (getTracer() && isAsyncIteratorObject(input2)) {
137682
137802
  input2 = override(input2, traceAsyncIterator("consume_async_iterator_object_input", input2));
137683
137803
  } else if (getTracer() && input2 instanceof ReadableStream) {
137684
137804
  input2 = override(input2, traceReadableStream("consume_octet_stream_input", input2));
137685
137805
  }
137686
- return intercept(this.interceptors, { ...options, path: path92, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
137806
+ return intercept(this.interceptors, { ...options, path: path98, input: input2 }, async ({ path: path210, input: input22, ...options2 }) => {
137687
137807
  const tracer = getTracer();
137688
137808
  const activeSpan = tracer?.getActiveSpan() ?? span;
137689
137809
  let request7 = await runWithSpan(
@@ -137740,18 +137860,18 @@ var RPCLinkCodec = class {
137740
137860
  this.headers = options.headers ?? {};
137741
137861
  this.serializer = options.serializer ?? new RPCSerializer();
137742
137862
  }
137743
- async encodeInput(input2, path92, options) {
137744
- let headers = toResolvedStandardHeaders(await value(this.headers, options, path92, input2));
137863
+ async encodeInput(input2, path98, options) {
137864
+ let headers = toResolvedStandardHeaders(await value(this.headers, options, path98, input2));
137745
137865
  if (options.lastEventId !== void 0) {
137746
137866
  headers = mergeStandardHeaders(headers, { "last-event-id": options.lastEventId });
137747
137867
  }
137748
- const expectedMethod = await value(this.expectedMethod, options, path92, input2);
137749
- const baseUrl = await value(this.baseUrl, options, path92, input2);
137868
+ const expectedMethod = await value(this.expectedMethod, options, path98, input2);
137869
+ const baseUrl = await value(this.baseUrl, options, path98, input2);
137750
137870
  const [pathname, search, hash2] = parseStandardUrl(baseUrl);
137751
- const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path92)}`;
137871
+ const newPathname = `${pathname.replace(END_SLASH_REGEX, "")}${pathToHttpPath(path98)}`;
137752
137872
  const serialized = this.serializer.serialize(input2);
137753
137873
  if (expectedMethod === "GET" && !(serialized instanceof Blob) && !(serialized instanceof ReadableStream) && !(serialized instanceof FormData) && !isAsyncIteratorObject(serialized)) {
137754
- const maxUrlLength = await value(this.maxUrlLength, options, path92, input2);
137874
+ const maxUrlLength = await value(this.maxUrlLength, options, path98, input2);
137755
137875
  const mergedSearch = new URLSearchParams(search);
137756
137876
  mergedSearch.append("data", stringifyJSON(serialized) ?? "");
137757
137877
  const url22 = `${newPathname}?${mergedSearch}${hash2 ?? ""}`;
@@ -137838,8 +137958,8 @@ var FetchLinkTransport = class {
137838
137958
  this.fetch = options.fetch ?? ((url2, init) => globalThis.fetch(url2, init));
137839
137959
  this.toFetchRequestOptions = options.toFetchRequest;
137840
137960
  }
137841
- async send(standardRequest, path92, options) {
137842
- let origin = await value(this.origin, options, path92);
137961
+ async send(standardRequest, path98, options) {
137962
+ let origin = await value(this.origin, options, path98);
137843
137963
  if (origin?.endsWith("/")) {
137844
137964
  origin = origin.slice(0, -1);
137845
137965
  }
@@ -137859,7 +137979,7 @@ var FetchLinkTransport = class {
137859
137979
  }
137860
137980
  }
137861
137981
  const fetch3 = this.fetch;
137862
- const response = await fetch3(url2, init, options, path92);
137982
+ const response = await fetch3(url2, init, options, path98);
137863
137983
  if (response.type === "opaqueredirect") {
137864
137984
  throw new TypeError("Unexpected redirect response: redirects are not followed.");
137865
137985
  }
@@ -138446,14 +138566,14 @@ var StandardHandler = class {
138446
138566
  span?.setAttribute("url.path", request22.url);
138447
138567
  return { matched: false };
138448
138568
  }
138449
- const { path: path92, procedure, decodeInput } = matchedOrNot;
138450
- span?.updateName(`${ORPC_NAME2}.${path92.join("/")}`);
138569
+ const { path: path98, procedure, decodeInput } = matchedOrNot;
138570
+ span?.updateName(`${ORPC_NAME2}.${path98.join("/")}`);
138451
138571
  span?.setAttribute("rpc.system", ORPC_NAME2);
138452
- span?.setAttribute("rpc.method", path92.join("."));
138572
+ span?.setAttribute("rpc.method", path98.join("."));
138453
138573
  try {
138454
138574
  const response = await intercept2(
138455
138575
  this.interceptors,
138456
- { context: context2, prefix: prefix2, request: request22, path: path92, procedure, decodeInput },
138576
+ { context: context2, prefix: prefix2, request: request22, path: path98, procedure, decodeInput },
138457
138577
  async ({ context: context3, prefix: prefix3, request: request32, path: path210, procedure: procedure2, decodeInput: decodeInput2 }) => {
138458
138578
  step2 = "decode_input";
138459
138579
  let input2 = await runWithSpan2("decode_input", decodeInput2);
@@ -138487,7 +138607,7 @@ var StandardHandler = class {
138487
138607
  message: `Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,
138488
138608
  cause: e10
138489
138609
  }) : toORPCError2(e10);
138490
- const response = await this.codec.encodeError(error63, procedure, path92, { context: context2, prefix: prefix2 });
138610
+ const response = await this.codec.encodeError(error63, procedure, path98, { context: context2, prefix: prefix2 });
138491
138611
  return { matched: true, response };
138492
138612
  }
138493
138613
  }
@@ -138594,7 +138714,7 @@ var RPCMatcher = class {
138594
138714
  this.rootRouter = router;
138595
138715
  this.index(router);
138596
138716
  }
138597
- index(router, path92 = []) {
138717
+ index(router, path98 = []) {
138598
138718
  const lazyResults = walkProcedureContractsSync(router, (procedure, procedurePath) => {
138599
138719
  if (!value2(this.filter, procedure, procedurePath)) {
138600
138720
  return;
@@ -138605,7 +138725,7 @@ var RPCMatcher = class {
138605
138725
  // contract-first entries have no implementation yet, resolveProcedure fills it in on demand
138606
138726
  procedure: procedure instanceof Procedure ? procedure : void 0
138607
138727
  });
138608
- }, path92);
138728
+ }, path98);
138609
138729
  for (const result of lazyResults) {
138610
138730
  this.pendingLazyRouters.set(pathToHttpPath2(result.path), result);
138611
138731
  }
@@ -138737,10 +138857,10 @@ var RPCHandlerCodec = class {
138737
138857
  }
138738
138858
  };
138739
138859
  }
138740
- encodeOutput(output2, procedure, path92, options) {
138860
+ encodeOutput(output2, procedure, path98, options) {
138741
138861
  return {
138742
138862
  headers: {},
138743
- status: value2(this.outputStatus, output2, procedure, path92, options) ?? DEFAULT_SUCCESS_STATUS,
138863
+ status: value2(this.outputStatus, output2, procedure, path98, options) ?? DEFAULT_SUCCESS_STATUS,
138744
138864
  body: this.serializer.serialize(output2)
138745
138865
  };
138746
138866
  }
@@ -138816,19 +138936,19 @@ function matchesZero(m10) {
138816
138936
  const last = m10.paramsMap[m10.paramsMap.length - 1];
138817
138937
  return last[2] || !!last[3] && !last[5];
138818
138938
  }
138819
- function normalizePath(path92) {
138820
- if (!path92.includes("/.")) return path92;
138939
+ function normalizePath(path98) {
138940
+ if (!path98.includes("/.")) return path98;
138821
138941
  const r10 = [];
138822
138942
  let s = "";
138823
- for (s of path92.split("/")) if (s === ".") continue;
138943
+ for (s of path98.split("/")) if (s === ".") continue;
138824
138944
  else if (s === "..") {
138825
138945
  if (r10.length > 1) r10.pop();
138826
138946
  } else r10.push(s);
138827
138947
  if (s === "." || s === "..") r10.push("");
138828
138948
  return r10.join("/") || "/";
138829
138949
  }
138830
- function splitPath(path92) {
138831
- const s = path92.split("/");
138950
+ function splitPath(path98) {
138951
+ const s = path98.split("/");
138832
138952
  s.shift();
138833
138953
  return s;
138834
138954
  }
@@ -138871,9 +138991,9 @@ function getMatchParams(segments, paramsMap, suffix, slash) {
138871
138991
  }
138872
138992
  return params;
138873
138993
  }
138874
- function encodeEscapes(path92) {
138875
- if (!path92.includes("\\")) return path92;
138876
- return path92.replace(/\\([:(){}\\])/g, (_, c10) => "\uFFFD" + ESCAPABLE.indexOf(c10));
138994
+ function encodeEscapes(path98) {
138995
+ if (!path98.includes("\\")) return path98;
138996
+ return path98.replace(/\\([:(){}\\])/g, (_, c10) => "\uFFFD" + ESCAPABLE.indexOf(c10));
138877
138997
  }
138878
138998
  function decodeEscapes(segment, prefix) {
138879
138999
  return segment.replace(/\uFFFD([0-5])/g, (_, i10) => prefix + ESCAPABLE[i10]);
@@ -138910,11 +139030,11 @@ function classSetOp(s) {
138910
139030
  }))) ;
138911
139031
  return found;
138912
139032
  }
138913
- function starGroups(path92) {
138914
- if (!path92.includes("(.*)")) return [path92];
139033
+ function starGroups(path98) {
139034
+ if (!path98.includes("(.*)")) return [path98];
138915
139035
  let count2 = 0;
138916
139036
  let unnamed;
138917
- return [path92.replace(/\\[\s\S]|(:[A-Za-z_]\w*)?\((?!\?)(\.\*\)(?!\*))?/g, (m10, name, star, at2) => {
139037
+ return [path98.replace(/\\[\s\S]|(:[A-Za-z_]\w*)?\((?!\?)(\.\*\)(?!\*))?/g, (m10, name, star, at2) => {
138918
139038
  if (m10[0] === "\\" || !star) {
138919
139039
  if (m10[0] === "(") count2++;
138920
139040
  return m10;
@@ -138923,25 +139043,25 @@ function starGroups(path92) {
138923
139043
  const k10 = count2;
138924
139044
  unnamed = (index) => index === k10 ? name.slice(1) : index > k10 ? index - 1 : index;
138925
139045
  } else count2++;
138926
- return /(^|[^\\])(\\\\)*([)*}?]|:[A-Za-z_]\w*)\{?$/.test(path92.slice(0, at2)) ? "\uFFFF*" : "*";
139046
+ return /(^|[^\\])(\\\\)*([)*}?]|:[A-Za-z_]\w*)\{?$/.test(path98.slice(0, at2)) ? "\uFFFF*" : "*";
138927
139047
  }), unnamed];
138928
139048
  }
138929
- function absolutePattern(path92) {
138930
- return /^[/{]/.test(path92) ? path92 : `/${path92}`;
139049
+ function absolutePattern(path98) {
139050
+ return /^[/{]/.test(path98) ? path98 : `/${path98}`;
138931
139051
  }
138932
- function dotSegments(path92) {
138933
- if (!DOT_SEGMENT.test(path92)) return path92;
138934
- const s = path92.split("/");
139052
+ function dotSegments(path98) {
139053
+ if (!DOT_SEGMENT.test(path98)) return path98;
139054
+ const s = path98.split("/");
138935
139055
  const out = [s[0]];
138936
139056
  let dot = false;
138937
139057
  for (let i10 = 1; i10 < s.length; i10++) {
138938
139058
  const m10 = /^(?:\.|%2e)(\.|%2e)?$/i.exec(s[i10]);
138939
139059
  if (m10) {
138940
- if (m10[1] && (out.length > 1 || out[0]) && !isText(out.pop())) invalidSyntax(DOT_SEGMENT_NEXT_TO, path92);
139060
+ if (m10[1] && (out.length > 1 || out[0]) && !isText(out.pop())) invalidSyntax(DOT_SEGMENT_NEXT_TO, path98);
138941
139061
  dot = true;
138942
139062
  continue;
138943
139063
  }
138944
- if (dot && /^[:*(]/.test(s[i10])) invalidSyntax(DOT_SEGMENT_NEXT_TO, path92);
139064
+ if (dot && /^[:*(]/.test(s[i10])) invalidSyntax(DOT_SEGMENT_NEXT_TO, path98);
138945
139065
  out.push(s[i10]);
138946
139066
  dot = false;
138947
139067
  }
@@ -139008,17 +139128,17 @@ function splitStar(segments, input2) {
139008
139128
  function oneCatchAll(input2) {
139009
139129
  throw new Error(`rou3: a route can have only one \`*\`, \`**\`, \`:name+\` or \`:name*\` (${input2})`);
139010
139130
  }
139011
- function splitRoute(path92) {
139012
- const s = splitPath(path92);
139131
+ function splitRoute(path98) {
139132
+ const s = splitPath(path98);
139013
139133
  while (s[s.length - 1] === "") s.pop();
139014
- if (path92.includes("**")) {
139134
+ if (path98.includes("**")) {
139015
139135
  for (let i10 = 0; i10 < s.length; i10++) if (/^\*\*[^:{}]/.test(s[i10])) s.splice(i10, 1, ...s[i10][2] === "*" ? ["**", s[i10].slice(2)] : [s[i10].slice(1)]);
139016
139136
  }
139017
139137
  return s;
139018
139138
  }
139019
- function expandedRouteId(path92) {
139020
- if (path92.charCodeAt(0) !== 47) return `{${expandedRouteId(`/${path92}`)}`;
139021
- return "/" + splitRoute(encodeEscapes(path92)).map((segment) => {
139139
+ function expandedRouteId(path98) {
139140
+ if (path98.charCodeAt(0) !== 47) return `{${expandedRouteId(`/${path98}`)}`;
139141
+ return "/" + splitRoute(encodeEscapes(path98)).map((segment) => {
139022
139142
  const key = segmentKey(segment);
139023
139143
  return typeof key === "string" ? key : segment;
139024
139144
  }).join("/");
@@ -139040,40 +139160,40 @@ function segmentWildcards(segment) {
139040
139160
  }
139041
139161
  return at2;
139042
139162
  }
139043
- function scanFirstGroup(path92) {
139163
+ function scanFirstGroup(path98) {
139044
139164
  let i10 = 0;
139045
139165
  let depth = 0;
139046
- for (; i10 < path92.length; i10++) {
139047
- const c10 = path92.charCodeAt(i10);
139166
+ for (; i10 < path98.length; i10++) {
139167
+ const c10 = path98.charCodeAt(i10);
139048
139168
  if (c10 === 92) i10++;
139049
139169
  else if (c10 === 40) depth++;
139050
139170
  else if (c10 === 41 && depth > 0) depth--;
139051
139171
  else if (c10 === 123 && depth === 0) break;
139052
139172
  }
139053
- if (i10 >= path92.length) return;
139173
+ if (i10 >= path98.length) return;
139054
139174
  let j10 = i10 + 1;
139055
139175
  depth = 0;
139056
- for (; j10 < path92.length; j10++) {
139057
- const c10 = path92.charCodeAt(j10);
139176
+ for (; j10 < path98.length; j10++) {
139177
+ const c10 = path98.charCodeAt(j10);
139058
139178
  if (c10 === 92) j10++;
139059
139179
  else if (c10 === 40) depth++;
139060
139180
  else if (c10 === 41 && depth > 0) depth--;
139061
139181
  else if (c10 === 125 && depth === 0) break;
139062
139182
  }
139063
- if (j10 >= path92.length) return;
139064
- const mod = path92[j10 + 1];
139183
+ if (j10 >= path98.length) return;
139184
+ const mod = path98[j10 + 1];
139065
139185
  const hasMod = mod === "?" || mod === "+" || mod === "*";
139066
139186
  return [
139067
- path92.slice(0, i10),
139068
- path92.slice(i10 + 1, j10).replace(NAME_CHAR, "\\$&"),
139069
- path92.slice(j10 + (hasMod ? 2 : 1)).replace(NAME_CHAR, "\\$&"),
139187
+ path98.slice(0, i10),
139188
+ path98.slice(i10 + 1, j10).replace(NAME_CHAR, "\\$&"),
139189
+ path98.slice(j10 + (hasMod ? 2 : 1)).replace(NAME_CHAR, "\\$&"),
139070
139190
  hasMod ? mod : void 0
139071
139191
  ];
139072
139192
  }
139073
139193
  var NAME_CHAR = /^[\w$\x80-]/;
139074
- function expandGroupDelimiters(path92, input2 = path92) {
139075
- if (!path92.includes("{")) return;
139076
- const group = scanFirstGroup(path92);
139194
+ function expandGroupDelimiters(path98, input2 = path98) {
139195
+ if (!path98.includes("{")) return;
139196
+ const group = scanFirstGroup(path98);
139077
139197
  if (!group) return;
139078
139198
  const [pre2, body, suf, mod] = group;
139079
139199
  if (mod === "+" || mod === "*") invalidSyntax(`unsupported \`{}${mod}\``, input2);
@@ -139175,43 +139295,43 @@ function linearRegExp(regexp) {
139175
139295
  return source === regexp.source ? regexp : new RegExp(`^${head}${source.slice(1)}`);
139176
139296
  }
139177
139297
  var upTo = (L, back) => L.replace(/^\\/, "").length < 2 ? `[^/${L}]*` : back ? `(?:[^/](?<!${L}))*` : `(?:(?!${L})[^/])*`;
139178
- function addRoute(ctx, method = "", path92, data) {
139298
+ function addRoute(ctx, method = "", path98, data) {
139179
139299
  method = method.toUpperCase();
139180
- path92 = absolutePattern(path92);
139181
- checkConstraints(path92);
139182
- const resolved = dotSegments(path92);
139300
+ path98 = absolutePattern(path98);
139301
+ checkConstraints(path98);
139302
+ const resolved = dotSegments(path98);
139183
139303
  const [route, unnamed] = starGroups(resolved);
139184
139304
  variants = void 0;
139185
- _add(ctx, method, route, data, unnamed && expandedRouteId(resolved), path92, unnamed);
139305
+ _add(ctx, method, route, data, unnamed && expandedRouteId(resolved), path98, unnamed);
139186
139306
  }
139187
139307
  var variants;
139188
- function _add(ctx, method, path92, data, route, input2 = path92, unnamed = same) {
139189
- const groupExpanded = expandGroupDelimiters(path92, input2);
139308
+ function _add(ctx, method, path98, data, route, input2 = path98, unnamed = same) {
139309
+ const groupExpanded = expandGroupDelimiters(path98, input2);
139190
139310
  if (groupExpanded) {
139191
139311
  if (groupExpanded[1] !== void 0) {
139192
- route ??= expandedRouteId(path92);
139312
+ route ??= expandedRouteId(path98);
139193
139313
  variants ??= {};
139194
139314
  }
139195
139315
  _add(ctx, method, groupExpanded[0], data, route, input2, unnamed);
139196
- if (groupExpanded[1] !== void 0) _add(ctx, method, groupExpanded[1], data, route, input2, /[*(]/.test(path92) ? skipGroup(path92, input2, unnamed) : unnamed);
139316
+ if (groupExpanded[1] !== void 0) _add(ctx, method, groupExpanded[1], data, route, input2, /[*(]/.test(path98) ? skipGroup(path98, input2, unnamed) : unnamed);
139197
139317
  return 0;
139198
139318
  }
139199
- path92 = encodeEscapes(path92);
139200
- const segments = splitRoute(path92);
139319
+ path98 = encodeEscapes(path98);
139320
+ const segments = splitRoute(path98);
139201
139321
  const expanded = expandModifiers(segments, input2);
139202
139322
  if (expanded) {
139203
- route ??= expandedRouteId(path92);
139323
+ route ??= expandedRouteId(path98);
139204
139324
  variants ??= {};
139205
139325
  let count2 = 0;
139206
139326
  for (const p of expanded) count2 = _add(ctx, method, p, data, route, input2, unnamed);
139207
139327
  return count2;
139208
139328
  }
139209
- const star = path92.includes("*");
139329
+ const star = path98.includes("*");
139210
139330
  const split = star ? splitStar(segments, input2) : void 0;
139211
139331
  if (split) {
139212
139332
  const [routes, join4, head] = split;
139213
139333
  if (routes.length > 1) {
139214
- route ??= expandedRouteId(path92);
139334
+ route ??= expandedRouteId(path98);
139215
139335
  variants ??= {};
139216
139336
  }
139217
139337
  let count2 = 0;
@@ -139331,8 +139451,8 @@ function _insert(ctx, method, segments, data, route, input2, unnamed, star, join
139331
139451
  return _unnamedParamIndex;
139332
139452
  }
139333
139453
  var same = (index) => index;
139334
- function skipGroup(path92, input2, unnamed = same) {
139335
- const [pre2, body] = scanFirstGroup(path92);
139454
+ function skipGroup(path98, input2, unnamed = same) {
139455
+ const [pre2, body] = scanFirstGroup(path98);
139336
139456
  if (!/[*(]/.test(body) && !pre2.endsWith("*")) return unnamed;
139337
139457
  const count2 = (p) => _add(createRouter(), "", p, void 0, void 0, input2);
139338
139458
  const before = count2(pre2);
@@ -139394,11 +139514,11 @@ function kindAt(m10, n10, p) {
139394
139514
  } else if ((suffix && index > suffix[0] ? index - suffix[0] - 1 + end : index) === p) return typeof name === "string" || plain ? 0 : 2;
139395
139515
  return 3;
139396
139516
  }
139397
- function findAllRoutes(ctx, method = "", path92, opts) {
139398
- if (opts?.normalize) path92 = normalizePath(path92);
139399
- const slash = path92.charCodeAt(path92.length - 1) === 47;
139400
- if (slash) path92 = path92.slice(0, -1);
139401
- const segments = splitPath(path92);
139517
+ function findAllRoutes(ctx, method = "", path98, opts) {
139518
+ if (opts?.normalize) path98 = normalizePath(path98);
139519
+ const slash = path98.charCodeAt(path98.length - 1) === 47;
139520
+ if (slash) path98 = path98.slice(0, -1);
139521
+ const segments = splitPath(path98);
139402
139522
  const matches2 = _findRanked(ctx, method, segments);
139403
139523
  let seen;
139404
139524
  for (let i10 = matches2.length - 1; i10 >= 0; i10--) {
@@ -139455,16 +139575,16 @@ function pushSorted(matches2, match, reverse) {
139455
139575
  }).sort((a10, b) => a10[1] - b[1]).map((e10) => e10[0]);
139456
139576
  for (const m10 of match) matches2.push(m10);
139457
139577
  }
139458
- function findRoute(ctx, method = "", path92, opts) {
139459
- if (opts?.normalize) path92 = normalizePath(path92);
139460
- const slash = path92.charCodeAt(path92.length - 1) === 47;
139461
- if (slash) path92 = path92.slice(0, -1);
139462
- const staticNode = ctx.static[path92];
139578
+ function findRoute(ctx, method = "", path98, opts) {
139579
+ if (opts?.normalize) path98 = normalizePath(path98);
139580
+ const slash = path98.charCodeAt(path98.length - 1) === 47;
139581
+ if (slash) path98 = path98.slice(0, -1);
139582
+ const staticNode = ctx.static[path98];
139463
139583
  if (staticNode && staticNode.methods) {
139464
139584
  const staticMatch = staticNode.methods[method] || staticNode.methods[""];
139465
139585
  if (staticMatch !== void 0) return { data: staticMatch[0].data };
139466
139586
  }
139467
- const segments = splitPath(path92);
139587
+ const segments = splitPath(path98);
139468
139588
  let match;
139469
139589
  if (segments.includes("") || ctx.root.hasSuffix && hasSuffixMatch(ctx.root, method, segments, 0)) {
139470
139590
  const matches2 = _findRanked(ctx, method, segments, true);
@@ -139760,8 +139880,8 @@ var STAR_SEGMENT = "*/";
139760
139880
  function routeToRegExp(route = "/") {
139761
139881
  route = absolutePattern(route);
139762
139882
  addRoute(createRouter(), "", route);
139763
- const [path92, unnamed] = starGroups(dotSegments(route));
139764
- return new RegExp(determinize(toRegExp(path92, route, unnamed).source));
139883
+ const [path98, unnamed] = starGroups(dotSegments(route));
139884
+ return new RegExp(determinize(toRegExp(path98, route, unnamed).source));
139765
139885
  }
139766
139886
  function toRegExp(route, input2, unnamed) {
139767
139887
  const inlineOptional = inlineOptionalGroup(route, input2, unnamed);
@@ -140118,7 +140238,7 @@ var OpenAPIMatcher = class {
140118
140238
  this.rootRouter = router;
140119
140239
  this.index(router);
140120
140240
  }
140121
- index(router, path92 = []) {
140241
+ index(router, path98 = []) {
140122
140242
  const routes = [];
140123
140243
  const lazyResults = walkProcedureContractsSync(router, (contract, path210) => {
140124
140244
  if (!value2(this.filter, contract, path210)) {
@@ -140139,7 +140259,7 @@ var OpenAPIMatcher = class {
140139
140259
  ...route
140140
140260
  }
140141
140261
  });
140142
- }, path92);
140262
+ }, path98);
140143
140263
  const pendingLazyRouters = lazyResults.map((result) => {
140144
140264
  const prefix = getOpenAPIMeta(result.router)?.prefix;
140145
140265
  return {
@@ -140239,10 +140359,10 @@ var OpenAPIMatcher = class {
140239
140359
  return entry.procedure;
140240
140360
  }
140241
140361
  };
140242
- function toRou3Route(path92) {
140243
- const dynamicParams = getDynamicPathParams(path92);
140362
+ function toRou3Route(path98) {
140363
+ const dynamicParams = getDynamicPathParams(path98);
140244
140364
  if (!dynamicParams) {
140245
- return { pattern: toRou3Literal(path92) };
140365
+ return { pattern: toRou3Literal(path98) };
140246
140366
  }
140247
140367
  let pattern = "";
140248
140368
  let literalStart = 0;
@@ -140251,11 +140371,11 @@ function toRou3Route(path92) {
140251
140371
  for (const param of dynamicParams) {
140252
140372
  const key = `p${params.length}`;
140253
140373
  params.push([key, param.parameterName]);
140254
- pattern += toRou3Literal(path92.slice(literalStart, param.startIndex));
140374
+ pattern += toRou3Literal(path98.slice(literalStart, param.startIndex));
140255
140375
  literalStart = param.startIndex + param.segment.length;
140256
140376
  if (param.allowsSlash) {
140257
140377
  if (catchAllKey !== void 0) {
140258
- throw new TypeError(`OpenAPI path "${path92}" has more than one catch-all param ({+name}), but only one is supported per path.`);
140378
+ throw new TypeError(`OpenAPI path "${path98}" has more than one catch-all param ({+name}), but only one is supported per path.`);
140259
140379
  }
140260
140380
  catchAllKey = key;
140261
140381
  pattern += `:${key}(.*)`;
@@ -140263,7 +140383,7 @@ function toRou3Route(path92) {
140263
140383
  pattern += `:${key}`;
140264
140384
  }
140265
140385
  }
140266
- pattern += toRou3Literal(path92.slice(literalStart));
140386
+ pattern += toRou3Literal(path98.slice(literalStart));
140267
140387
  return { pattern, params, catchAllKey };
140268
140388
  }
140269
140389
  var ROU3_SYNTAX_REGEX = /[\\:*?+(){}]|(?<![^/])\.(?=\.?(?:\/|$))/g;
@@ -140271,8 +140391,8 @@ function toRou3Literal(text5) {
140271
140391
  const normalized = NORMALIZABLE_PATHNAME_REGEX2.test(text5) ? normalizeRou3Path(text5) : text5;
140272
140392
  return normalized.replace(ROU3_SYNTAX_REGEX, "\\$&");
140273
140393
  }
140274
- function normalizeRou3Path(path92) {
140275
- return path92.split("/").map((segment) => safeDecodeURIComponent2(segment).replace(ROU3_ENCODED_SEGMENT_TEXT_REGEX, safeEncodeURIComponent2)).join("/");
140394
+ function normalizeRou3Path(path98) {
140395
+ return path98.split("/").map((segment) => safeDecodeURIComponent2(segment).replace(ROU3_ENCODED_SEGMENT_TEXT_REGEX, safeEncodeURIComponent2)).join("/");
140276
140396
  }
140277
140397
  function toRou3PrefixMatcher(prefix) {
140278
140398
  const catchAll = getDynamicPathParams(prefix)?.find((param) => param.allowsSlash);
@@ -140362,7 +140482,7 @@ var OpenAPIHandlerCodecCore = class {
140362
140482
  /**
140363
140483
  * @throws {TypeError} If `outputStructure` is "detailed" and the output doesn't match the expected structure.
140364
140484
  */
140365
- encodeOutput(output2, procedure, path92) {
140485
+ encodeOutput(output2, procedure, path98) {
140366
140486
  const meta3 = getOpenAPIMeta(procedure);
140367
140487
  const successStatus = meta3?.successStatus ?? DEFAULT_SUCCESS_STATUS;
140368
140488
  const outputStructure = meta3?.outputStructure ?? DEFAULT_OPENAPI_OUTPUT_STRUCTURE;
@@ -140375,7 +140495,7 @@ var OpenAPIHandlerCodecCore = class {
140375
140495
  }
140376
140496
  if (!isValidDetailedOutput(output2)) {
140377
140497
  throw new TypeError(`
140378
- Invalid "detailed" output structure returned by procedure (${path92.join(".")}):
140498
+ Invalid "detailed" output structure returned by procedure (${path98.join(".")}):
140379
140499
  \u2022 Expected an object with optional properties:
140380
140500
  - status (number <400)
140381
140501
  - headers (object)
@@ -140988,7 +141108,7 @@ function profileValue(name, paths) {
140988
141108
  function createConfigApiRouter(deps) {
140989
141109
  const authed = doorApiAuth(deps.expectedToken);
140990
141110
  const { paths } = deps;
140991
- const route = (path92, summary) => authed.meta(openapi({ method: "POST", path: path92, summary, tags: [CONFIG_API_TAG] }));
141111
+ const route = (path98, summary) => authed.meta(openapi({ method: "POST", path: path98, summary, tags: [CONFIG_API_TAG] }));
140992
141112
  return {
140993
141113
  config: {
140994
141114
  identity: {
@@ -143228,8 +143348,8 @@ function createCodexRouteMount(ports, upstreamBase, provider) {
143228
143348
  request7.body.resume();
143229
143349
  return;
143230
143350
  }
143231
- const path92 = new URL(request7.url, "http://127.0.0.1").pathname;
143232
- const translated = { method: request7.method, path: path92, body, signal: request7.signal };
143351
+ const path98 = new URL(request7.url, "http://127.0.0.1").pathname;
143352
+ const translated = { method: request7.method, path: path98, body, signal: request7.signal };
143233
143353
  const routed = await route(translated);
143234
143354
  if (request7.signal.aborted) {
143235
143355
  return;
@@ -143463,9 +143583,9 @@ function descendExpanded(root, value3, key) {
143463
143583
  }
143464
143584
  }
143465
143585
  function relaxRejectedRecursiveProperty(request7, body) {
143466
- const path92 = rejectedPath(body);
143467
- if (path92 === void 0) return void 0;
143468
- const propertyIndices = path92.flatMap((part, index) => part === "properties" && path92[index + 1] !== void 0 ? [index] : []).reverse();
143586
+ const path98 = rejectedPath(body);
143587
+ if (path98 === void 0) return void 0;
143588
+ const propertyIndices = path98.flatMap((part, index) => part === "properties" && path98[index + 1] !== void 0 ? [index] : []).reverse();
143469
143589
  if (propertyIndices.length === 0) return void 0;
143470
143590
  const copy2 = structuredClone(request7);
143471
143591
  let changed = false;
@@ -143474,14 +143594,14 @@ function relaxRejectedRecursiveProperty(request7, body) {
143474
143594
  const schema = declaration.parametersJsonSchema;
143475
143595
  if (schema === void 0) continue;
143476
143596
  let leaf = schema;
143477
- for (const part of path92) leaf = descendExpanded(schema, leaf, part);
143597
+ for (const part of path98) leaf = descendExpanded(schema, leaf, part);
143478
143598
  if (!record2(leaf) || typeof leaf.$ref !== "string") continue;
143479
143599
  let repairedProperty = false;
143480
143600
  for (const propertyIndex of propertyIndices) {
143481
- const name = path92[propertyIndex + 1];
143601
+ const name = path98[propertyIndex + 1];
143482
143602
  if (name === void 0) continue;
143483
143603
  let owner = schema;
143484
- for (const part of path92.slice(0, propertyIndex)) owner = descendExpanded(schema, owner, part);
143604
+ for (const part of path98.slice(0, propertyIndex)) owner = descendExpanded(schema, owner, part);
143485
143605
  if (!record2(owner) || !Array.isArray(owner.required) || !owner.required.includes(name) || !record2(owner.properties)) continue;
143486
143606
  const property = owner.properties[name];
143487
143607
  if (!record2(property)) continue;
@@ -143495,8 +143615,8 @@ function relaxRejectedRecursiveProperty(request7, body) {
143495
143615
  }
143496
143616
  if (!repairedProperty) {
143497
143617
  let parent = schema;
143498
- for (const part of path92.slice(0, -1)) parent = descendExpanded(schema, parent, part);
143499
- const key = path92.at(-1);
143618
+ for (const part of path98.slice(0, -1)) parent = descendExpanded(schema, parent, part);
143619
+ const key = path98.at(-1);
143500
143620
  const truncated = { description: "Recursive value: the original tool schema validates this value." };
143501
143621
  if (record2(parent) && key !== void 0 && Object.hasOwn(parent, key)) {
143502
143622
  parent[key] = truncated;
@@ -143988,8 +144108,8 @@ function createAntigravityRouteMount(ports, upstreamBase, provider) {
143988
144108
  request7.body.resume();
143989
144109
  return;
143990
144110
  }
143991
- const path92 = new URL(request7.url, "http://127.0.0.1").pathname;
143992
- const translated = { method: request7.method, path: path92, body, signal: request7.signal };
144111
+ const path98 = new URL(request7.url, "http://127.0.0.1").pathname;
144112
+ const translated = { method: request7.method, path: path98, body, signal: request7.signal };
143993
144113
  const routed = await route(translated);
143994
144114
  if (request7.signal.aborted) {
143995
144115
  return;
@@ -144033,7 +144153,7 @@ function createPassthroughRoute(name, target) {
144033
144153
  headroomUpstream: target.headroomUpstream,
144034
144154
  serve: async (request7, response) => {
144035
144155
  const incoming = new URL(request7.url, "http://127.0.0.1");
144036
- const path92 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
144156
+ const path98 = target.stripPrefix !== void 0 && incoming.pathname.startsWith(target.stripPrefix) ? incoming.pathname.slice(target.stripPrefix.length) : incoming.pathname;
144037
144157
  const headers = forwardableHeaders(request7.headers);
144038
144158
  delete headers.host;
144039
144159
  await new Promise((resolve3) => {
@@ -144041,7 +144161,7 @@ function createPassthroughRoute(name, target) {
144041
144161
  host: base.hostname,
144042
144162
  port: base.port === "" ? void 0 : Number(base.port),
144043
144163
  method: request7.method,
144044
- path: `${basePath}${path92}${incoming.search}`,
144164
+ path: `${basePath}${path98}${incoming.search}`,
144045
144165
  headers,
144046
144166
  agent
144047
144167
  };
@@ -144247,13 +144367,13 @@ async function scanRequestHead(request7, wholeBody = false) {
144247
144367
  }
144248
144368
 
144249
144369
  // src/frontdoor/providerRoute.ts
144250
- var isRcSelfHostPath = (path92) => path92 === "/v1/code/sessions" || path92.startsWith("/v1/code/sessions/") || path92 === "/v1/sessions" || path92.startsWith("/v1/sessions/");
144370
+ var isRcSelfHostPath = (path98) => path98 === "/v1/code/sessions" || path98.startsWith("/v1/code/sessions/") || path98 === "/v1/sessions" || path98.startsWith("/v1/sessions/");
144251
144371
  function scopeSessionProviderPath(request7) {
144252
144372
  if (request7.session.provider === void 0) {
144253
144373
  return request7;
144254
144374
  }
144255
- const path92 = new URL(request7.url, "http://127.0.0.1").pathname;
144256
- if (!path92.startsWith("/v1/") || isRcSelfHostPath(path92)) {
144375
+ const path98 = new URL(request7.url, "http://127.0.0.1").pathname;
144376
+ if (!path98.startsWith("/v1/") || isRcSelfHostPath(path98)) {
144257
144377
  return request7;
144258
144378
  }
144259
144379
  return { ...request7, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(request7.session.provider)}${request7.url}` };
@@ -144388,13 +144508,13 @@ function createProviderRouteResolver(deps) {
144388
144508
  return route;
144389
144509
  };
144390
144510
  const resolve3 = (request7) => {
144391
- const path92 = new URL(request7.url, "http://127.0.0.1").pathname;
144392
- const scoped = parseProviderPath(path92);
144511
+ const path98 = new URL(request7.url, "http://127.0.0.1").pathname;
144512
+ const scoped = parseProviderPath(path98);
144393
144513
  if (scoped === void 0) {
144394
- if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path92)) {
144514
+ if (deps.rcSelfHostRoute !== void 0 && isRcSelfHostPath(path98)) {
144395
144515
  return { ok: true, route: deps.rcSelfHostRoute };
144396
144516
  }
144397
- return path92.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path92}` };
144517
+ return path98.startsWith("/v1/") ? { ok: true, route: oauthRoute } : { ok: false, status: HTTP_STATUS.notFound, message: `no such endpoint: ${path98}` };
144398
144518
  }
144399
144519
  const { provider } = scoped;
144400
144520
  let definition;
@@ -144490,8 +144610,8 @@ function createProviderRouteResolver(deps) {
144490
144610
  let modelChoice;
144491
144611
  const visited = /* @__PURE__ */ new Set();
144492
144612
  for (; ; ) {
144493
- const path92 = new URL(current.url, "http://127.0.0.1").pathname;
144494
- const scoped = parseProviderPath(path92);
144613
+ const path98 = new URL(current.url, "http://127.0.0.1").pathname;
144614
+ const scoped = parseProviderPath(path98);
144495
144615
  const providerName = scoped?.provider ?? current.session.provider;
144496
144616
  if (providerName !== void 0 && visited.has(providerName)) {
144497
144617
  return { ok: false, status: HTTP_STATUS.internalServerError, message: `provider routing cycle: ${[...visited, providerName].join(" -> ")}` };
@@ -144506,7 +144626,7 @@ function createProviderRouteResolver(deps) {
144506
144626
  } catch {
144507
144627
  routes = void 0;
144508
144628
  }
144509
- const resolvesNames = !nameResolved && !isRcSelfHostPath(path92);
144629
+ const resolvesNames = !nameResolved && !isRcSelfHostPath(path98);
144510
144630
  if (resolvesNames) {
144511
144631
  const scan2 = await scanRequestHead(current, true);
144512
144632
  if (scan2.replayed === void 0) {
@@ -144545,7 +144665,7 @@ function createProviderRouteResolver(deps) {
144545
144665
  }
144546
144666
  if (routed.provider !== providerName) {
144547
144667
  const scopedPrefix = providerName === void 0 ? void 0 : `${PROVIDER_PATH_PREFIX}${encodeURIComponent(providerName)}`;
144548
- const rest2 = scopedPrefix !== void 0 && path92.startsWith(scopedPrefix) ? path92.slice(scopedPrefix.length) : path92;
144668
+ const rest2 = scopedPrefix !== void 0 && path98.startsWith(scopedPrefix) ? path98.slice(scopedPrefix.length) : path98;
144549
144669
  const query2 = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
144550
144670
  const carried = replay;
144551
144671
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(routed.provider)}${rest2}${query2}`, body: carried.body, headers: carried.headers };
@@ -144599,7 +144719,7 @@ function createProviderRouteResolver(deps) {
144599
144719
  const headers = Object.fromEntries(Object.entries(replay.headers).filter(([name]) => name.toLowerCase() !== "content-length"));
144600
144720
  replay = { ...replay, headers, body: import_node_stream3.Readable.from([Buffer.from(rewritten, "utf8")]) };
144601
144721
  }
144602
- const rest = scoped === void 0 ? path92 : path92.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
144722
+ const rest = scoped === void 0 ? path98 : path98.slice(`${PROVIDER_PATH_PREFIX}${encodeURIComponent(scoped.provider)}`.length);
144603
144723
  const query = current.url.includes("?") ? current.url.slice(current.url.indexOf("?")) : "";
144604
144724
  current = { ...current, url: `${PROVIDER_PATH_PREFIX}${encodeURIComponent(matched.provider)}${rest}${query}`, body: replay.body, headers: replay.headers };
144605
144725
  }
@@ -150586,15 +150706,15 @@ function parseNumstat(output2) {
150586
150706
  if (addedText === void 0 || deletedText === void 0 || pathText === void 0) {
150587
150707
  continue;
150588
150708
  }
150589
- const path92 = pathText === "" ? fields[index + 2] : pathText;
150709
+ const path98 = pathText === "" ? fields[index + 2] : pathText;
150590
150710
  if (pathText === "") {
150591
150711
  index += 2;
150592
150712
  }
150593
150713
  const lines = { added: Number(addedText), deleted: Number(deletedText) };
150594
- if (path92 !== void 0 && Number.isInteger(lines.added) && Number.isInteger(lines.deleted)) {
150714
+ if (path98 !== void 0 && Number.isInteger(lines.added) && Number.isInteger(lines.deleted)) {
150595
150715
  added += lines.added;
150596
150716
  deleted += lines.deleted;
150597
- byPath.set(path92, lines);
150717
+ byPath.set(path98, lines);
150598
150718
  }
150599
150719
  }
150600
150720
  return { total: { added, deleted }, byPath };
@@ -151633,11 +151753,11 @@ function targetText(tool, columns) {
151633
151753
  if (!FILE_TOOLS.includes(tool.name)) {
151634
151754
  return truncateWithEllipsis(target, room, ELLIPSIS);
151635
151755
  }
151636
- const path92 = target.replaceAll("\\", "/");
151637
- if (visibleLength(path92) <= room) {
151638
- return path92;
151756
+ const path98 = target.replaceAll("\\", "/");
151757
+ if (visibleLength(path98) <= room) {
151758
+ return path98;
151639
151759
  }
151640
- const file2 = path92.split("/").pop() ?? path92;
151760
+ const file2 = path98.split("/").pop() ?? path98;
151641
151761
  return visibleLength(DIRECTORY_ELLIPSIS) + visibleLength(file2) > room ? truncateWithEllipsis(file2, room, FILE_ELLIPSIS) : `${DIRECTORY_ELLIPSIS}${file2}`;
151642
151762
  }
151643
151763
  function finishedByKind(tools) {
@@ -155394,8 +155514,8 @@ function getErrorMap2() {
155394
155514
 
155395
155515
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v3/helpers/parseUtil.js
155396
155516
  var makeIssue = (params) => {
155397
- const { data, path: path92, errorMaps, issueData } = params;
155398
- const fullPath = [...path92, ...issueData.path || []];
155517
+ const { data, path: path98, errorMaps, issueData } = params;
155518
+ const fullPath = [...path98, ...issueData.path || []];
155399
155519
  const fullIssue = {
155400
155520
  ...issueData,
155401
155521
  path: fullPath
@@ -155510,11 +155630,11 @@ var errorUtil;
155510
155630
 
155511
155631
  // node_modules/.pnpm/zod@4.6.7/node_modules/zod/v3/types.js
155512
155632
  var ParseInputLazyPath = class {
155513
- constructor(parent, value3, path92, key) {
155633
+ constructor(parent, value3, path98, key) {
155514
155634
  this._cachedPath = [];
155515
155635
  this.parent = parent;
155516
155636
  this.data = value3;
155517
- this._path = path92;
155637
+ this._path = path98;
155518
155638
  this._key = key;
155519
155639
  }
155520
155640
  get path() {
@@ -159077,11 +159197,11 @@ function normalizeObjectSchema(schema) {
159077
159197
  }
159078
159198
  return void 0;
159079
159199
  }
159080
- function getDotPath(path92) {
159081
- if (path92.length === 0) {
159200
+ function getDotPath(path98) {
159201
+ if (path98.length === 0) {
159082
159202
  return "object root";
159083
159203
  }
159084
- return path92.reduce((acc, seg, index) => {
159204
+ return path98.reduce((acc, seg, index) => {
159085
159205
  if (index === 0) {
159086
159206
  return String(seg);
159087
159207
  }
@@ -164193,11 +164313,83 @@ function registerHeadroomCommand(program2, deps) {
164193
164313
  }
164194
164314
 
164195
164315
  // src/supervise/commands.ts
164316
+ var import_node_fs33 = require("node:fs");
164196
164317
  init_realPorts();
164197
164318
 
164319
+ // src/supervise/hookGuard.ts
164320
+ var import_node_path84 = __toESM(require("node:path"), 1);
164321
+ init_lock();
164322
+ function prefixOf(sessionId) {
164323
+ return `${sessionId}.hook.`;
164324
+ }
164325
+ function hooksPending(fs36, paths, pool, sessionId) {
164326
+ return fs36.readdir(stateDirOf(paths, pool)).some((name) => name.startsWith(prefixOf(sessionId)) && name.endsWith(".json"));
164327
+ }
164328
+ function currentConversation(fs36, paths, pool, sessionId) {
164329
+ const state = readSessionState(fs36, paths, pool, sessionId);
164330
+ return state === void 0 || state.unavailable === true || hooksPending(fs36, paths, pool, sessionId) ? void 0 : state.conversationId ?? sessionId;
164331
+ }
164332
+ function announceHook(deps, pool, sessionId) {
164333
+ const dir = stateDirOf(deps.paths, pool);
164334
+ deps.fs.mkdirPrivate(dir);
164335
+ const marker = import_node_path84.default.join(dir, `${prefixOf(sessionId)}${String(deps.pid)}.json`);
164336
+ const created = deps.fs.writeFileExclusive(marker, `${JSON.stringify({ pid: deps.pid })}
164337
+ `);
164338
+ return {
164339
+ acquire: () => {
164340
+ const lock = acquireIdentityLock({ identity: `mark-${sessionId}`, dir, fs: deps.fs, nowMs: deps.now, pid: deps.pid, isRunning: deps.isRunning, sleep: deps.sleep, ...deps.maxAttempts === void 0 ? {} : { maxAttempts: deps.maxAttempts } });
164341
+ return {
164342
+ finish: (success2, newTurn) => {
164343
+ try {
164344
+ if (success2 && newTurn) {
164345
+ for (const name of deps.fs.readdir(dir)) {
164346
+ if (!name.startsWith(prefixOf(sessionId)) || !name.endsWith(".json")) {
164347
+ continue;
164348
+ }
164349
+ const pidText = name.slice(prefixOf(sessionId).length, -".json".length);
164350
+ const pid = Number(pidText);
164351
+ if (Number.isSafeInteger(pid) && pid > 0 && pid !== deps.pid && !deps.isRunning(pid)) {
164352
+ deps.fs.removeRecursive(import_node_path84.default.join(dir, name));
164353
+ }
164354
+ }
164355
+ }
164356
+ if (success2 && (created || newTurn)) {
164357
+ deps.fs.removeRecursive(marker);
164358
+ }
164359
+ } finally {
164360
+ lock.release();
164361
+ }
164362
+ }
164363
+ };
164364
+ }
164365
+ };
164366
+ }
164367
+
164198
164368
  // src/supervise/marks.ts
164369
+ var import_node_path85 = __toESM(require("node:path"), 1);
164370
+ init_zod();
164199
164371
  init_resumeContext();
164200
164372
  init_shellQuote();
164373
+ var MarkHookInputSchema = external_exports.object({
164374
+ session_id: external_exports.uuid(),
164375
+ transcript_path: external_exports.string().refine(import_node_path85.default.isAbsolute),
164376
+ prompt_id: external_exports.uuid().optional(),
164377
+ hook_event_name: external_exports.enum(["SessionStart", "UserPromptSubmit", "Stop", "StopFailure"]),
164378
+ background_tasks: external_exports.array(external_exports.unknown()).optional(),
164379
+ session_crons: external_exports.array(external_exports.unknown()).optional()
164380
+ });
164381
+ function markFromHook(requested, payload) {
164382
+ const input2 = MarkHookInputSchema.parse(payload);
164383
+ const starts = input2.hook_event_name === "SessionStart" || input2.hook_event_name === "UserPromptSubmit";
164384
+ if (requested === "busy" !== starts) {
164385
+ throw new Error(`unexpected ${input2.hook_event_name} hook for a ${requested} mark`);
164386
+ }
164387
+ if (input2.hook_event_name === "UserPromptSubmit" && input2.prompt_id === void 0) {
164388
+ throw new Error("UserPromptSubmit did not identify its prompt");
164389
+ }
164390
+ const idle = input2.hook_event_name === "Stop" && input2.prompt_id !== void 0 && input2.background_tasks?.length === 0 && input2.session_crons?.length === 0;
164391
+ return { conversationId: input2.session_id, transcriptPath: input2.transcript_path, ...input2.prompt_id === void 0 ? {} : { promptId: input2.prompt_id }, sessionStart: input2.hook_event_name === "SessionStart", mark: idle ? "idle" : "busy" };
164392
+ }
164201
164393
  var MARK_HOOK_TIMEOUT_SECONDS = 10;
164202
164394
  var SUPERVISE_MARK_COMMAND = "__supervise-mark";
164203
164395
  function markHooksSettings(invocation, root, pool, sessionId) {
@@ -164212,21 +164404,42 @@ function markHooksSettings(invocation, root, pool, sessionId) {
164212
164404
  ]
164213
164405
  }
164214
164406
  ];
164215
- return JSON.stringify({ hooks: { UserPromptSubmit: hook("busy"), Stop: hook("idle"), StopFailure: hook("idle") } });
164407
+ return JSON.stringify({ hooks: { SessionStart: hook("busy"), UserPromptSubmit: hook("busy"), Stop: hook("idle"), StopFailure: hook("idle") } });
164408
+ }
164409
+ function recordUnknown(context, pool, sessionId) {
164410
+ const previous = readSessionState(context.fs, context.paths, pool, sessionId);
164411
+ writeSessionState(context.fs, context.paths, pool, sessionId, { ...previous, mark: "busy", unavailable: true, at: new Date(context.now()).toISOString() });
164216
164412
  }
164217
- function recordMark(context, pool, sessionId, mark) {
164413
+ function recordMark(context, pool, sessionId, mark, conversationId = sessionId, transcriptPath, promptId, ending2 = false, sessionStart = false) {
164414
+ if (ending2 && promptId === void 0) {
164415
+ recordUnknown(context, pool, sessionId);
164416
+ return;
164417
+ }
164218
164418
  const previous = readSessionState(context.fs, context.paths, pool, sessionId);
164219
- let contextTokens = previous?.contextTokens;
164419
+ if ((mark === "idle" || ending2) && promptId !== void 0 && ((previous?.conversationId ?? sessionId) !== conversationId || previous?.promptId !== promptId)) {
164420
+ return;
164421
+ }
164422
+ const sameConversation = (previous?.conversationId ?? sessionId) === conversationId;
164423
+ const currentPrompt = promptId ?? (sessionStart && sameConversation ? previous?.promptId : void 0);
164424
+ let contextTokens = sameConversation ? previous?.contextTokens : void 0;
164220
164425
  if (mark === "idle") {
164221
- if (context.configDir === void 0) {
164426
+ if (transcriptPath === void 0 && context.configDir === void 0) {
164222
164427
  throw new Error("CLAUDE_CONFIG_DIR is not set, so the session's transcript cannot be found");
164223
164428
  }
164224
- contextTokens = resumedContextTokens(context.fs, { claudeHome: context.configDir, cwd: context.cwd, passthrough: ["--resume", sessionId] }) ?? contextTokens;
164429
+ const transcript = transcriptPath === void 0 ? void 0 : context.fs.readFileUtf8(transcriptPath);
164430
+ if (transcriptPath === void 0 && context.configDir !== void 0) {
164431
+ contextTokens = resumedContextTokens(context.fs, { claudeHome: context.configDir, cwd: context.cwd, passthrough: ["--resume", conversationId] }) ?? contextTokens;
164432
+ } else if (transcript !== void 0) {
164433
+ contextTokens = contextTokensOfTranscript(transcript) ?? contextTokens;
164434
+ }
164225
164435
  }
164226
164436
  writeSessionState(context.fs, context.paths, pool, sessionId, {
164227
164437
  mark,
164438
+ ...conversationId === sessionId ? {} : { conversationId },
164439
+ ...transcriptPath === void 0 ? {} : { transcriptPath },
164440
+ ...currentPrompt === void 0 ? {} : { promptId: currentPrompt },
164228
164441
  ...contextTokens === void 0 ? {} : { contextTokens },
164229
- ...previous?.compacted === true ? { compacted: true } : {},
164442
+ ...sameConversation && previous?.compacted === true ? { compacted: true } : {},
164230
164443
  at: new Date(context.now()).toISOString()
164231
164444
  });
164232
164445
  }
@@ -164238,12 +164451,27 @@ function isTurnMark(value3) {
164238
164451
  }
164239
164452
  function registerSuperviseMarkCommand(program2, deps) {
164240
164453
  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) => {
164454
+ const context = { fs: realFarmFs, paths: deps.paths, now: Date.now, configDir: process.env.CLAUDE_CONFIG_DIR, cwd: process.cwd() };
164455
+ let guard;
164241
164456
  try {
164457
+ const announcement = announceHook({ fs: realFarmFs, paths: deps.paths, now: Date.now, pid: process.pid, isRunning: realIsProcessRunning, sleep: realSleepSync }, pool, session);
164458
+ const raw = (0, import_node_fs33.readFileSync)(0, "utf8");
164459
+ guard = announcement.acquire();
164242
164460
  if (!isTurnMark(mark)) {
164243
164461
  throw new Error(`"${mark}" is not a turn mark: use busy or idle`);
164244
164462
  }
164245
- recordMark({ fs: realFarmFs, paths: deps.paths, now: Date.now, configDir: process.env.CLAUDE_CONFIG_DIR, cwd: process.cwd() }, pool, session, mark);
164463
+ const payload = JSON.parse(raw);
164464
+ const actual = markFromHook(mark, payload);
164465
+ recordMark(context, pool, session, actual.mark, actual.conversationId, actual.transcriptPath, actual.promptId, mark === "idle", actual.sessionStart);
164466
+ guard.finish(true, mark === "busy");
164246
164467
  } catch (error63) {
164468
+ if (guard !== void 0) {
164469
+ try {
164470
+ recordUnknown(context, pool, session);
164471
+ } finally {
164472
+ guard.finish(false, false);
164473
+ }
164474
+ }
164247
164475
  console.error(`agent-shim: could not record the turn mark: ${error63 instanceof Error ? error63.message : String(error63)}`);
164248
164476
  deps.exit(1);
164249
164477
  }
@@ -164254,7 +164482,7 @@ function registerSuperviseMarkCommand(program2, deps) {
164254
164482
  init_zod();
164255
164483
 
164256
164484
  // src/realCatalogueRefresh.ts
164257
- var import_node_path84 = __toESM(require("node:path"), 1);
164485
+ var import_node_path86 = __toESM(require("node:path"), 1);
164258
164486
  var import_node_os21 = __toESM(require("node:os"), 1);
164259
164487
  init_blockingSpawn();
164260
164488
  init_translate2();
@@ -164329,8 +164557,8 @@ async function refreshCatalogueForReal(paths, name, env, ...owner) {
164329
164557
  const provider = readProvider(paths, name);
164330
164558
  const login = provider?.kind === "codex" ? resolveCodexConfig(provider.codex).login : void 0;
164331
164559
  const configuredHome = env.CODEX_HOME;
164332
- const home = configuredHome === void 0 || configuredHome === "" ? import_node_path84.default.join(import_node_os21.default.homedir(), ".codex") : configuredHome;
164333
- const source = login === void 0 ? void 0 : login === "chatgpt-sign-in" ? paths.chatgptSignInFile : import_node_path84.default.resolve(home, "auth.json");
164560
+ const home = configuredHome === void 0 || configuredHome === "" ? import_node_path86.default.join(import_node_os21.default.homedir(), ".codex") : configuredHome;
164561
+ const source = login === void 0 ? void 0 : login === "chatgpt-sign-in" ? paths.chatgptSignInFile : import_node_path86.default.resolve(home, "auth.json");
164334
164562
  let revision = source === void 0 ? void 0 : realFsPort.fileRevision?.(source);
164335
164563
  const codexAuth = login === void 0 ? void 0 : createCodexRoutePorts((line) => {
164336
164564
  console.error(line);
@@ -164376,7 +164604,7 @@ async function refreshCatalogueForReal(paths, name, env, ...owner) {
164376
164604
  if (source === void 0 || revision === void 0) throw new Error("Codex login revision is unavailable");
164377
164605
  if (realFsPort.fileRevision?.(source) !== revision) throw new Error("Codex login changed during catalogue refresh");
164378
164606
  const destination = catalogueBindingPath(paths, providerName, supervisorPid, generation);
164379
- realFarmFs.mkdirp(import_node_path84.default.dirname(destination));
164607
+ realFarmFs.mkdirp(import_node_path86.default.dirname(destination));
164380
164608
  realFarmFs.writeFilePrivate(destination, JSON.stringify({ fingerprint, source, revision }));
164381
164609
  }
164382
164610
  });
@@ -164386,7 +164614,7 @@ async function refreshCatalogueForReal(paths, name, env, ...owner) {
164386
164614
  init_realPorts();
164387
164615
 
164388
164616
  // src/usage/realJobRunner.ts
164389
- var import_node_path85 = __toESM(require("node:path"), 1);
164617
+ var import_node_path87 = __toESM(require("node:path"), 1);
164390
164618
  init_conditions();
164391
164619
  init_identityClaude();
164392
164620
  var JOB_LAUNCH_FLAGS = ["--no-headroom", "--no-remote-control", "--track-usage"];
@@ -164399,7 +164627,7 @@ ${outcome.trimEnd()}
164399
164627
  }
164400
164628
  function createRealJobRunner(params) {
164401
164629
  return async (name, identity, job) => {
164402
- const logFile = import_node_path85.default.join(params.paths.jobLogsDir, `${name}.log`);
164630
+ const logFile = import_node_path87.default.join(params.paths.jobLogsDir, `${name}.log`);
164403
164631
  const append = (outcome) => {
164404
164632
  params.fs.mkdirPrivate(params.paths.jobLogsDir);
164405
164633
  params.fs.appendFilePrivate(logFile, logEntry(name, identity, params.now(), outcome));
@@ -164458,7 +164686,7 @@ function registerHeadlessCommands(program2, deps) {
164458
164686
  }
164459
164687
 
164460
164688
  // src/jobs.ts
164461
- var import_node_path86 = __toESM(require("node:path"), 1);
164689
+ var import_node_path88 = __toESM(require("node:path"), 1);
164462
164690
  init_commandDeps();
164463
164691
  init_cliError();
164464
164692
  init_schema();
@@ -164485,7 +164713,7 @@ function jobOf(options) {
164485
164713
  target: options.identity === void 0 ? { pool: options.pool ?? "" } : { identity: options.identity },
164486
164714
  trigger: options.at === void 0 ? { beforeReset: options.beforeReset ?? "fiveHour", lead: options.lead ?? "" } : { at: options.at },
164487
164715
  prompt: options.prompt,
164488
- cwd: import_node_path86.default.resolve(options.cwd ?? process.cwd()),
164716
+ cwd: import_node_path88.default.resolve(options.cwd ?? process.cwd()),
164489
164717
  timeout: options.timeout,
164490
164718
  ...options.model === void 0 ? {} : { model: options.model },
164491
164719
  ...options.allowedTool === void 0 ? {} : { allowedTools: options.allowedTool }
@@ -164558,7 +164786,7 @@ function registerJobCommand(program2, deps) {
164558
164786
  console.log(`Allowed tools: ${entry.allowedTools.join(", ")}`);
164559
164787
  }
164560
164788
  console.log(`Prompt: ${entry.prompt}`);
164561
- console.log(`Results: ${import_node_path86.default.join(paths.jobLogsDir, `${name}.log`)}`);
164789
+ console.log(`Results: ${import_node_path88.default.join(paths.jobLogsDir, `${name}.log`)}`);
164562
164790
  }),
164563
164791
  ["agent-shim job show digest"]
164564
164792
  );
@@ -164581,7 +164809,7 @@ function registerJobCommand(program2, deps) {
164581
164809
  throw new UsageError(`No member of the job's pool can be picked right now.`);
164582
164810
  }
164583
164811
  await createRealJobRunner({ paths, spawnDaemon: spawnDetachedSupervisor, fs: realFarmFs, now: () => /* @__PURE__ */ new Date() })(name, identity, entry);
164584
- console.log(`Ran job "${name}" as ${identity}; the result is in ${import_node_path86.default.join(paths.jobLogsDir, `${name}.log`)}.`);
164812
+ console.log(`Ran job "${name}" as ${identity}; the result is in ${import_node_path88.default.join(paths.jobLogsDir, `${name}.log`)}.`);
164585
164813
  }),
164586
164814
  ["agent-shim job run digest"]
164587
164815
  );
@@ -164756,14 +164984,14 @@ init_cliError();
164756
164984
  init_providerCatalogue();
164757
164985
  init_state();
164758
164986
  init_modelPicker();
164759
- var import_node_fs34 = __toESM(require("node:fs"), 1);
164987
+ var import_node_fs35 = __toESM(require("node:fs"), 1);
164760
164988
  var import_node_os22 = __toESM(require("node:os"), 1);
164761
164989
  init_credential();
164762
164990
  init_providerAliases();
164763
164991
 
164764
164992
  // src/providerRename.ts
164765
- var import_node_fs33 = __toESM(require("node:fs"), 1);
164766
- var import_node_path87 = __toESM(require("node:path"), 1);
164993
+ var import_node_fs34 = __toESM(require("node:fs"), 1);
164994
+ var import_node_path89 = __toESM(require("node:path"), 1);
164767
164995
  init_zod();
164768
164996
  init_schema();
164769
164997
  init_store();
@@ -164808,7 +165036,7 @@ function renameProvider(paths, from, to2, ports) {
164808
165036
  const previousAliases = readProviderAliases(paths);
164809
165037
  writeProviderAliases(paths, aliasesAfterRename(previousAliases, from, to2));
164810
165038
  try {
164811
- import_node_fs33.default.renameSync(providerJsonPath(paths, from), providerJsonPath(paths, to2));
165039
+ import_node_fs34.default.renameSync(providerJsonPath(paths, from), providerJsonPath(paths, to2));
164812
165040
  } catch (error63) {
164813
165041
  writeProviderAliases(paths, previousAliases);
164814
165042
  throw error63;
@@ -164828,26 +165056,26 @@ function moveState(paths, from, to2, ports) {
164828
165056
  `);
164829
165057
  moved.push(`usage ${snapshot.identity}`);
164830
165058
  }
164831
- if (import_node_fs33.default.existsSync(catalogueCachePath(paths, from))) {
164832
- import_node_fs33.default.renameSync(catalogueCachePath(paths, from), catalogueCachePath(paths, to2));
165059
+ if (import_node_fs34.default.existsSync(catalogueCachePath(paths, from))) {
165060
+ import_node_fs34.default.renameSync(catalogueCachePath(paths, from), catalogueCachePath(paths, to2));
164833
165061
  moved.push("catalogue");
164834
165062
  }
164835
165063
  const globalBinding = catalogueBindingPath(paths, from);
164836
- if (import_node_fs33.default.existsSync(globalBinding)) {
164837
- import_node_fs33.default.renameSync(globalBinding, catalogueBindingPath(paths, to2));
165064
+ if (import_node_fs34.default.existsSync(globalBinding)) {
165065
+ import_node_fs34.default.renameSync(globalBinding, catalogueBindingPath(paths, to2));
164838
165066
  if (!moved.includes("catalogue")) moved.push("catalogue");
164839
165067
  }
164840
- const supervisorsDir = import_node_path87.default.join(paths.catalogueDir, "supervisors");
164841
- if (import_node_fs33.default.existsSync(supervisorsDir)) {
164842
- for (const entry of import_node_fs33.default.readdirSync(supervisorsDir, { withFileTypes: true })) {
165068
+ const supervisorsDir = import_node_path89.default.join(paths.catalogueDir, "supervisors");
165069
+ if (import_node_fs34.default.existsSync(supervisorsDir)) {
165070
+ for (const entry of import_node_fs34.default.readdirSync(supervisorsDir, { withFileTypes: true })) {
164843
165071
  const pid = Number(entry.name);
164844
165072
  if (!entry.isDirectory() || !Number.isSafeInteger(pid) || pid <= 0 || String(pid) !== entry.name) continue;
164845
- for (const generation of import_node_fs33.default.readdirSync(import_node_path87.default.join(supervisorsDir, entry.name), { withFileTypes: true })) {
165073
+ for (const generation of import_node_fs34.default.readdirSync(import_node_path89.default.join(supervisorsDir, entry.name), { withFileTypes: true })) {
164846
165074
  if (!generation.isDirectory() || !external_exports.uuid().safeParse(generation.name).success) continue;
164847
165075
  for (const location of [catalogueCachePath, catalogueBindingPath]) {
164848
165076
  const source = location(paths, from, pid, generation.name);
164849
- if (import_node_fs33.default.existsSync(source)) {
164850
- import_node_fs33.default.renameSync(source, location(paths, to2, pid, generation.name));
165077
+ if (import_node_fs34.default.existsSync(source)) {
165078
+ import_node_fs34.default.renameSync(source, location(paths, to2, pid, generation.name));
164851
165079
  if (!moved.includes("catalogue")) moved.push("catalogue");
164852
165080
  }
164853
165081
  }
@@ -164891,7 +165119,7 @@ function rewriteReferences(paths, from, to2) {
164891
165119
  const launch = renamedLaunch(profile.launch, from, to2);
164892
165120
  const models = profile.models === void 0 ? void 0 : renamedModels(profile.models, from, to2);
164893
165121
  if (launch !== void 0 || models !== void 0) {
164894
- applyPatch(import_node_path87.default.join(paths.configProfilesDir, `${name}.json`), ConfigProfileSchema, { ...launch === void 0 ? {} : { launch }, ...models === void 0 ? {} : { models } });
165122
+ applyPatch(import_node_path89.default.join(paths.configProfilesDir, `${name}.json`), ConfigProfileSchema, { ...launch === void 0 ? {} : { launch }, ...models === void 0 ? {} : { models } });
164895
165123
  rewritten.push(`profile ${name}`);
164896
165124
  }
164897
165125
  }
@@ -165227,7 +165455,7 @@ function registerProviderCommand(program2, deps) {
165227
165455
  throw new UsageError(`Provider "${name}" has no catalogue setting. Set one with \`agent-shim provider set ${name} --catalogue-tier <tier>\`.`);
165228
165456
  }
165229
165457
  const catalogueSetting = found.catalogue;
165230
- const cache = options.refresh === true ? await refreshCatalogueForReal(paths, name, process.env) : parseCatalogueCache(import_node_fs34.default.existsSync(catalogueCachePath(paths, name)) ? import_node_fs34.default.readFileSync(catalogueCachePath(paths, name), "utf8") : void 0);
165458
+ const cache = options.refresh === true ? await refreshCatalogueForReal(paths, name, process.env) : parseCatalogueCache(import_node_fs35.default.existsSync(catalogueCachePath(paths, name)) ? import_node_fs35.default.readFileSync(catalogueCachePath(paths, name), "utf8") : void 0);
165231
165459
  if (cache === void 0) {
165232
165460
  throw new UsageError(`No catalogue has been fetched for "${name}" yet: the front door fetches it shortly after it starts, or run \`agent-shim provider models ${name} --refresh\`.`);
165233
165461
  }
@@ -165672,9 +165900,9 @@ function registerRuleCommand(program2, deps) {
165672
165900
 
165673
165901
  // src/codex/launch.ts
165674
165902
  var import_node_crypto33 = require("node:crypto");
165675
- var import_node_fs36 = __toESM(require("node:fs"), 1);
165903
+ var import_node_fs37 = __toESM(require("node:fs"), 1);
165676
165904
  var import_node_os23 = __toESM(require("node:os"), 1);
165677
- var import_node_path88 = __toESM(require("node:path"), 1);
165905
+ var import_node_path90 = __toESM(require("node:path"), 1);
165678
165906
  init_cliError();
165679
165907
  init_claudeShim();
165680
165908
  init_load();
@@ -165692,7 +165920,7 @@ init_walk();
165692
165920
 
165693
165921
  // src/supervise/realPorts.ts
165694
165922
  var import_node_child_process11 = require("node:child_process");
165695
- var import_node_fs35 = __toESM(require("node:fs"), 1);
165923
+ var import_node_fs36 = __toESM(require("node:fs"), 1);
165696
165924
  init_realPorts();
165697
165925
  init_blockingSpawn();
165698
165926
  var realSupervisedSpawnPort = {
@@ -165707,6 +165935,7 @@ var realSupervisedSpawnPort = {
165707
165935
  });
165708
165936
  });
165709
165937
  return {
165938
+ pid: child.pid,
165710
165939
  exit,
165711
165940
  signal: (signal) => {
165712
165941
  child.kill(signal);
@@ -165737,9 +165966,17 @@ var realTimerPort = {
165737
165966
  }
165738
165967
  };
165739
165968
  function realWatchDirectory(directory, accepts, what, log) {
165969
+ return watchDirectory(directory, accepts, what, log, true);
165970
+ }
165971
+ function realWatchExistingDirectory(directory, accepts, what, log) {
165972
+ return watchDirectory(directory, accepts, what, log, false);
165973
+ }
165974
+ function watchDirectory(directory, accepts, what, log, createPrivate) {
165740
165975
  return (onChange) => {
165741
- realFarmFs.mkdirPrivate(directory);
165742
- const watcher = import_node_fs35.default.watch(directory, { persistent: false }, (_event, filename) => {
165976
+ if (createPrivate) {
165977
+ realFarmFs.mkdirPrivate(directory);
165978
+ }
165979
+ const watcher = import_node_fs36.default.watch(directory, { persistent: false }, (_event, filename) => {
165743
165980
  if (filename === null || accepts(filename)) {
165744
165981
  onChange();
165745
165982
  }
@@ -165831,9 +166068,9 @@ function prepareCodexLaunch(options) {
165831
166068
  const errors = assembleCascade(cascade).diagnostics.filter((item) => item.severity === "error");
165832
166069
  if (errors.length > 0) throw new UsageError(errors.map((item) => item.message).join("\n"));
165833
166070
  const canonical = canonicalCodexHome(env, options.home);
165834
- const farmRoot = import_node_path88.default.join(paths.identitiesDir, id2);
165835
- const relative = import_node_path88.default.relative(canonical, farmRoot);
165836
- if (relative === "" || !relative.startsWith(`..${import_node_path88.default.sep}`) && relative !== ".." && !import_node_path88.default.isAbsolute(relative)) throw new UsageError("The canonical Codex home cannot contain an identity home.");
166071
+ const farmRoot = import_node_path90.default.join(paths.identitiesDir, id2);
166072
+ const relative = import_node_path90.default.relative(canonical, farmRoot);
166073
+ if (relative === "" || !relative.startsWith(`..${import_node_path90.default.sep}`) && relative !== ".." && !import_node_path90.default.isAbsolute(relative)) throw new UsageError("The canonical Codex home cannot contain an identity home.");
165837
166074
  const result = resyncFarm({ ...options, identitiesDir: paths.identitiesDir, identity: id2, claudeHome: canonical, cascade, classification: { defaults: CODEX_CATEGORIES }, lock, ...profile.name === void 0 ? {} : { configProfile: profile.name }, identityExists: () => readIdentityById(paths, id2)?.agent === "codex" });
165838
166075
  for (const diagnostic of result.diagnostics) options.warn(diagnostic.message);
165839
166076
  return {
@@ -165860,16 +166097,16 @@ async function runCodex(paths, argv) {
165860
166097
  const own2 = resolveOwnBinaryCheck(paths, realContentSourcePath());
165861
166098
  const resolveBinary = () => {
165862
166099
  const explicit = process.env.AGENT_SHIM_CODEX_BIN;
165863
- const candidates = explicit === void 0 ? (process.env.PATH ?? "").split(import_node_path88.default.delimiter).filter(Boolean).map((dir) => findExecutableInDir(dir, "codex")) : [import_node_path88.default.resolve(explicit)];
166100
+ const candidates = explicit === void 0 ? (process.env.PATH ?? "").split(import_node_path90.default.delimiter).filter(Boolean).map((dir) => findExecutableInDir(dir, "codex")) : [import_node_path90.default.resolve(explicit)];
165864
166101
  for (const candidate of candidates) {
165865
166102
  if (candidate !== void 0 && !own2(candidate)) return candidate;
165866
166103
  }
165867
166104
  throw new UsageError("No real Codex CLI found on PATH. Install Codex or set AGENT_SHIM_CODEX_BIN to its executable.");
165868
166105
  };
165869
- const plan = prepareCodexLaunch({ paths, argv, env: process.env, cwd: import_node_fs36.default.realpathSync(process.cwd()), home: import_node_os23.default.homedir(), fs: realFarmFs, read: cosmiconfigReader(), resolveBinary, now: Date.now, pid: process.pid, isRunning: realIsProcessRunning, sleep: realSleepSync, uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto33.randomUUID)()}`, warn: (message) => {
166106
+ const plan = prepareCodexLaunch({ paths, argv, env: process.env, cwd: import_node_fs37.default.realpathSync(process.cwd()), home: import_node_os23.default.homedir(), fs: realFarmFs, read: cosmiconfigReader(), resolveBinary, now: Date.now, pid: process.pid, isRunning: realIsProcessRunning, sleep: realSleepSync, uniqueSuffix: `${String(process.pid)}.${(0, import_node_crypto33.randomUUID)()}`, warn: (message) => {
165870
166107
  console.error(`agent-shim: ${message}`);
165871
166108
  }, ...resolveGitBranch(realRunPort, process.cwd()) });
165872
- import_node_fs36.default.chmodSync(plan.env.CODEX_HOME ?? "", PRIVATE_DIRECTORY_MODE);
166109
+ import_node_fs37.default.chmodSync(plan.env.CODEX_HOME ?? "", PRIVATE_DIRECTORY_MODE);
165873
166110
  process.exitCode = await runCodexChild(plan, realSupervisedSpawnPort, realSignalPort);
165874
166111
  }
165875
166112
 
@@ -165968,7 +166205,7 @@ function registerSessionCommands(program2, deps) {
165968
166205
  }
165969
166206
 
165970
166207
  // src/usage/commands.ts
165971
- var import_node_path89 = __toESM(require("node:path"), 1);
166208
+ var import_node_path91 = __toESM(require("node:path"), 1);
165972
166209
  init_commandDeps();
165973
166210
  init_identityStore();
165974
166211
  init_realPorts();
@@ -166103,7 +166340,7 @@ function collectAccounts(fs36, paths, identity, probe) {
166103
166340
  return {
166104
166341
  identity: name,
166105
166342
  account: readAccountMetadata(fs36, paths.identitiesDir, id2),
166106
- signIn: identitySignIn(fs36, probe, { farmRoot: import_node_path89.default.join(paths.identitiesDir, id2), hasCredentialBlock: stored2?.credential !== void 0, provider: stored2?.provider }),
166343
+ signIn: identitySignIn(fs36, probe, { farmRoot: import_node_path91.default.join(paths.identitiesDir, id2), hasCredentialBlock: stored2?.credential !== void 0, provider: stored2?.provider }),
166107
166344
  // Named, like the view around it, by the identity's name; the snapshot is filed under its id.
166108
166345
  usage: ((snapshot) => snapshot === void 0 ? void 0 : { ...snapshot, identity: name })(readUsageSnapshot(fs36, paths.usageSnapshotsDir, id2))
166109
166346
  };
@@ -166614,7 +166851,11 @@ async function realRefresher(params) {
166614
166851
  }
166615
166852
 
166616
166853
  // src/supervise/launch.ts
166617
- var import_node_crypto34 = require("node:crypto");
166854
+ var import_node_crypto35 = require("node:crypto");
166855
+ var import_node_fs40 = require("node:fs");
166856
+ var import_node_path96 = __toESM(require("node:path"), 1);
166857
+ var import_promises21 = require("node:stream/promises");
166858
+ init_package();
166618
166859
  init_claudeSession();
166619
166860
  init_claudeSubcommand();
166620
166861
  init_pool();
@@ -166634,7 +166875,7 @@ init_preflight();
166634
166875
  var PERCENT6 = 100;
166635
166876
  var asPercent = (fraction) => `${String(Math.round(fraction * PERCENT6))}%`;
166636
166877
  function compactableTokens(state) {
166637
- return state?.mark === "idle" && state.compacted !== true && state.contextTokens !== void 0 && state.contextTokens > 0 ? state.contextTokens : void 0;
166878
+ return state?.mark === "idle" && state.unavailable !== true && state.compacted !== true && state.contextTokens !== void 0 && state.contextTokens > 0 ? state.contextTokens : void 0;
166638
166879
  }
166639
166880
  function presentWindows(input2) {
166640
166881
  const unified = input2.snapshot?.providers[ANTHROPIC_PROVIDER]?.rateLimit?.unified;
@@ -166679,7 +166920,7 @@ function decideCompaction(input2) {
166679
166920
  return { compact: false, reason: "a larger session on this member compacts first" };
166680
166921
  }
166681
166922
  const reason = triggerReason(input2);
166682
- return reason === void 0 ? { compact: false, reason: "the member's quota has not reached the trigger" } : { compact: true, contextTokens: tokens, reason };
166923
+ return reason === void 0 ? { compact: false, reason: "the member's quota has not reached the trigger" } : { compact: true, contextTokens: tokens, reason, ...own2?.state?.conversationId === void 0 ? {} : { conversationId: own2.state.conversationId } };
166683
166924
  }
166684
166925
 
166685
166926
  // src/supervise/realCompact.ts
@@ -166739,8 +166980,9 @@ function createCompactionDeps(wiring) {
166739
166980
  return {
166740
166981
  shouldCompact: (identity, sessionId) => {
166741
166982
  const nowMs = wiring.now();
166742
- const sessions = liveSupervised(fs36, paths, pool, wiring.isRunning).filter((session) => session.identity === identity).map((session) => ({ sessionId: session.sessionId, state: readSessionState(fs36, paths, pool, session.sessionId) }));
166743
- return decideCompaction({
166983
+ const registry2 = liveSupervised(fs36, paths, pool, wiring.isRunning).filter((session) => session.identity === identity);
166984
+ const sessions = registry2.map((session) => ({ sessionId: session.sessionId, state: readSessionState(fs36, paths, pool, session.sessionId) }));
166985
+ const decision = decideCompaction({
166744
166986
  atUtilisation: wiring.policy.compactAtUtilisation,
166745
166987
  snapshot: readUsageSnapshot(fs36, paths.usageSnapshotsDir, identity),
166746
166988
  records: () => readUsageLog(fs36, paths.usageLogDir, { sinceMs: nowMs - FIVE_HOUR_WINDOW_MS }).records.filter((record3) => record3.identity === identity),
@@ -166748,6 +166990,15 @@ function createCompactionDeps(wiring) {
166748
166990
  sessionId,
166749
166991
  nowMs
166750
166992
  });
166993
+ if (!decision.compact) {
166994
+ return decision;
166995
+ }
166996
+ const own2 = registry2.find((session) => session.sessionId === sessionId);
166997
+ const state = sessions.find((session) => session.sessionId === sessionId)?.state;
166998
+ if (own2 === void 0 || state === void 0 || !wiring.hooksFinished(own2, state)) {
166999
+ return { compact: false, reason: "the turn's Stop hooks have not finished successfully" };
167000
+ }
167001
+ return decision;
166751
167002
  },
166752
167003
  acquire: (identity) => {
166753
167004
  try {
@@ -166761,14 +167012,27 @@ function createCompactionDeps(wiring) {
166761
167012
  }
166762
167013
  },
166763
167014
  compact: wiring.compact,
166764
- markCompacted: (sessionId, compacted) => {
166765
- const previous = readSessionState(fs36, paths, pool, sessionId);
166766
- writeSessionState(fs36, paths, pool, sessionId, {
166767
- mark: previous?.mark ?? "idle",
166768
- ...previous?.contextTokens === void 0 ? {} : { contextTokens: previous.contextTokens },
166769
- ...compacted ? { compacted: true } : {},
166770
- at: new Date(wiring.now()).toISOString()
166771
- });
167015
+ markCompacted: (sessionId, compacted, conversationId) => {
167016
+ const dir = stateDirOf(paths, pool);
167017
+ fs36.mkdirPrivate(dir);
167018
+ const lock = acquireIdentityLock({ identity: `mark-${sessionId}`, dir, fs: fs36, nowMs: wiring.now, pid: wiring.pid, isRunning: wiring.isRunning, sleep: wiring.sleep });
167019
+ try {
167020
+ const previous = readSessionState(fs36, paths, pool, sessionId);
167021
+ if (conversationId !== void 0 && (previous?.unavailable === true || (previous?.conversationId ?? sessionId) !== conversationId)) return false;
167022
+ writeSessionState(fs36, paths, pool, sessionId, {
167023
+ mark: previous?.mark ?? "idle",
167024
+ ...previous?.conversationId === void 0 ? {} : { conversationId: previous.conversationId },
167025
+ ...previous?.transcriptPath === void 0 ? {} : { transcriptPath: previous.transcriptPath },
167026
+ ...previous?.promptId === void 0 ? {} : { promptId: previous.promptId },
167027
+ ...previous?.unavailable === true ? { unavailable: true } : {},
167028
+ ...previous?.contextTokens === void 0 ? {} : { contextTokens: previous.contextTokens },
167029
+ ...compacted ? { compacted: true } : {},
167030
+ at: new Date(wiring.now()).toISOString()
167031
+ });
167032
+ return true;
167033
+ } finally {
167034
+ lock.release();
167035
+ }
166772
167036
  }
166773
167037
  };
166774
167038
  }
@@ -166783,15 +167047,180 @@ function quotaHitOf(fs36, paths, identity, sessionId, sinceMs, nowMs) {
166783
167047
  const { records } = readUsageLog(fs36, paths.usageLogDir, { sinceMs });
166784
167048
  for (let index = records.length - 1; index >= 0; index -= 1) {
166785
167049
  const record3 = records[index];
166786
- if (record3?.sessionId === sessionId && record3.identity === identity && record3.limit?.kind === "quota-exhausted") {
167050
+ if (record3?.sessionId === sessionId && record3.identity === identity && record3.route === "anthropic" && record3.limit?.kind === "quota-exhausted") {
166787
167051
  return { reason, ...record3.limit.resetAt === void 0 ? {} : { resetAt: record3.limit.resetAt } };
166788
167052
  }
166789
167053
  }
166790
167054
  return void 0;
166791
167055
  }
166792
167056
 
167057
+ // src/supervise/lifecycle.ts
167058
+ var import_node_path92 = __toESM(require("node:path"), 1);
167059
+ init_zod();
167060
+ var SignalSchema = external_exports.string().regex(/^SIG[A-Z0-9]+$/);
167061
+ var ChildPidSchema = external_exports.number().int().positive().nullable();
167062
+ var LifecycleEventSchema = external_exports.discriminatedUnion("kind", [
167063
+ external_exports.strictObject({ kind: external_exports.literal("child_started"), childPid: ChildPidSchema }),
167064
+ external_exports.strictObject({ kind: external_exports.literal("departure"), reason: external_exports.enum(["quota", "model"]) }),
167065
+ external_exports.strictObject({ kind: external_exports.literal("child_signal"), childPid: ChildPidSchema, signal: SignalSchema }),
167066
+ external_exports.strictObject({ kind: external_exports.literal("child_exited"), childPid: ChildPidSchema, status: external_exports.number().int().nullable(), signal: SignalSchema.nullable(), spawnFailed: external_exports.boolean() }),
167067
+ external_exports.strictObject({ kind: external_exports.literal("compaction"), phase: external_exports.enum(["live", "after_move"]), outcome: external_exports.enum(["compacted", "unchanged", "failed", "interrupted", "not_attempted"]) })
167068
+ ]);
167069
+ function createLifecycleRecorder(params) {
167070
+ const directory = import_node_path92.default.join(params.logsDir, "supervisor");
167071
+ const file2 = import_node_path92.default.join(directory, `${params.fileId}.jsonl`);
167072
+ let warned2 = false;
167073
+ return (event) => {
167074
+ try {
167075
+ const safeEvent = LifecycleEventSchema.parse(event);
167076
+ params.fs.mkdirPrivate(directory);
167077
+ params.fs.appendFilePrivate(file2, `${JSON.stringify({ schemaVersion: 1, at: new Date(params.now()).toISOString(), sessionId: params.sessionId, supervisorPid: params.supervisorPid, supervisorVersion: params.supervisorVersion, entrypointSha256AtStart: params.entrypointSha256AtStart, ...safeEvent })}
167078
+ `);
167079
+ } catch {
167080
+ if (!warned2) {
167081
+ warned2 = true;
167082
+ params.log.warn("agent-shim: could not record supervisor lifecycle diagnostics");
167083
+ }
167084
+ }
167085
+ };
167086
+ }
167087
+
167088
+ // src/supervise/nativeCompact.ts
167089
+ var import_node_crypto34 = require("node:crypto");
167090
+ var import_node_fs38 = require("node:fs");
167091
+ var import_promises20 = require("node:timers/promises");
167092
+ var RESULT_POLL_MS = 250;
167093
+ function nativeCompactionReady(plugin) {
167094
+ return (0, import_node_fs38.existsSync)(plugin.ready);
167095
+ }
167096
+ async function compactInSession(plugin, conversationId, signal) {
167097
+ if (!nativeCompactionReady(plugin)) throw new Error("the in-process compaction plugin did not load");
167098
+ signal.throwIfAborted();
167099
+ const id2 = (0, import_node_crypto34.randomUUID)();
167100
+ const temporary = `${plugin.request}.${id2}`;
167101
+ (0, import_node_fs38.writeFileSync)(temporary, JSON.stringify({ id: id2, conversationId }), { mode: 384 });
167102
+ (0, import_node_fs38.renameSync)(temporary, plugin.request);
167103
+ try {
167104
+ while (!signal.aborted) {
167105
+ signal.throwIfAborted();
167106
+ if ((0, import_node_fs38.existsSync)(plugin.result)) {
167107
+ let value3;
167108
+ try {
167109
+ value3 = JSON.parse((0, import_node_fs38.readFileSync)(plugin.result, "utf8"));
167110
+ } catch (error63) {
167111
+ if (!(error63 instanceof SyntaxError)) throw error63;
167112
+ }
167113
+ if (typeof value3 === "object" && value3 !== null && "id" in value3 && value3.id === id2) {
167114
+ if ("error" in value3 && typeof value3.error === "string") throw new Error(value3.error);
167115
+ if ("kind" in value3 && value3.kind === "unchanged" && "skip" in value3 && typeof value3.skip === "string") return { kind: "unchanged", reason: value3.skip };
167116
+ if ("kind" in value3 && value3.kind === "running") {
167117
+ await (0, import_promises20.setTimeout)(RESULT_POLL_MS, void 0, { signal });
167118
+ continue;
167119
+ }
167120
+ if (!("kind" in value3) || value3.kind !== "compacted") throw new Error("the compaction plugin returned an invalid result");
167121
+ const beforeTokens = "tokensBefore" in value3 && typeof value3.tokensBefore === "number" ? value3.tokensBefore : void 0;
167122
+ const afterTokens = "tokensAfter" in value3 && typeof value3.tokensAfter === "number" ? value3.tokensAfter : void 0;
167123
+ return { kind: "compacted", ...beforeTokens === void 0 ? {} : { beforeTokens }, ...afterTokens === void 0 ? {} : { afterTokens } };
167124
+ }
167125
+ }
167126
+ await (0, import_promises20.setTimeout)(RESULT_POLL_MS, void 0, { signal });
167127
+ }
167128
+ signal.throwIfAborted();
167129
+ throw new Error("compaction wait ended unexpectedly");
167130
+ } finally {
167131
+ (0, import_node_fs38.writeFileSync)(plugin.request, "{}", { mode: 384 });
167132
+ }
167133
+ }
167134
+
167135
+ // src/supervise/nativeCompactionPlugin.ts
167136
+ var import_node_fs39 = require("node:fs");
167137
+ var import_node_os24 = require("node:os");
167138
+ var import_node_path93 = __toESM(require("node:path"), 1);
167139
+ function stageNativeCompactionPlugin() {
167140
+ const directory = (0, import_node_fs39.mkdtempSync)(import_node_path93.default.join((0, import_node_os24.tmpdir)(), "agent-shim-compact-"));
167141
+ const ready = import_node_path93.default.join(directory, "ready.json");
167142
+ const request7 = import_node_path93.default.join(directory, "request.json");
167143
+ const result = import_node_path93.default.join(directory, "result.json");
167144
+ try {
167145
+ (0, import_node_fs39.mkdirSync)(import_node_path93.default.join(directory, ".claude-plugin"), { mode: 448 });
167146
+ (0, import_node_fs39.mkdirSync)(import_node_path93.default.join(directory, "hooks"), { mode: 448 });
167147
+ (0, import_node_fs39.writeFileSync)(import_node_path93.default.join(directory, ".claude-plugin", "plugin.json"), JSON.stringify({ name: "agent-shim-compaction", version: "1.0.0", description: "Compacts supervised sessions in process" }), { mode: 384 });
167148
+ (0, import_node_fs39.writeFileSync)(import_node_path93.default.join(directory, "hooks", "hooks.json"), JSON.stringify({ modules: ["./register.js"] }), { mode: 384 });
167149
+ (0, import_node_fs39.writeFileSync)(import_node_path93.default.join(directory, "hooks", "register.js"), pluginSource(ready, request7, result), { mode: 384 });
167150
+ (0, import_node_fs39.writeFileSync)(request7, "{}", { mode: 384 });
167151
+ (0, import_node_fs39.writeFileSync)(result, "{}", { mode: 384 });
167152
+ return { directory, ready, request: request7, result, release: () => {
167153
+ (0, import_node_fs39.rmSync)(directory, { recursive: true, force: true });
167154
+ } };
167155
+ } catch (error63) {
167156
+ (0, import_node_fs39.rmSync)(directory, { recursive: true, force: true });
167157
+ throw error63;
167158
+ }
167159
+ }
167160
+ function pluginSource(ready, request7, result) {
167161
+ return `export function register(on) {
167162
+ let running = false;
167163
+ let lastRequest;
167164
+ function outcome(id, compacted) {
167165
+ return { id, ...(typeof compacted?.skip === 'string' ? { kind: 'unchanged', skip: compacted.skip } : { kind: 'compacted', tokensBefore: compacted?.tokensBefore, tokensAfter: compacted?.tokensAfter }) };
167166
+ }
167167
+ on('classic.PostCompact', async ($, event, next) => {
167168
+ const answer = await next(event);
167169
+ $.clock.after(0, async () => {
167170
+ const text = await $.fs.read(${JSON.stringify(result)});
167171
+ if (typeof text !== 'string') return;
167172
+ const current = JSON.parse(text);
167173
+ if (current.kind === 'running' && typeof current.id === 'string') {
167174
+ await $.fs.write(${JSON.stringify(result)}, JSON.stringify({ id: current.id, kind: 'compacted' }));
167175
+ }
167176
+ });
167177
+ return answer;
167178
+ });
167179
+ on('session.start', async ($, event, next) => {
167180
+ const answer = await next(event);
167181
+ await $.fs.write(${JSON.stringify(ready)}, JSON.stringify({ ready: true }));
167182
+ $.clock.every(1000, async () => {
167183
+ if (running) return;
167184
+ running = true;
167185
+ try {
167186
+ const text = await $.fs.read(${JSON.stringify(request7)});
167187
+ if (typeof text !== 'string') return;
167188
+ const item = JSON.parse(text);
167189
+ if (typeof item.id !== 'string' || typeof item.conversationId !== 'string' || item.id === lastRequest) return;
167190
+ const priorText = await $.fs.read(${JSON.stringify(result)});
167191
+ if (typeof priorText === 'string') {
167192
+ const prior = JSON.parse(priorText);
167193
+ if (prior.id === item.id) { lastRequest = item.id; return; }
167194
+ }
167195
+ lastRequest = item.id;
167196
+ let response;
167197
+ await $.fs.write(${JSON.stringify(result)}, JSON.stringify({ id: item.id, kind: 'running' }));
167198
+ try {
167199
+ if (await $.session.id() !== item.conversationId) throw new Error('the conversation changed before compaction');
167200
+ const compacted = await $.session.compact({});
167201
+ response = outcome(item.id, compacted);
167202
+ } catch (error) {
167203
+ response = { id: item.id, error: String(error) };
167204
+ }
167205
+ await $.fs.write(${JSON.stringify(result)}, JSON.stringify(response));
167206
+ } finally {
167207
+ running = false;
167208
+ }
167209
+ });
167210
+ return answer;
167211
+ });
167212
+ }
167213
+ `;
167214
+ }
167215
+ function withNativeCompactionPlugin(args, directory) {
167216
+ const end = args.indexOf("--");
167217
+ const result = [...args];
167218
+ result.splice(end === -1 ? result.length : end, 0, "--plugin-dir", directory);
167219
+ return result;
167220
+ }
167221
+
166793
167222
  // src/supervise/move.ts
166794
- var import_node_path90 = __toESM(require("node:path"), 1);
167223
+ var import_node_path94 = __toESM(require("node:path"), 1);
166795
167224
  init_identityRecords();
166796
167225
  init_lock();
166797
167226
  init_poolPick();
@@ -166828,7 +167257,7 @@ function createMover(deps) {
166828
167257
  cwd: deps.cwd,
166829
167258
  now: deps.now,
166830
167259
  sleep: deps.sleep,
166831
- passthrough: ["--resume", request7.sessionId],
167260
+ passthrough: ["--resume", request7.conversationId ?? request7.sessionId],
166832
167261
  ...request7.contextTokens === void 0 ? {} : { resumeContextTokens: request7.contextTokens },
166833
167262
  ...Object.keys(committed).length === 0 ? {} : { committedContextTokens: committed },
166834
167263
  wait: false,
@@ -166843,7 +167272,7 @@ function createMover(deps) {
166843
167272
  if (pickedId === request7.from) {
166844
167273
  return { kind: "stay", reason: `no other member of pool "${pool}" can take it` };
166845
167274
  }
166846
- const transcript = pickedId === void 0 ? void 0 : import_node_path90.default.join(paths.identitiesDir, pickedId, "projects", projectDirNameOf(deps.cwd), `${request7.sessionId}.jsonl`);
167275
+ const transcript = pickedId === void 0 ? void 0 : import_node_path94.default.join(paths.identitiesDir, pickedId, "projects", projectDirNameOf(deps.cwd), `${request7.conversationId ?? request7.sessionId}.jsonl`);
166847
167276
  if (pickedId === void 0 || transcript === void 0 || farmFs.lstat(transcript)?.kind !== "file") {
166848
167277
  return { kind: "stay", reason: `${resolution.identity} does not share this conversation's history, so it could not resume it` };
166849
167278
  }
@@ -166885,7 +167314,7 @@ function createIdentityMover(deps) {
166885
167314
  if (request7.to === request7.from) {
166886
167315
  return { kind: "stay", reason: `the model already runs under this session's identity` };
166887
167316
  }
166888
- const transcript = import_node_path90.default.join(paths.identitiesDir, request7.to, "projects", projectDirNameOf(deps.cwd), `${request7.sessionId}.jsonl`);
167317
+ const transcript = import_node_path94.default.join(paths.identitiesDir, request7.to, "projects", projectDirNameOf(deps.cwd), `${request7.conversationId ?? request7.sessionId}.jsonl`);
166889
167318
  if (farmFs.lstat(transcript)?.kind !== "file") {
166890
167319
  return { kind: "stay", reason: `${toName} does not share this conversation's history, so it could not resume it` };
166891
167320
  }
@@ -166906,6 +167335,60 @@ function createIdentityMover(deps) {
166906
167335
  };
166907
167336
  }
166908
167337
 
167338
+ // src/supervise/stopSummary.ts
167339
+ init_zod();
167340
+ var FinishedStopSchema = external_exports.object({
167341
+ type: external_exports.literal("system"),
167342
+ subtype: external_exports.literal("stop_hook_summary"),
167343
+ sessionId: external_exports.string(),
167344
+ timestamp: external_exports.iso.datetime(),
167345
+ preventedContinuation: external_exports.literal(false),
167346
+ stopReason: external_exports.literal(""),
167347
+ hookErrors: external_exports.array(external_exports.unknown()).length(0)
167348
+ });
167349
+ function stopHooksFinished(text5, conversationId, markedAt) {
167350
+ if (!text5.endsWith("\n")) {
167351
+ return false;
167352
+ }
167353
+ const lines = text5.split("\n");
167354
+ for (let index = lines.length - 2; index >= 0; index -= 1) {
167355
+ const line = lines[index];
167356
+ if (line === void 0 || line === "") {
167357
+ continue;
167358
+ }
167359
+ let record3;
167360
+ try {
167361
+ record3 = JSON.parse(line);
167362
+ } catch {
167363
+ return false;
167364
+ }
167365
+ if (typeof record3 !== "object" || record3 === null || !("type" in record3)) {
167366
+ return false;
167367
+ }
167368
+ if (record3.type === "user" || record3.type === "assistant" || record3.type === "attachment") {
167369
+ return false;
167370
+ }
167371
+ if (record3.type === "system" && "subtype" in record3 && record3.subtype === "stop_hook_summary") {
167372
+ const parsed = FinishedStopSchema.safeParse(record3);
167373
+ return parsed.success && parsed.data.sessionId === conversationId && Date.parse(parsed.data.timestamp) >= Date.parse(markedAt);
167374
+ }
167375
+ }
167376
+ return false;
167377
+ }
167378
+
167379
+ // src/supervise/settings.ts
167380
+ var import_node_path95 = __toESM(require("node:path"), 1);
167381
+ function stageSupervisedSettings(fs36, paths, pool, sessionId, pid, contents) {
167382
+ const directory = import_node_path95.default.join(superviseDirOf(paths, pool), "settings");
167383
+ const file2 = import_node_path95.default.join(directory, `${sessionId}.${String(pid)}.json`);
167384
+ fs36.mkdirPrivate(directory);
167385
+ fs36.writeFilePrivate(file2, `${contents}
167386
+ `);
167387
+ return { file: file2, release: () => {
167388
+ fs36.removeRecursive(file2);
167389
+ } };
167390
+ }
167391
+
166909
167392
  // src/supervise/supervise.ts
166910
167393
  init_hold();
166911
167394
  init_spawn();
@@ -166930,6 +167413,7 @@ function messageOf2(error63) {
166930
167413
  return error63 instanceof Error ? error63.message : String(error63);
166931
167414
  }
166932
167415
  async function stopChild(deps, child) {
167416
+ deps.lifecycle?.({ kind: "child_signal", childPid: child.pid ?? null, signal: "SIGTERM" });
166933
167417
  child.signal("SIGTERM");
166934
167418
  const grace = deps.timer.after(STOP_GRACE_MS);
166935
167419
  const stopped = await Promise.race([child.exit.then((result2) => ({ result: result2 })), grace.elapsed.then(() => void 0)]);
@@ -166937,20 +167421,32 @@ async function stopChild(deps, child) {
166937
167421
  if (stopped !== void 0) {
166938
167422
  return stopped.result;
166939
167423
  }
167424
+ deps.lifecycle?.({ kind: "child_signal", childPid: child.pid ?? null, signal: "SIGKILL" });
166940
167425
  child.signal("SIGKILL");
166941
167426
  const result = await child.exit;
166942
167427
  deps.resetTerminal();
166943
167428
  return result;
166944
167429
  }
166945
- async function runChild2(deps, plan, identity, canCompact) {
167430
+ async function runChild2(deps, plan, identity, compactedConversation, onCompacted) {
166946
167431
  const startedMs = deps.now();
166947
167432
  const child = deps.spawn.spawn(plan.bin, plan.args, { stdio: "inherit", env: plan.env });
166948
167433
  plan.markChildStarted();
166949
- const state = { terminating: false, leaving: false, checking: false, wakes: 0, declined: false, lastWarning: "" };
167434
+ deps.lifecycle?.({ kind: "child_started", childPid: child.pid ?? null });
167435
+ const observedExit = child.exit.then((result) => {
167436
+ deps.lifecycle?.({ kind: "child_exited", childPid: child.pid ?? null, status: result.status, signal: result.signal, spawnFailed: result.error !== void 0 });
167437
+ return result;
167438
+ });
167439
+ const state = { terminating: false, leaving: false, checking: false, compacting: false, wakes: 0, declined: false, lastWarning: "" };
167440
+ const liveAbort = new AbortController();
167441
+ let attemptedWake = -1;
167442
+ let liveTask;
167443
+ let compacted = compactedConversation;
167444
+ let recheck = () => void 0;
166950
167445
  const stopHandlers = [
166951
167446
  ...["SIGHUP", "SIGTERM"].map(
166952
167447
  (signal) => deps.signals.on(signal, () => {
166953
167448
  state.terminating = true;
167449
+ deps.lifecycle?.({ kind: "child_signal", childPid: child.pid ?? null, signal });
166954
167450
  child.signal(signal);
166955
167451
  })
166956
167452
  ),
@@ -166961,30 +167457,63 @@ async function runChild2(deps, plan, identity, canCompact) {
166961
167457
  depart = resolve3;
166962
167458
  });
166963
167459
  const handleRefusal = async (hit) => {
166964
- const outcome = await deps.decideMove({ sessionId: plan.sessionId, from: identity, contextTokens: deps.contextTokens(plan.sessionId) });
167460
+ const conversationId = deps.currentConversationId(plan.sessionId);
167461
+ if (conversationId === void 0) {
167462
+ const warning = `agent-shim: cannot move session ${plan.sessionId}: its current conversation is unknown`;
167463
+ if (warning !== state.lastWarning) {
167464
+ state.lastWarning = warning;
167465
+ deps.log.warn(warning);
167466
+ }
167467
+ return;
167468
+ }
167469
+ const outcome = await deps.decideMove({ sessionId: plan.sessionId, ...conversationId === plan.sessionId ? {} : { conversationId }, from: identity, contextTokens: deps.contextTokens(conversationId) });
166965
167470
  if (outcome.kind === "move") {
166966
167471
  state.leaving = true;
166967
- depart(outcome);
167472
+ deps.lifecycle?.({ kind: "departure", reason: "quota" });
167473
+ depart({ ...outcome, conversationId });
166968
167474
  } else {
166969
167475
  state.declined = true;
166970
167476
  deps.log.warn(`agent-shim: ${labelOf3(deps, identity)} is out of quota${hit.resetAt === void 0 ? "" : ` until ${hit.resetAt}`}, and this session stays on it: ${outcome.reason}`);
166971
167477
  }
166972
167478
  };
166973
167479
  const considerCompacting = (compaction) => {
167480
+ const live = compaction.live;
167481
+ if (live === void 0 || state.compacting || attemptedWake === state.wakes) return;
166974
167482
  const decision = compaction.shouldCompact(identity, plan.sessionId);
166975
- if (!decision.compact) {
167483
+ if (!decision.compact || (decision.conversationId ?? plan.sessionId) === compacted) return;
167484
+ if (!live.ready()) {
167485
+ const warning = `agent-shim: cannot compact session ${plan.sessionId}: the in-process plugin is not ready`;
167486
+ if (warning !== state.lastWarning) {
167487
+ state.lastWarning = warning;
167488
+ deps.log.warn(warning);
167489
+ }
166976
167490
  return;
166977
167491
  }
166978
167492
  const slot = compaction.acquire(identity);
166979
- if (slot === void 0) {
166980
- return;
166981
- }
166982
- if (compaction.shouldCompact(identity, plan.sessionId).compact) {
166983
- state.leaving = true;
166984
- depart({ kind: "compact", slot, contextTokens: decision.contextTokens, reason: decision.reason });
166985
- } else {
167493
+ if (slot === void 0) return;
167494
+ state.compacting = true;
167495
+ attemptedWake = state.wakes;
167496
+ const conversationId = decision.conversationId ?? plan.sessionId;
167497
+ deps.log.info(`agent-shim: ${decision.reason}; compacting session ${plan.sessionId} in process`);
167498
+ liveTask = live.compact(conversationId, liveAbort.signal).then((result) => {
167499
+ deps.lifecycle?.({ kind: "compaction", phase: "live", outcome: result.kind });
167500
+ if (result.kind === "compacted") {
167501
+ if (compaction.markCompacted(plan.sessionId, true, conversationId)) {
167502
+ compacted = conversationId;
167503
+ onCompacted(conversationId);
167504
+ }
167505
+ deps.log.info(`agent-shim: compacted session ${plan.sessionId} on ${labelOf3(deps, identity)}`);
167506
+ } else {
167507
+ deps.log.info(`agent-shim: session ${plan.sessionId} was left as it was: ${result.reason}`);
167508
+ }
167509
+ }).catch((error63) => {
167510
+ deps.lifecycle?.({ kind: "compaction", phase: "live", outcome: liveAbort.signal.aborted ? "interrupted" : "failed" });
167511
+ if (!liveAbort.signal.aborted) deps.log.warn(`agent-shim: could not compact session ${plan.sessionId}: ${messageOf2(error63)}`);
167512
+ }).finally(() => {
166986
167513
  slot.release();
166987
- }
167514
+ state.compacting = false;
167515
+ if (!liveAbort.signal.aborted && state.wakes > attemptedWake) recheck();
167516
+ });
166988
167517
  };
166989
167518
  const isLeaving = () => state.leaving;
166990
167519
  const check2 = async () => {
@@ -167000,12 +167529,15 @@ async function runChild2(deps, plan, identity, canCompact) {
167000
167529
  if (isLeaving()) {
167001
167530
  break;
167002
167531
  }
167003
- const move = deps.claimModelMove(plan.sessionId);
167004
- if (move !== void 0) {
167005
- const outcome = deps.decideRemodel({ sessionId: plan.sessionId, from: identity, to: move.to });
167532
+ if (state.compacting) continue;
167533
+ const currentConversation2 = deps.currentConversationId(plan.sessionId);
167534
+ const move = currentConversation2 === void 0 ? void 0 : deps.claimModelMove(plan.sessionId);
167535
+ if (move !== void 0 && currentConversation2 !== void 0) {
167536
+ const outcome = deps.decideRemodel({ sessionId: plan.sessionId, ...currentConversation2 === plan.sessionId ? {} : { conversationId: currentConversation2 }, from: identity, to: move.to, contextTokens: deps.contextTokens(currentConversation2) });
167006
167537
  if (outcome.kind === "move") {
167007
167538
  state.leaving = true;
167008
- depart({ kind: "remodel", to: outcome.to, model: move.model });
167539
+ deps.lifecycle?.({ kind: "departure", reason: "model" });
167540
+ depart({ kind: "remodel", to: outcome.to, model: move.model, conversationId: currentConversation2 });
167009
167541
  } else {
167010
167542
  deps.log.warn(`agent-shim: session ${plan.sessionId} picked a model under ${labelOf3(deps, move.to)}, but stays on ${labelOf3(deps, identity)}: ${outcome.reason}`);
167011
167543
  }
@@ -167019,7 +167551,7 @@ async function runChild2(deps, plan, identity, canCompact) {
167019
167551
  continue;
167020
167552
  }
167021
167553
  state.declined = false;
167022
- if (canCompact && deps.compaction !== void 0) {
167554
+ if (deps.compaction !== void 0) {
167023
167555
  considerCompacting(deps.compaction);
167024
167556
  }
167025
167557
  } while (handled !== state.wakes);
@@ -167033,6 +167565,9 @@ async function runChild2(deps, plan, identity, canCompact) {
167033
167565
  state.checking = false;
167034
167566
  }
167035
167567
  };
167568
+ recheck = () => {
167569
+ void check2();
167570
+ };
167036
167571
  const stopWatching = deps.watchChanges(identity, () => {
167037
167572
  void check2();
167038
167573
  });
@@ -167040,24 +167575,23 @@ async function runChild2(deps, plan, identity, canCompact) {
167040
167575
  void check2();
167041
167576
  });
167042
167577
  try {
167043
- const first = await Promise.race([child.exit.then((result2) => ({ kind: "exited", result: result2 })), departing]);
167578
+ const first = await Promise.race([observedExit.then((result2) => ({ kind: "exited", result: result2 })), departing]);
167044
167579
  stopWatching();
167045
167580
  stopWatchingMoves?.();
167046
167581
  if (first.kind === "exited") {
167047
167582
  return first;
167048
167583
  }
167049
167584
  deps.log.info(
167050
- first.kind === "move" ? `agent-shim: ${labelOf3(deps, identity)} is out of quota; resuming session ${plan.sessionId} under ${labelOf3(deps, first.to)} (${first.explanation})` : first.kind === "remodel" ? `agent-shim: resuming session ${plan.sessionId} under ${labelOf3(deps, first.to)} with ${first.model}, which only runs there` : `agent-shim: ${first.reason}; compacting the ${String(first.contextTokens)}-token context of session ${plan.sessionId} on ${labelOf3(deps, identity)}`
167585
+ first.kind === "move" ? `agent-shim: ${labelOf3(deps, identity)} is out of quota; resuming session ${plan.sessionId} under ${labelOf3(deps, first.to)} (${first.explanation})` : `agent-shim: resuming session ${plan.sessionId} under ${labelOf3(deps, first.to)} with ${first.model}, which only runs there`
167051
167586
  );
167052
167587
  const result = await stopChild(deps, child);
167053
167588
  if (state.terminating) {
167054
- if (first.kind === "compact") {
167055
- first.slot.release();
167056
- }
167057
167589
  return { kind: "exited", result };
167058
167590
  }
167059
167591
  return first;
167060
167592
  } finally {
167593
+ liveAbort.abort();
167594
+ await liveTask;
167061
167595
  stopWatching();
167062
167596
  stopWatchingMoves?.();
167063
167597
  for (const stop of stopHandlers) {
@@ -167068,7 +167602,7 @@ async function runChild2(deps, plan, identity, canCompact) {
167068
167602
  function signalExit(signal) {
167069
167603
  return childExitCode({ status: null, signal });
167070
167604
  }
167071
- async function compactSession(deps, compaction, slot, identity, sessionId) {
167605
+ async function compactSession(deps, compaction, slot, identity, sessionId, conversationId = sessionId) {
167072
167606
  const abort = new AbortController();
167073
167607
  const interrupted = { signal: void 0 };
167074
167608
  const stopHandlers = ["SIGINT", "SIGHUP", "SIGTERM"].map(
@@ -167077,8 +167611,11 @@ async function compactSession(deps, compaction, slot, identity, sessionId) {
167077
167611
  abort.abort();
167078
167612
  })
167079
167613
  );
167614
+ let completed = false;
167080
167615
  try {
167081
- const result = await compaction.compact({ identity: memberName(deps, identity), sessionId, cwd: deps.cwd }, abort.signal);
167616
+ const result = await compaction.compact({ identity: memberName(deps, identity), sessionId: conversationId, cwd: deps.cwd }, abort.signal);
167617
+ completed = true;
167618
+ deps.lifecycle?.({ kind: "compaction", phase: "after_move", outcome: result.kind });
167082
167619
  if (result.kind === "unchanged") {
167083
167620
  deps.log.info(`agent-shim: session ${sessionId} was left as it was: ${result.reason}`);
167084
167621
  } else {
@@ -167086,6 +167623,7 @@ async function compactSession(deps, compaction, slot, identity, sessionId) {
167086
167623
  deps.log.info(`agent-shim: compacted session ${sessionId} on ${labelOf3(deps, identity)}${sizes}`);
167087
167624
  }
167088
167625
  } catch (error63) {
167626
+ deps.lifecycle?.({ kind: "compaction", phase: "after_move", outcome: interrupted.signal === void 0 ? "failed" : "interrupted" });
167089
167627
  if (interrupted.signal === void 0) {
167090
167628
  deps.log.warn(`agent-shim: could not compact session ${sessionId} on ${labelOf3(deps, identity)}, which resumes as it was: ${messageOf2(error63)}`);
167091
167629
  }
@@ -167095,14 +167633,14 @@ async function compactSession(deps, compaction, slot, identity, sessionId) {
167095
167633
  }
167096
167634
  slot.release();
167097
167635
  }
167098
- compaction.markCompacted(sessionId, true);
167099
- return interrupted.signal;
167636
+ if (completed) compaction.markCompacted(sessionId, true);
167637
+ return { signal: interrupted.signal, completed };
167100
167638
  }
167101
167639
  async function supervise(deps, first) {
167102
167640
  const { compaction } = deps;
167103
- const base = { sessionId: first.sessionId, ...first.settings === void 0 ? {} : { settings: first.settings } };
167641
+ const base = { sessionId: first.sessionId, ...first.settings === void 0 ? {} : { settings: first.settings }, ...first.settingsFile === void 0 ? {} : { settingsFile: first.settingsFile } };
167104
167642
  let launch = first;
167105
- let compactedHere = false;
167643
+ let compactedHere;
167106
167644
  try {
167107
167645
  for (let moved = false; ; moved = true) {
167108
167646
  const plan = deps.prepare(launch);
@@ -167120,7 +167658,9 @@ async function supervise(deps, first) {
167120
167658
  }
167121
167659
  let outcome;
167122
167660
  try {
167123
- outcome = await runChild2(deps, plan, identity, compaction !== void 0 && !compactedHere);
167661
+ outcome = await runChild2(deps, plan, identity, compactedHere, (conversationId) => {
167662
+ compactedHere = conversationId;
167663
+ });
167124
167664
  } finally {
167125
167665
  plan.release();
167126
167666
  }
@@ -167130,28 +167670,23 @@ async function supervise(deps, first) {
167130
167670
  }
167131
167671
  return childExitCode(outcome.result);
167132
167672
  }
167133
- if (outcome.kind === "compact") {
167134
- const interrupted = compaction === void 0 ? void 0 : await compactSession(deps, compaction, outcome.slot, identity, plan.sessionId);
167135
- compactedHere = true;
167136
- if (interrupted !== void 0) {
167137
- return signalExit(interrupted);
167138
- }
167139
- launch = { ...base, conversation: "resume", member: memberName(deps, identity) };
167140
- continue;
167141
- }
167142
- launch = { ...base, conversation: "resume", member: memberName(deps, outcome.to), from: labelOf3(deps, identity), ...outcome.kind === "remodel" ? { model: outcome.model } : {} };
167143
- const compactedOnOld = compactedHere;
167144
- compactedHere = false;
167673
+ launch = { ...base, conversation: "resume", ...outcome.conversationId === plan.sessionId ? {} : { conversationId: outcome.conversationId }, member: memberName(deps, outcome.to), from: labelOf3(deps, identity), ...outcome.kind === "remodel" ? { model: outcome.model } : {} };
167674
+ const compactedOnOld = compactedHere === outcome.conversationId;
167675
+ compactedHere = void 0;
167145
167676
  if (compaction !== void 0) {
167146
167677
  compaction.markCompacted(plan.sessionId, false);
167147
167678
  const slot = compactedOnOld ? void 0 : compaction.acquire(outcome.to);
167148
167679
  if (slot !== void 0) {
167149
- const interrupted = await compactSession(deps, compaction, slot, outcome.to, plan.sessionId);
167150
- compactedHere = true;
167151
- if (interrupted !== void 0) {
167152
- return signalExit(interrupted);
167680
+ const result = await compactSession(deps, compaction, slot, outcome.to, plan.sessionId, outcome.conversationId);
167681
+ if (result.completed) compactedHere = outcome.conversationId;
167682
+ if (result.signal !== void 0) {
167683
+ return signalExit(result.signal);
167153
167684
  }
167685
+ } else {
167686
+ deps.lifecycle?.({ kind: "compaction", phase: "after_move", outcome: "not_attempted" });
167154
167687
  }
167688
+ } else {
167689
+ deps.lifecycle?.({ kind: "compaction", phase: "after_move", outcome: "not_attempted" });
167155
167690
  }
167156
167691
  }
167157
167692
  } finally {
@@ -167172,31 +167707,52 @@ async function runSupervised(params) {
167172
167707
  log.warn(`agent-shim: pool "${pool}" resumes on a spent quota, which needs a POSIX terminal; this launch runs unsupervised`);
167173
167708
  return void 0;
167174
167709
  }
167175
- const first = initialConversationOf(params.passthrough, { newId: import_node_crypto34.randomUUID, latestId: () => latestConversationId(farm.fs, { claudeHome: farm.claudeHome, cwd: farm.cwd }) });
167710
+ if (params.extraFlags.includes("--")) {
167711
+ log.warn(`agent-shim: pool "${pool}" cannot supervise a launch whose extra flags end option parsing`);
167712
+ return void 0;
167713
+ }
167714
+ const first = initialConversationOf(params.passthrough, { newId: import_node_crypto35.randomUUID, latestId: () => latestConversationId(farm.fs, { claudeHome: farm.claudeHome, cwd: farm.cwd }) });
167176
167715
  if ("reason" in first) {
167177
167716
  log.warn(`agent-shim: pool "${pool}" resumes on a spent quota, but this launch runs unsupervised: ${first.reason}`);
167178
167717
  return void 0;
167179
167718
  }
167180
- let launch = first;
167719
+ let entrypointSha256AtStart;
167720
+ try {
167721
+ const hash2 = (0, import_node_crypto35.createHash)("sha256");
167722
+ await (0, import_promises21.pipeline)((0, import_node_fs40.createReadStream)(realContentSourcePath()), hash2);
167723
+ entrypointSha256AtStart = hash2.digest("hex");
167724
+ } catch {
167725
+ entrypointSha256AtStart = null;
167726
+ log.warn("agent-shim: could not fingerprint the supervisor entrypoint");
167727
+ }
167728
+ const lifecycle = createLifecycleRecorder({ fs: realFarmFs, logsDir: paths.logsDir, fileId: (0, import_node_crypto35.randomUUID)(), sessionId: first.sessionId, supervisorPid: farm.lock.pid, supervisorVersion: package_default.version, entrypointSha256AtStart, now: farm.now, log });
167181
167729
  let compaction;
167182
167730
  const policy = params.pools[pool];
167183
- if (policy?.compactBeforeLimit === true) {
167184
- if (hasSettingsArgument(params.passthrough)) {
167185
- 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`);
167186
- } else {
167187
- launch = { ...first, settings: markHooksSettings(selfInvocation([]), paths.root, pool, first.sessionId) };
167188
- compaction = createCompactionDeps({
167189
- paths,
167190
- fs: realFarmFs,
167191
- pool,
167192
- policy,
167193
- pid: farm.lock.pid,
167194
- now: farm.now,
167195
- isRunning: farm.lock.isRunning,
167196
- sleep: farm.lock.sleep,
167197
- compact: createRealCompactor({ paths, spawnDaemon: params.spawnDaemon })
167198
- });
167199
- }
167731
+ const markSettings = markHooksSettings(selfInvocation([]), paths.root, pool, first.sessionId);
167732
+ const settingsArgs2 = [...params.extraFlags, ...params.passthrough];
167733
+ const settings2 = hasSettingsArgument(settingsArgs2) ? combineCallerSettings(settingsArgs2, markSettings, (name) => farm.fs.readFileUtf8(import_node_path96.default.resolve(farm.cwd, name))) : void 0;
167734
+ const plugin = policy?.compactBeforeLimit === true ? stageNativeCompactionPlugin() : void 0;
167735
+ if (policy?.compactBeforeLimit === true && plugin !== void 0) {
167736
+ const baseCompaction = createCompactionDeps({
167737
+ paths,
167738
+ fs: realFarmFs,
167739
+ pool,
167740
+ policy,
167741
+ pid: farm.lock.pid,
167742
+ now: farm.now,
167743
+ isRunning: farm.lock.isRunning,
167744
+ sleep: farm.lock.sleep,
167745
+ hooksFinished: (session, state) => {
167746
+ if (hooksPending(realFarmFs, paths, pool, session.sessionId)) {
167747
+ return false;
167748
+ }
167749
+ const conversationId = state.conversationId ?? session.sessionId;
167750
+ const text5 = state.transcriptPath === void 0 ? void 0 : realFarmFs.readFileUtf8(state.transcriptPath);
167751
+ return text5 !== void 0 && stopHooksFinished(text5, conversationId, state.at);
167752
+ },
167753
+ compact: createRealCompactor({ paths, spawnDaemon: params.spawnDaemon })
167754
+ });
167755
+ compaction = { ...baseCompaction, live: { ready: () => nativeCompactionReady(plugin), compact: async (conversationId, signal) => await compactInSession(plugin, conversationId, signal) } };
167200
167756
  }
167201
167757
  const mover = createMover({
167202
167758
  paths,
@@ -167226,64 +167782,120 @@ async function runSupervised(params) {
167226
167782
  pickMember: resolvePoolLaunch,
167227
167783
  log
167228
167784
  });
167229
- return await supervise(
167230
- {
167231
- pool,
167232
- cwd: farm.cwd,
167233
- pid: farm.lock.pid,
167234
- prepare: params.prepare,
167235
- spawn: realSupervisedSpawnPort,
167236
- signals: realSignalPort,
167237
- timer: realTimerPort,
167238
- watchChanges: (identity, onChange) => {
167239
- const stopSnapshot = realWatchDirectory(paths.usageSnapshotsDir, (filename) => filename === `${identity}.json`, `${identity}'s usage`, log)(onChange);
167240
- const stopState = compaction === void 0 ? void 0 : realWatchDirectory(stateDirOf(paths, pool), (filename) => filename.endsWith(".json"), "the pool's sessions", log)(onChange);
167241
- return () => {
167242
- stopSnapshot();
167243
- stopState?.();
167244
- };
167245
- },
167246
- quotaHit: (identity, sessionId, sinceMs) => quotaHitOf(realFarmFs, paths, identity, sessionId, sinceMs, farm.now()),
167247
- decideMove: async (request7) => {
167248
- await refreshPools({ paths, cwd: farm.cwd, poolNames: [pool], spawnDaemon: params.spawnDaemon, log: (line) => {
167249
- log.warn(line);
167250
- } });
167251
- return mover(request7);
167252
- },
167253
- contextTokens: (sessionId) => resumedContextTokens(farm.fs, { claudeHome: farm.claudeHome, cwd: farm.cwd, passthrough: ["--resume", sessionId] }),
167254
- claimModelMove: (sessionId) => {
167255
- const request7 = readModelMove(realFarmFs, paths, sessionId);
167256
- if (request7 === void 0) {
167257
- return void 0;
167785
+ const staged = settings2 === void 0 ? void 0 : stageSupervisedSettings(realFarmFs, paths, pool, first.sessionId, farm.lock.pid, settings2);
167786
+ const launch = { ...first, ...staged === void 0 ? { settings: markSettings } : { settingsFile: staged.file } };
167787
+ try {
167788
+ return await supervise(
167789
+ {
167790
+ pool,
167791
+ cwd: farm.cwd,
167792
+ pid: farm.lock.pid,
167793
+ lifecycle,
167794
+ prepare: (nextLaunch) => {
167795
+ const plan = params.prepare(nextLaunch);
167796
+ if (plugin === void 0) return plan;
167797
+ (0, import_node_fs40.rmSync)(plugin.ready, { force: true });
167798
+ return { ...plan, args: withNativeCompactionPlugin(plan.args, plugin.directory) };
167799
+ },
167800
+ spawn: realSupervisedSpawnPort,
167801
+ signals: realSignalPort,
167802
+ timer: realTimerPort,
167803
+ watchChanges: (identity, onChange) => {
167804
+ const stopPlugin = plugin === void 0 ? void 0 : realWatchExistingDirectory(plugin.directory, (filename) => filename === "ready.json", "the compaction plugin", log)(onChange);
167805
+ const stopSnapshot = realWatchDirectory(paths.usageSnapshotsDir, (filename) => filename === `${identity}.json`, `${identity}'s usage`, log)(onChange);
167806
+ let watchedDir;
167807
+ let stopTranscripts;
167808
+ let transcriptWarning = "";
167809
+ const watchTranscript = () => {
167810
+ const transcript = readSessionState(realFarmFs, paths, pool, first.sessionId)?.transcriptPath;
167811
+ const directory = transcript === void 0 ? void 0 : import_node_path96.default.dirname(transcript);
167812
+ if (compaction === void 0 || directory === watchedDir) {
167813
+ return;
167814
+ }
167815
+ stopTranscripts?.();
167816
+ watchedDir = void 0;
167817
+ stopTranscripts = void 0;
167818
+ if (directory !== void 0 && realFarmFs.lstat(directory) !== void 0) {
167819
+ try {
167820
+ stopTranscripts = realWatchExistingDirectory(directory, (filename) => filename.endsWith(".jsonl"), "the session transcripts", log)(onChange);
167821
+ watchedDir = directory;
167822
+ transcriptWarning = "";
167823
+ } catch (error63) {
167824
+ const warning = `agent-shim: could not watch the session transcripts: ${error63 instanceof Error ? error63.message : String(error63)}`;
167825
+ if (warning !== transcriptWarning) {
167826
+ transcriptWarning = warning;
167827
+ log.warn(warning);
167828
+ }
167829
+ }
167830
+ }
167831
+ };
167832
+ const stopState = realWatchDirectory(stateDirOf(paths, pool), (filename) => filename.endsWith(".json"), "the pool's sessions", log)(() => {
167833
+ watchTranscript();
167834
+ onChange();
167835
+ });
167836
+ watchTranscript();
167837
+ if (plugin !== void 0 && nativeCompactionReady(plugin)) queueMicrotask(onChange);
167838
+ return () => {
167839
+ stopPlugin?.();
167840
+ stopSnapshot();
167841
+ stopState();
167842
+ stopTranscripts?.();
167843
+ };
167844
+ },
167845
+ quotaHit: (identity, sessionId, sinceMs) => quotaHitOf(realFarmFs, paths, identity, sessionId, sinceMs, farm.now()),
167846
+ decideMove: async (request7) => {
167847
+ await refreshPools({ paths, cwd: farm.cwd, poolNames: [pool], spawnDaemon: params.spawnDaemon, log: (line) => {
167848
+ log.warn(line);
167849
+ } });
167850
+ return mover(request7);
167851
+ },
167852
+ contextTokens: (sessionId) => {
167853
+ const state = readSessionState(realFarmFs, paths, pool, first.sessionId);
167854
+ if (state?.transcriptPath === void 0 || (state.conversationId ?? first.sessionId) !== sessionId) {
167855
+ return void 0;
167856
+ }
167857
+ const transcript = realFarmFs.readFileUtf8(state.transcriptPath);
167858
+ return transcript === void 0 ? void 0 : contextTokensOfTranscript(transcript);
167859
+ },
167860
+ currentConversationId: (sessionId) => currentConversation(realFarmFs, paths, pool, sessionId),
167861
+ claimModelMove: (sessionId) => {
167862
+ const request7 = readModelMove(realFarmFs, paths, sessionId);
167863
+ if (request7 === void 0) {
167864
+ return void 0;
167865
+ }
167866
+ removeModelMove(realFarmFs, paths, sessionId);
167867
+ return { to: request7.to, model: request7.model };
167868
+ },
167869
+ decideRemodel: (request7) => identityMover(request7),
167870
+ watchModelMoves: (onChange) => realWatchDirectory(paths.modelMovesDir, () => true, "the model-move requests", log)(onChange),
167871
+ ...compaction === void 0 ? {} : { compaction },
167872
+ register: (session) => {
167873
+ registerSupervised(realFarmFs, paths, session);
167874
+ },
167875
+ unregister: (sessionId) => {
167876
+ unregisterSupervised(realFarmFs, paths, pool, sessionId);
167877
+ },
167878
+ resetTerminal,
167879
+ now: farm.now,
167880
+ log,
167881
+ // An identity whose name cannot be read is named by its id, which reaches it, so its relaunch reports the file.
167882
+ nameOf: (id2) => {
167883
+ const record3 = identityRecordsOver(realFarmFs, paths.identitiesDir).find((candidate) => candidate.id === id2);
167884
+ return record3 === void 0 ? void 0 : record3.name ?? record3.id;
167258
167885
  }
167259
- removeModelMove(realFarmFs, paths, sessionId);
167260
- return { to: request7.to, model: request7.model };
167261
167886
  },
167262
- decideRemodel: (request7) => identityMover({ sessionId: request7.sessionId, from: request7.from, to: request7.to, contextTokens: void 0 }),
167263
- watchModelMoves: (onChange) => realWatchDirectory(paths.modelMovesDir, () => true, "the model-move requests", log)(onChange),
167264
- ...compaction === void 0 ? {} : { compaction },
167265
- register: (session) => {
167266
- registerSupervised(realFarmFs, paths, session);
167267
- },
167268
- unregister: (sessionId) => {
167269
- unregisterSupervised(realFarmFs, paths, pool, sessionId);
167270
- },
167271
- resetTerminal,
167272
- now: farm.now,
167273
- log,
167274
- // An identity whose name cannot be read is named by its id, which reaches it, so its relaunch reports the file.
167275
- nameOf: (id2) => {
167276
- const record3 = identityRecordsOver(realFarmFs, paths.identitiesDir).find((candidate) => candidate.id === id2);
167277
- return record3 === void 0 ? void 0 : record3.name ?? record3.id;
167278
- }
167279
- },
167280
- launch
167281
- );
167887
+ launch
167888
+ );
167889
+ } finally {
167890
+ staged?.release();
167891
+ plugin?.release();
167892
+ }
167282
167893
  }
167283
167894
 
167284
167895
  // src/runClaude.ts
167285
167896
  init_launcher();
167286
167897
  init_argv();
167898
+ init_extraFlags();
167287
167899
 
167288
167900
  // src/launcher/native.ts
167289
167901
  init_cliError();
@@ -167416,6 +168028,7 @@ async function runClaude(argvOverride) {
167416
168028
  pools: farm.pools,
167417
168029
  farm: farm.runtime,
167418
168030
  passthrough: nativeArgv.rest,
168031
+ extraFlags: splitExtraFlags(procForDecision.env.CLAUDE_EXTRA_FLAGS),
167419
168032
  // 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.
167420
168033
  prepare: (launch) => prepareLaunch(launch.member === void 0 ? { ...prepareParams, supervised: launch } : { ...prepareParams, update: void 0, supervised: launch }),
167421
168034
  spawnDaemon: spawnDetachedSupervisor,
@@ -167431,7 +168044,7 @@ async function runClaude(argvOverride) {
167431
168044
  // src/cli.ts
167432
168045
  async function main() {
167433
168046
  aliasLegacyEnv(process.env);
167434
- const invokedName = import_node_path91.default.basename(process.argv[1] ?? "agent-shim");
168047
+ const invokedName = import_node_path97.default.basename(process.argv[1] ?? "agent-shim");
167435
168048
  if (isInvokedAsClaude(invokedName)) {
167436
168049
  await runClaude();
167437
168050
  return;