agent-shim 11.84.0 → 11.84.1

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.
Files changed (4) hide show
  1. package/dist/cli.cjs +1043 -1009
  2. package/dist/index.cjs +499 -465
  3. package/dist/index.mjs +487 -453
  4. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1278,7 +1278,7 @@ function parseIgnoringUnrecognisedKeys(schema, raw) {
1278
1278
  return second.success ? { success: true, data: second.data, ignored } : { success: false, issues: second.error.issues };
1279
1279
  }
1280
1280
  function describeIgnoredKeys(filePath, ignored) {
1281
- const places = ignored.map(({ path: path48, keys }) => `${path48.length === 0 ? "" : `${path48.map(String).join(".")}.`}${keys.join(", ")}`);
1281
+ const places = ignored.map(({ path: path49, keys }) => `${path49.length === 0 ? "" : `${path49.map(String).join(".")}.`}${keys.join(", ")}`);
1282
1282
  return `${filePath} has settings this version of agent-shim does not know and ignores: ${places.join("; ")}. A newer release may read them.`;
1283
1283
  }
1284
1284
  function noteIgnoredKeys(filePath, ignored) {
@@ -1300,9 +1300,9 @@ function restoreIgnoredKeys(filePath, value) {
1300
1300
  return value;
1301
1301
  }
1302
1302
  const restored = structuredClone(value);
1303
- for (const { path: path48, values } of ignored) {
1303
+ for (const { path: path49, values } of ignored) {
1304
1304
  let holder = restored;
1305
- for (const step of path48) {
1305
+ for (const step of path49) {
1306
1306
  holder = isRecord(holder) ? holder[step] : void 0;
1307
1307
  }
1308
1308
  if (isRecord(holder)) {
@@ -3022,8 +3022,8 @@ var init_lock = __esm({
3022
3022
  // src/launcher/farm.ts
3023
3023
  import path8 from "node:path";
3024
3024
  import { z as z4 } from "zod";
3025
- function readFarmManifest(fs15, farmRoot) {
3026
- const raw = fs15.readFileUtf8(path8.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs15.readFileUtf8(path8.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
3025
+ function readFarmManifest(fs16, farmRoot) {
3026
+ const raw = fs16.readFileUtf8(path8.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs16.readFileUtf8(path8.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
3027
3027
  if (raw === void 0) {
3028
3028
  return void 0;
3029
3029
  }
@@ -3081,9 +3081,9 @@ function buildEntryFacts(params) {
3081
3081
  entries
3082
3082
  };
3083
3083
  }
3084
- function listSubtree(fs15, root, rel) {
3084
+ function listSubtree(fs16, root, rel) {
3085
3085
  const absolute = path8.join(root, rel);
3086
- const stat = fs15.lstat(absolute);
3086
+ const stat = fs16.lstat(absolute);
3087
3087
  if (stat === void 0) {
3088
3088
  return [];
3089
3089
  }
@@ -3091,10 +3091,10 @@ function listSubtree(fs15, root, rel) {
3091
3091
  return [{ rel, kind: "symlink" }];
3092
3092
  }
3093
3093
  if (stat.kind === "dir") {
3094
- const children = [...fs15.readdir(absolute)].sort().flatMap((name) => listSubtree(fs15, root, `${rel}/${name}`));
3094
+ const children = [...fs16.readdir(absolute)].sort().flatMap((name) => listSubtree(fs16, root, `${rel}/${name}`));
3095
3095
  return [{ rel, kind: "dir" }, ...children];
3096
3096
  }
3097
- const contentHash = fs15.hashFile(absolute);
3097
+ const contentHash = fs16.hashFile(absolute);
3098
3098
  return [{ rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } }];
3099
3099
  }
3100
3100
  function topLevelScopeRoots(roots) {
@@ -3108,25 +3108,25 @@ function topLevelScopeRoots(roots) {
3108
3108
  }
3109
3109
  return kept;
3110
3110
  }
3111
- function reconciliationScope(fs15, farmRoot, manifest) {
3111
+ function reconciliationScope(fs16, farmRoot, manifest) {
3112
3112
  if (manifest !== void 0) {
3113
3113
  return topLevelScopeRoots(manifest.materialised);
3114
3114
  }
3115
- return [...fs15.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs15.lstat(path8.join(farmRoot, name))?.kind === "dir").sort();
3115
+ return [...fs16.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs16.lstat(path8.join(farmRoot, name))?.kind === "dir").sort();
3116
3116
  }
3117
- function collectFarmListing(fs15, farmRoot, scopeRoots) {
3118
- return scopeRoots.flatMap((root) => listSubtree(fs15, farmRoot, root));
3117
+ function collectFarmListing(fs16, farmRoot, scopeRoots) {
3118
+ return scopeRoots.flatMap((root) => listSubtree(fs16, farmRoot, root));
3119
3119
  }
3120
- function collectCanonicalCounterparts(fs15, claudeHome, farmListing) {
3120
+ function collectCanonicalCounterparts(fs16, claudeHome, farmListing) {
3121
3121
  const out = [];
3122
3122
  for (const entry of farmListing) {
3123
3123
  const absolute = path8.join(claudeHome, entry.rel);
3124
- const stat = fs15.lstat(absolute);
3124
+ const stat = fs16.lstat(absolute);
3125
3125
  if (stat === void 0) {
3126
3126
  continue;
3127
3127
  }
3128
3128
  if (stat.kind === "file") {
3129
- const contentHash = fs15.hashFile(absolute);
3129
+ const contentHash = fs16.hashFile(absolute);
3130
3130
  out.push({ rel: entry.rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } });
3131
3131
  continue;
3132
3132
  }
@@ -3964,9 +3964,9 @@ var init_providerCatalogue = __esm({
3964
3964
  // src/frontdoor/state.ts
3965
3965
  import path10 from "node:path";
3966
3966
  import { z as z6 } from "zod";
3967
- function readCatalogueStatus(fs15, paths, pid, generation, name) {
3967
+ function readCatalogueStatus(fs16, paths, pid, generation, name) {
3968
3968
  const file = path10.join(path10.dirname(catalogueCachePath(paths, name, pid, generation)), `${name}.status.json`);
3969
- const raw = fs15.readFileUtf8(file);
3969
+ const raw = fs16.readFileUtf8(file);
3970
3970
  if (raw === void 0) return void 0;
3971
3971
  try {
3972
3972
  const value = z6.strictObject({ status: z6.enum(["running", "ready", "failed"]), fingerprint: z6.string().min(1).optional(), recordedAt: z6.number().optional() }).safeParse(JSON.parse(raw));
@@ -3975,14 +3975,14 @@ function readCatalogueStatus(fs15, paths, pid, generation, name) {
3975
3975
  return void 0;
3976
3976
  }
3977
3977
  }
3978
- function writeFrontDoorCodexHome(fs15, frontdoorDir, pid, codexHome, generation) {
3978
+ function writeFrontDoorCodexHome(fs16, frontdoorDir, pid, codexHome, generation) {
3979
3979
  const directory = path10.join(frontdoorDir, "codex-homes");
3980
- fs15.mkdirp(directory);
3981
- fs15.writeFilePrivate(path10.join(directory, `${String(pid)}.json`), `${JSON.stringify({ codexHome, generation })}
3980
+ fs16.mkdirp(directory);
3981
+ fs16.writeFilePrivate(path10.join(directory, `${String(pid)}.json`), `${JSON.stringify({ codexHome, generation })}
3982
3982
  `);
3983
3983
  }
3984
- function readFrontDoorCodexRecord(fs15, frontdoorDir, pid) {
3985
- const raw = fs15.readFileUtf8(path10.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
3984
+ function readFrontDoorCodexRecord(fs16, frontdoorDir, pid) {
3985
+ const raw = fs16.readFileUtf8(path10.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
3986
3986
  if (raw === void 0) return void 0;
3987
3987
  try {
3988
3988
  const parsed = z6.strictObject({ codexHome: z6.string().min(1), generation: z6.uuid() }).safeParse(JSON.parse(raw));
@@ -3991,13 +3991,13 @@ function readFrontDoorCodexRecord(fs15, frontdoorDir, pid) {
3991
3991
  return void 0;
3992
3992
  }
3993
3993
  }
3994
- function removeFrontDoorCodexHome(fs15, frontdoorDir, pid) {
3995
- fs15.removeRecursive(path10.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
3994
+ function removeFrontDoorCodexHome(fs16, frontdoorDir, pid) {
3995
+ fs16.removeRecursive(path10.join(frontdoorDir, "codex-homes", `${String(pid)}.json`));
3996
3996
  }
3997
- function readFrontDoorState(fs15, stateFile) {
3997
+ function readFrontDoorState(fs16, stateFile) {
3998
3998
  let raw;
3999
3999
  try {
4000
- raw = fs15.readFileUtf8(stateFile);
4000
+ raw = fs16.readFileUtf8(stateFile);
4001
4001
  } catch {
4002
4002
  return void 0;
4003
4003
  }
@@ -4011,9 +4011,9 @@ function readFrontDoorState(fs15, stateFile) {
4011
4011
  return void 0;
4012
4012
  }
4013
4013
  }
4014
- function writeFrontDoorState(fs15, stateFile, state) {
4015
- fs15.mkdirp(path10.dirname(stateFile));
4016
- fs15.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
4014
+ function writeFrontDoorState(fs16, stateFile, state) {
4015
+ fs16.mkdirp(path10.dirname(stateFile));
4016
+ fs16.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
4017
4017
  `);
4018
4018
  }
4019
4019
  function directOrigin(port) {
@@ -4023,37 +4023,37 @@ function frontDoorOrigin(state) {
4023
4023
  const port = state?.directPort ?? state?.lastDirectPort;
4024
4024
  return port === void 0 ? void 0 : directOrigin(port);
4025
4025
  }
4026
- function writeFrontDoorDirectRecord(fs15, recordsDir, record) {
4027
- fs15.mkdirp(recordsDir);
4028
- fs15.writeFilePrivate(path10.join(recordsDir, `${String(record.pid)}.json`), `${JSON.stringify({ directPort: record.directPort })}
4026
+ function writeFrontDoorDirectRecord(fs16, recordsDir, record) {
4027
+ fs16.mkdirp(recordsDir);
4028
+ fs16.writeFilePrivate(path10.join(recordsDir, `${String(record.pid)}.json`), `${JSON.stringify({ directPort: record.directPort })}
4029
4029
  `);
4030
4030
  }
4031
- function removeFrontDoorDirectRecord(fs15, recordsDir, pid) {
4032
- fs15.removeRecursive(path10.join(recordsDir, `${String(pid)}.json`));
4031
+ function removeFrontDoorDirectRecord(fs16, recordsDir, pid) {
4032
+ fs16.removeRecursive(path10.join(recordsDir, `${String(pid)}.json`));
4033
4033
  }
4034
- function markFrontDoorDraining(fs15, markersDir, pid) {
4035
- fs15.mkdirp(markersDir);
4036
- fs15.writeFilePrivate(path10.join(markersDir, String(pid)), "\n");
4034
+ function markFrontDoorDraining(fs16, markersDir, pid) {
4035
+ fs16.mkdirp(markersDir);
4036
+ fs16.writeFilePrivate(path10.join(markersDir, String(pid)), "\n");
4037
4037
  }
4038
- function unmarkFrontDoorDraining(fs15, markersDir, pid) {
4039
- fs15.removeRecursive(path10.join(markersDir, String(pid)));
4038
+ function unmarkFrontDoorDraining(fs16, markersDir, pid) {
4039
+ fs16.removeRecursive(path10.join(markersDir, String(pid)));
4040
4040
  }
4041
- function listDrainingFrontDoors(fs15, markersDir, isRunning) {
4042
- return fs15.readdir(markersDir).flatMap((file) => /^[1-9]\d*$/.test(file) && Number.isSafeInteger(Number(file)) ? [Number(file)] : []).filter(isRunning).sort((a, b) => a - b);
4041
+ function listDrainingFrontDoors(fs16, markersDir, isRunning) {
4042
+ return fs16.readdir(markersDir).flatMap((file) => /^[1-9]\d*$/.test(file) && Number.isSafeInteger(Number(file)) ? [Number(file)] : []).filter(isRunning).sort((a, b) => a - b);
4043
4043
  }
4044
4044
  function recordPid(file) {
4045
4045
  const pidText = /^([1-9]\d*)\.json$/.exec(file)?.[1];
4046
4046
  const pid = pidText === void 0 ? void 0 : Number(pidText);
4047
4047
  return pid !== void 0 && Number.isSafeInteger(pid) ? pid : void 0;
4048
4048
  }
4049
- function readDirectRecordEntry(fs15, recordsDir, file) {
4049
+ function readDirectRecordEntry(fs16, recordsDir, file) {
4050
4050
  const pid = recordPid(file);
4051
4051
  if (pid === void 0) {
4052
4052
  return void 0;
4053
4053
  }
4054
4054
  let raw;
4055
4055
  try {
4056
- raw = fs15.readFileUtf8(path10.join(recordsDir, file));
4056
+ raw = fs16.readFileUtf8(path10.join(recordsDir, file));
4057
4057
  } catch {
4058
4058
  return void 0;
4059
4059
  }
@@ -4067,37 +4067,37 @@ function readDirectRecordEntry(fs15, recordsDir, file) {
4067
4067
  return { malformed: true };
4068
4068
  }
4069
4069
  }
4070
- function listFrontDoorDirectRecords(fs15, recordsDir) {
4071
- return fs15.readdir(recordsDir).flatMap((file) => {
4072
- const entry = readDirectRecordEntry(fs15, recordsDir, file);
4070
+ function listFrontDoorDirectRecords(fs16, recordsDir) {
4071
+ return fs16.readdir(recordsDir).flatMap((file) => {
4072
+ const entry = readDirectRecordEntry(fs16, recordsDir, file);
4073
4073
  return entry?.record === void 0 ? [] : [entry.record];
4074
4074
  }).sort((a, b) => a.pid - b.pid);
4075
4075
  }
4076
- function pruneMalformedFrontDoorDirectFiles(fs15, recordsDir, isRunning) {
4077
- for (const file of fs15.readdir(recordsDir)) {
4076
+ function pruneMalformedFrontDoorDirectFiles(fs16, recordsDir, isRunning) {
4077
+ for (const file of fs16.readdir(recordsDir)) {
4078
4078
  const writer = RECORD_TEMPORARY_FILE.exec(file)?.[1];
4079
4079
  const stale = writer !== void 0 && !isRunning(Number(writer));
4080
- if (stale || readDirectRecordEntry(fs15, recordsDir, file)?.malformed === true) {
4081
- fs15.removeRecursive(path10.join(recordsDir, file));
4080
+ if (stale || readDirectRecordEntry(fs16, recordsDir, file)?.malformed === true) {
4081
+ fs16.removeRecursive(path10.join(recordsDir, file));
4082
4082
  }
4083
4083
  }
4084
4084
  }
4085
4085
  function liveFrontDoorDirectRecords(records, liveness) {
4086
4086
  return records.filter((record) => liveness.doors.has(record.pid) || liveness.unknown.has(record.pid));
4087
4087
  }
4088
- function pruneDeadFrontDoorDirectRecords(fs15, recordsDir, records, liveness) {
4088
+ function pruneDeadFrontDoorDirectRecords(fs16, recordsDir, records, liveness) {
4089
4089
  for (const record of records) {
4090
4090
  if (!liveness.doors.has(record.pid) && !liveness.unknown.has(record.pid)) {
4091
- removeFrontDoorDirectRecord(fs15, recordsDir, record.pid);
4091
+ removeFrontDoorDirectRecord(fs16, recordsDir, record.pid);
4092
4092
  }
4093
4093
  }
4094
4094
  }
4095
4095
  function recordOf(details) {
4096
4096
  return details === void 0 ? {} : { sessionId: details.sessionId, ...details.models === void 0 ? {} : { models: details.models } };
4097
4097
  }
4098
- function writeFrontDoorSession(fs15, sessionsDir, session) {
4099
- fs15.mkdirPrivate(sessionsDir);
4100
- fs15.writeFilePrivate(path10.join(sessionsDir, sessionRecordName(session.pid)), `${JSON.stringify(session, null, 2)}
4098
+ function writeFrontDoorSession(fs16, sessionsDir, session) {
4099
+ fs16.mkdirPrivate(sessionsDir);
4100
+ fs16.writeFilePrivate(path10.join(sessionsDir, sessionRecordName(session.pid)), `${JSON.stringify(session, null, 2)}
4101
4101
  `);
4102
4102
  }
4103
4103
  function sessionRecordName(pid) {
@@ -4109,32 +4109,32 @@ function isSessionRecordName(name) {
4109
4109
  function summaryOf(session) {
4110
4110
  return { pid: session.pid, startedAt: session.startedAt, ...session.supervisorPid === void 0 ? {} : { supervisorPid: session.supervisorPid } };
4111
4111
  }
4112
- function readFrontDoorSessionRecord(fs15, sessionsDir, name) {
4112
+ function readFrontDoorSessionRecord(fs16, sessionsDir, name) {
4113
4113
  try {
4114
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs15.readFileUtf8(path10.join(sessionsDir, name)) ?? ""));
4114
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs16.readFileUtf8(path10.join(sessionsDir, name)) ?? ""));
4115
4115
  return parsed.success ? parsed.data : void 0;
4116
4116
  } catch {
4117
4117
  return void 0;
4118
4118
  }
4119
4119
  }
4120
- function listFrontDoorSessions(fs15, sessionsDir) {
4120
+ function listFrontDoorSessions(fs16, sessionsDir) {
4121
4121
  const sessions = [];
4122
- for (const name of fs15.readdir(sessionsDir)) {
4123
- const record = isSessionRecordName(name) ? readFrontDoorSessionRecord(fs15, sessionsDir, name) : void 0;
4122
+ for (const name of fs16.readdir(sessionsDir)) {
4123
+ const record = isSessionRecordName(name) ? readFrontDoorSessionRecord(fs16, sessionsDir, name) : void 0;
4124
4124
  if (record !== void 0) {
4125
4125
  sessions.push(summaryOf(record));
4126
4126
  }
4127
4127
  }
4128
4128
  return sessions.sort((a, b) => a.pid - b.pid);
4129
4129
  }
4130
- function removeFrontDoorSession(fs15, sessionsDir, pid) {
4131
- fs15.removeRecursive(path10.join(sessionsDir, sessionRecordName(pid)));
4130
+ function removeFrontDoorSession(fs16, sessionsDir, pid) {
4131
+ fs16.removeRecursive(path10.join(sessionsDir, sessionRecordName(pid)));
4132
4132
  }
4133
- function pruneDeadFrontDoorSessions(fs15, sessionsDir, listed, isRunning) {
4133
+ function pruneDeadFrontDoorSessions(fs16, sessionsDir, listed, isRunning) {
4134
4134
  const removed = [];
4135
4135
  for (const session of listed) {
4136
4136
  if (!isRunning(session.pid)) {
4137
- removeFrontDoorSession(fs15, sessionsDir, session.pid);
4137
+ removeFrontDoorSession(fs16, sessionsDir, session.pid);
4138
4138
  removed.push(session.pid);
4139
4139
  }
4140
4140
  }
@@ -4217,19 +4217,19 @@ var init_processRole = __esm({
4217
4217
  // src/frontdoor/catalogueCleanup.ts
4218
4218
  import path11 from "node:path";
4219
4219
  import { z as z7 } from "zod";
4220
- async function pruneAbandonedCatalogueGenerations(fs15, paths, ownPid, generation, runningAmong) {
4220
+ async function pruneAbandonedCatalogueGenerations(fs16, paths, ownPid, generation, runningAmong) {
4221
4221
  const root = path11.join(paths.catalogueDir, "supervisors");
4222
- const owners = fs15.readdir(root).flatMap((entry) => {
4222
+ const owners = fs16.readdir(root).flatMap((entry) => {
4223
4223
  const pid = Number(entry);
4224
- return Number.isSafeInteger(pid) && pid > 0 && String(pid) === entry && fs15.lstat(path11.join(root, entry))?.kind === "dir" ? [pid] : [];
4224
+ return Number.isSafeInteger(pid) && pid > 0 && String(pid) === entry && fs16.lstat(path11.join(root, entry))?.kind === "dir" ? [pid] : [];
4225
4225
  });
4226
4226
  const running = await runningAmong(owners);
4227
4227
  for (const pid of owners) {
4228
4228
  if (pid !== ownPid && running.has(pid)) continue;
4229
4229
  const directory = path11.join(root, String(pid));
4230
- for (const entry of fs15.readdir(directory)) {
4230
+ for (const entry of fs16.readdir(directory)) {
4231
4231
  const candidate = path11.join(directory, entry);
4232
- if (z7.uuid().safeParse(entry).success && (pid !== ownPid || entry !== generation) && fs15.lstat(candidate)?.kind === "dir") fs15.removeRecursive(candidate);
4232
+ if (z7.uuid().safeParse(entry).success && (pid !== ownPid || entry !== generation) && fs16.lstat(candidate)?.kind === "dir") fs16.removeRecursive(candidate);
4233
4233
  }
4234
4234
  }
4235
4235
  }
@@ -4258,9 +4258,9 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
4258
4258
  }
4259
4259
  }
4260
4260
  async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4261
- const { fs: fs15, paths } = ports;
4261
+ const { fs: fs16, paths } = ports;
4262
4262
  const servingBinary = ports.statOwnExecutable();
4263
- const previous = readFrontDoorState(fs15, paths.frontdoorStateFile);
4263
+ const previous = readFrontDoorState(fs16, paths.frontdoorStateFile);
4264
4264
  let lastPort = previous?.lastPort;
4265
4265
  let lastConnectPort = previous?.lastConnectPort;
4266
4266
  let lastDirectPort = previous?.lastDirectPort;
@@ -4274,8 +4274,8 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4274
4274
  const fail = async (message) => {
4275
4275
  ports.closeRcStreamHub();
4276
4276
  if (predecessor === void 0) {
4277
- writeFrontDoorState(fs15, paths.frontdoorStateFile, { lastError: message, ...sticky() });
4278
- fs15.removeRecursive(paths.frontdoorLockFile);
4277
+ writeFrontDoorState(fs16, paths.frontdoorStateFile, { lastError: message, ...sticky() });
4278
+ fs16.removeRecursive(paths.frontdoorLockFile);
4279
4279
  }
4280
4280
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
4281
4281
  const chain = ports.respawnChain;
@@ -4286,7 +4286,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4286
4286
  return 1;
4287
4287
  };
4288
4288
  if (predecessor === void 0) {
4289
- writeFrontDoorState(fs15, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
4289
+ writeFrontDoorState(fs16, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
4290
4290
  }
4291
4291
  const previousSticky = lastPort;
4292
4292
  let http3;
@@ -4327,14 +4327,14 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4327
4327
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom admits the new address once its supervisor rewrites the allowlist file)`);
4328
4328
  }
4329
4329
  lastDirectPort = direct.port;
4330
- writeFrontDoorDirectRecord(fs15, paths.frontdoorDirectRecordsDir, { pid: ports.ownPid, directPort: direct.port });
4331
- writeFrontDoorCodexHome(fs15, paths.frontdoorDir, ports.ownPid, ports.codexHome, ports.catalogueGeneration);
4332
- writeFrontDoorState(fs15, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http3.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
4333
- await pruneAbandonedCatalogueGenerations(fs15, paths, ports.ownPid, ports.catalogueGeneration, ports.runningAmong);
4330
+ writeFrontDoorDirectRecord(fs16, paths.frontdoorDirectRecordsDir, { pid: ports.ownPid, directPort: direct.port });
4331
+ writeFrontDoorCodexHome(fs16, paths.frontdoorDir, ports.ownPid, ports.codexHome, ports.catalogueGeneration);
4332
+ writeFrontDoorState(fs16, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http3.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
4333
+ await pruneAbandonedCatalogueGenerations(fs16, paths, ports.ownPid, ports.catalogueGeneration, ports.runningAmong);
4334
4334
  ports.onServing();
4335
4335
  ports.doorHealth.generation({ providerPort: http3.port, connectPort: connect3.port, directPort: direct.port });
4336
4336
  if (predecessor === void 0) {
4337
- fs15.removeRecursive(paths.frontdoorLockFile);
4337
+ fs16.removeRecursive(paths.frontdoorLockFile);
4338
4338
  } else {
4339
4339
  predecessor.serving();
4340
4340
  }
@@ -4343,7 +4343,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4343
4343
  let idleSince;
4344
4344
  let ticks = 0;
4345
4345
  const supersedingOwner = async () => {
4346
- const owner = readFrontDoorState(fs15, paths.frontdoorStateFile)?.supervisorPid;
4346
+ const owner = readFrontDoorState(fs16, paths.frontdoorStateFile)?.supervisorPid;
4347
4347
  return owner !== void 0 && owner !== ports.ownPid && (await ports.runningAmong([owner])).has(owner) ? owner : void 0;
4348
4348
  };
4349
4349
  let supersededBy;
@@ -4372,15 +4372,15 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4372
4372
  ports.stopBackgroundWork?.();
4373
4373
  const drained = [direct.drain(), connect3.drain(), http3.drain()];
4374
4374
  if (await supersedingOwner() === void 0) {
4375
- writeFrontDoorState(fs15, paths.frontdoorStateFile, sticky());
4375
+ writeFrontDoorState(fs16, paths.frontdoorStateFile, sticky());
4376
4376
  }
4377
- markFrontDoorDraining(fs15, paths.frontdoorDrainingDir, ports.ownPid);
4377
+ markFrontDoorDraining(fs16, paths.frontdoorDrainingDir, ports.ownPid);
4378
4378
  ports.closeRcStreamHub();
4379
4379
  await Promise.all(drained);
4380
- unmarkFrontDoorDraining(fs15, paths.frontdoorDrainingDir, ports.ownPid);
4381
- removeFrontDoorDirectRecord(fs15, paths.frontdoorDirectRecordsDir, ports.ownPid);
4382
- removeFrontDoorCodexHome(fs15, paths.frontdoorDir, ports.ownPid);
4383
- fs15.removeRecursive(catalogueGenerationDir(paths, ports.ownPid, ports.catalogueGeneration));
4380
+ unmarkFrontDoorDraining(fs16, paths.frontdoorDrainingDir, ports.ownPid);
4381
+ removeFrontDoorDirectRecord(fs16, paths.frontdoorDirectRecordsDir, ports.ownPid);
4382
+ removeFrontDoorCodexHome(fs16, paths.frontdoorDir, ports.ownPid);
4383
+ fs16.removeRecursive(catalogueGenerationDir(paths, ports.ownPid, ports.catalogueGeneration));
4384
4384
  ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: the connections this door carried have ended; exiting`);
4385
4385
  return 0;
4386
4386
  };
@@ -4401,14 +4401,14 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4401
4401
  await connect3.close();
4402
4402
  await http3.close();
4403
4403
  ports.closeRcStreamHub();
4404
- removeFrontDoorDirectRecord(fs15, paths.frontdoorDirectRecordsDir, ports.ownPid);
4405
- removeFrontDoorCodexHome(fs15, paths.frontdoorDir, ports.ownPid);
4406
- fs15.removeRecursive(catalogueGenerationDir(paths, ports.ownPid, ports.catalogueGeneration));
4404
+ removeFrontDoorDirectRecord(fs16, paths.frontdoorDirectRecordsDir, ports.ownPid);
4405
+ removeFrontDoorCodexHome(fs16, paths.frontdoorDir, ports.ownPid);
4406
+ fs16.removeRecursive(catalogueGenerationDir(paths, ports.ownPid, ports.catalogueGeneration));
4407
4407
  };
4408
4408
  const shutdown = async () => {
4409
4409
  await closeServing();
4410
4410
  if (await supersedingOwner() === void 0) {
4411
- writeFrontDoorState(fs15, paths.frontdoorStateFile, sticky());
4411
+ writeFrontDoorState(fs16, paths.frontdoorStateFile, sticky());
4412
4412
  }
4413
4413
  return 0;
4414
4414
  };
@@ -4427,7 +4427,7 @@ async function serveFrontDoor(idleShutdownMinutes, ports, options) {
4427
4427
  ticks += 1;
4428
4428
  const listed = ports.registry.rescan();
4429
4429
  const running = await ports.runningAmong(listed.map((session) => session.pid));
4430
- const pruned = pruneDeadFrontDoorSessions(fs15, paths.frontdoorSessionsDir, listed, (pid) => running.has(pid));
4430
+ const pruned = pruneDeadFrontDoorSessions(fs16, paths.frontdoorSessionsDir, listed, (pid) => running.has(pid));
4431
4431
  ports.registry.forget(pruned);
4432
4432
  ports.observeLaunchRegistry(listed, pruned);
4433
4433
  ports.checkQuotaExpiry();
@@ -4504,8 +4504,8 @@ function parseConnectTarget(authority) {
4504
4504
  function isInterceptedHost(host, interceptHosts) {
4505
4505
  return interceptHosts.includes(host);
4506
4506
  }
4507
- function servedByPipeline(path48) {
4508
- return path48?.startsWith(ROUTED_PATH_PREFIX) === true;
4507
+ function servedByPipeline(path49) {
4508
+ return path49?.startsWith(ROUTED_PATH_PREFIX) === true;
4509
4509
  }
4510
4510
  function forwardableHeaders(headers) {
4511
4511
  const connectionTokens = new Set(
@@ -4949,7 +4949,7 @@ var init_package = __esm({
4949
4949
  "package.json"() {
4950
4950
  package_default = {
4951
4951
  name: "agent-shim",
4952
- version: "11.84.0",
4952
+ version: "11.84.1",
4953
4953
  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.",
4954
4954
  license: "MIT",
4955
4955
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -5175,43 +5175,43 @@ function parseJson(raw, schema) {
5175
5175
  const parsed = schema.safeParse(JSON.parse(raw));
5176
5176
  return parsed.success ? parsed.data : void 0;
5177
5177
  }
5178
- function readHeadroomState(fs15, stateFile) {
5178
+ function readHeadroomState(fs16, stateFile) {
5179
5179
  try {
5180
- return parseJson(fs15.readFileUtf8(stateFile), HeadroomStateSchema);
5180
+ return parseJson(fs16.readFileUtf8(stateFile), HeadroomStateSchema);
5181
5181
  } catch {
5182
5182
  return void 0;
5183
5183
  }
5184
5184
  }
5185
- function writeHeadroomState(fs15, stateFile, state) {
5186
- fs15.mkdirp(path14.dirname(stateFile));
5187
- fs15.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
5185
+ function writeHeadroomState(fs16, stateFile, state) {
5186
+ fs16.mkdirp(path14.dirname(stateFile));
5187
+ fs16.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
5188
5188
  `);
5189
5189
  }
5190
- function resolveServingHeadroomState(fs15, files, isRunning) {
5191
- const current = readHeadroomState(fs15, files.stateFile);
5190
+ function resolveServingHeadroomState(fs16, files, isRunning) {
5191
+ const current = readHeadroomState(fs16, files.stateFile);
5192
5192
  if (current !== void 0) {
5193
5193
  return { path: files.stateFile, state: current };
5194
5194
  }
5195
- const legacy = readHeadroomState(fs15, files.legacyStateFile);
5195
+ const legacy = readHeadroomState(fs16, files.legacyStateFile);
5196
5196
  if (legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid)) {
5197
5197
  return { path: files.legacyStateFile, state: legacy };
5198
5198
  }
5199
5199
  return void 0;
5200
5200
  }
5201
- function migrateHeadroomState(fs15, files, isRunning) {
5202
- const legacy = readHeadroomState(fs15, files.legacyStateFile);
5201
+ function migrateHeadroomState(fs16, files, isRunning) {
5202
+ const legacy = readHeadroomState(fs16, files.legacyStateFile);
5203
5203
  const legacyLive = legacy?.supervisorPid !== void 0 && isRunning(legacy.supervisorPid);
5204
- const current = readHeadroomState(fs15, files.stateFile);
5204
+ const current = readHeadroomState(fs16, files.stateFile);
5205
5205
  if (current !== void 0 || legacyLive) {
5206
- if (!legacyLive && fs15.readFileUtf8(files.legacyStateFile) !== void 0) {
5207
- fs15.removeRecursive(files.legacyStateFile);
5206
+ if (!legacyLive && fs16.readFileUtf8(files.legacyStateFile) !== void 0) {
5207
+ fs16.removeRecursive(files.legacyStateFile);
5208
5208
  }
5209
5209
  return;
5210
5210
  }
5211
5211
  if (legacy !== void 0) {
5212
- writeHeadroomState(fs15, files.stateFile, legacy);
5212
+ writeHeadroomState(fs16, files.stateFile, legacy);
5213
5213
  }
5214
- fs15.removeRecursive(files.legacyStateFile);
5214
+ fs16.removeRecursive(files.legacyStateFile);
5215
5215
  }
5216
5216
  function hashAllowlist(allowlist) {
5217
5217
  return createHash3("sha256").update(allowlist.join("\n")).digest("hex");
@@ -5244,27 +5244,27 @@ function isAdmissibleUrl(entry) {
5244
5244
  function parseAllowlistFile(content) {
5245
5245
  return content.replace(/^\uFEFF/, "").replace(ALLOWLIST_FILE_COMMENT, "").split(ALLOWLIST_FILE_SEPARATORS).map((entry) => entry.replace(ALLOWLIST_SURROUNDING_WHITESPACE, "")).filter((entry) => entry !== "" && !ALLOWLIST_ENTRY_WHITESPACE.test(entry) && (entry.includes("://") ? isAdmissibleUrl(entry) : isBareHost(entry)));
5246
5246
  }
5247
- function writeAllowlistFile(fs15, allowlistFile, allowlist) {
5248
- fs15.mkdirPrivate(path14.dirname(allowlistFile));
5249
- fs15.writeFilePrivate(allowlistFile, formatAllowlistFile(allowlist));
5247
+ function writeAllowlistFile(fs16, allowlistFile, allowlist) {
5248
+ fs16.mkdirPrivate(path14.dirname(allowlistFile));
5249
+ fs16.writeFilePrivate(allowlistFile, formatAllowlistFile(allowlist));
5250
5250
  }
5251
- function pruneStaleAllowlistTemporaries(fs15, allowlistFile, isRunning) {
5251
+ function pruneStaleAllowlistTemporaries(fs16, allowlistFile, isRunning) {
5252
5252
  const prefix = `${path14.basename(allowlistFile)}.`;
5253
- for (const name of fs15.readdir(path14.dirname(allowlistFile))) {
5253
+ for (const name of fs16.readdir(path14.dirname(allowlistFile))) {
5254
5254
  const writer = name.startsWith(prefix) ? /^([1-9]\d*)\.tmp$/.exec(name.slice(prefix.length))?.[1] : void 0;
5255
5255
  if (writer !== void 0 && !isRunning(Number(writer))) {
5256
- fs15.removeRecursive(path14.join(path14.dirname(allowlistFile), name));
5256
+ fs16.removeRecursive(path14.join(path14.dirname(allowlistFile), name));
5257
5257
  }
5258
5258
  }
5259
5259
  }
5260
- function readAllProviders(fs15, providersDir) {
5260
+ function readAllProviders(fs16, providersDir) {
5261
5261
  const result = [];
5262
- for (const name of fs15.readdir(providersDir)) {
5262
+ for (const name of fs16.readdir(providersDir)) {
5263
5263
  if (!name.endsWith(".json")) {
5264
5264
  continue;
5265
5265
  }
5266
5266
  try {
5267
- const parsed = parseJson(fs15.readFileUtf8(path14.join(providersDir, name)), ProviderSchema);
5267
+ const parsed = parseJson(fs16.readFileUtf8(path14.join(providersDir, name)), ProviderSchema);
5268
5268
  if (parsed !== void 0) {
5269
5269
  result.push({ name: name.slice(0, -".json".length), provider: parsed });
5270
5270
  }
@@ -5274,22 +5274,22 @@ function readAllProviders(fs15, providersDir) {
5274
5274
  }
5275
5275
  return result;
5276
5276
  }
5277
- function writeSession(fs15, sessionsDir, session) {
5278
- fs15.mkdirp(sessionsDir);
5279
- fs15.writeFileUtf8(path14.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
5277
+ function writeSession(fs16, sessionsDir, session) {
5278
+ fs16.mkdirp(sessionsDir);
5279
+ fs16.writeFileUtf8(path14.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
5280
5280
  `);
5281
5281
  }
5282
- function removeSession(fs15, sessionsDir, pid) {
5283
- fs15.removeRecursive(path14.join(sessionsDir, `${String(pid)}.json`));
5282
+ function removeSession(fs16, sessionsDir, pid) {
5283
+ fs16.removeRecursive(path14.join(sessionsDir, `${String(pid)}.json`));
5284
5284
  }
5285
- function listSessions(fs15, sessionsDir) {
5285
+ function listSessions(fs16, sessionsDir) {
5286
5286
  const sessions = [];
5287
- for (const name of fs15.readdir(sessionsDir)) {
5287
+ for (const name of fs16.readdir(sessionsDir)) {
5288
5288
  if (!name.endsWith(".json")) {
5289
5289
  continue;
5290
5290
  }
5291
5291
  try {
5292
- const parsed = parseJson(fs15.readFileUtf8(path14.join(sessionsDir, name)), HeadroomSessionSchema);
5292
+ const parsed = parseJson(fs16.readFileUtf8(path14.join(sessionsDir, name)), HeadroomSessionSchema);
5293
5293
  if (parsed !== void 0) {
5294
5294
  sessions.push(parsed);
5295
5295
  }
@@ -5299,22 +5299,22 @@ function listSessions(fs15, sessionsDir) {
5299
5299
  }
5300
5300
  return sessions.sort((a, b) => a.pid - b.pid);
5301
5301
  }
5302
- function sessionsForSupervisor(fs15, sessionsDir, supervisorPid) {
5303
- return listSessions(fs15, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
5302
+ function sessionsForSupervisor(fs16, sessionsDir, supervisorPid) {
5303
+ return listSessions(fs16, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
5304
5304
  }
5305
- function pruneDeadSessions(fs15, sessionsDir, isRunning) {
5305
+ function pruneDeadSessions(fs16, sessionsDir, isRunning) {
5306
5306
  const removed = [];
5307
- for (const session of listSessions(fs15, sessionsDir)) {
5307
+ for (const session of listSessions(fs16, sessionsDir)) {
5308
5308
  if (!isRunning(session.pid)) {
5309
- removeSession(fs15, sessionsDir, session.pid);
5309
+ removeSession(fs16, sessionsDir, session.pid);
5310
5310
  removed.push(session.pid);
5311
5311
  }
5312
5312
  }
5313
5313
  return removed;
5314
5314
  }
5315
- function readStartLock(fs15, lockFile) {
5315
+ function readStartLock(fs16, lockFile) {
5316
5316
  try {
5317
- return parseJson(fs15.readFileUtf8(lockFile), HeadroomLockSchema);
5317
+ return parseJson(fs16.readFileUtf8(lockFile), HeadroomLockSchema);
5318
5318
  } catch {
5319
5319
  return void 0;
5320
5320
  }
@@ -5404,12 +5404,12 @@ function earlierReleaseAllowlistHash(providers, doorOrigin) {
5404
5404
  }
5405
5405
  return hashAllowlist([...entries].sort());
5406
5406
  }
5407
- function earlierReleaseDaemon(fs15, paths, daemon) {
5407
+ function earlierReleaseDaemon(fs16, paths, daemon) {
5408
5408
  if (daemonIdentity(daemon.commandLine, daemon.socketPath) !== "earlier-release") {
5409
5409
  return void 0;
5410
5410
  }
5411
- const providers = readAllProviders(fs15, paths.providersDir).map((entry) => entry.provider);
5412
- const expected = earlierReleaseAllowlistHash(providers, frontDoorOrigin(readFrontDoorState(fs15, paths.frontdoorStateFile)));
5411
+ const providers = readAllProviders(fs16, paths.providersDir).map((entry) => entry.provider);
5412
+ const expected = earlierReleaseAllowlistHash(providers, frontDoorOrigin(readFrontDoorState(fs16, paths.frontdoorStateFile)));
5413
5413
  return { admitsServingDoor: daemon.recordedHash === expected };
5414
5414
  }
5415
5415
  var EARLIER_RELEASE_ALLOWLIST, EARLIER_RELEASE_ANTHROPIC_UPSTREAM;
@@ -5434,8 +5434,8 @@ function awaitingCause(daemonPid, identity, allowlistFile) {
5434
5434
  }
5435
5435
  return `the headroom supervisor has not written an allowlist admitting this launch's upstreams to ${allowlistFile} within ${String(HEADROOM_START_TIMEOUT_MS)}ms`;
5436
5436
  }
5437
- function daemonAdmits(fs15, allowlistFile, recordedHash, required) {
5438
- const content = fs15.readFileUtf8(allowlistFile);
5437
+ function daemonAdmits(fs16, allowlistFile, recordedHash, required) {
5438
+ const content = fs16.readFileUtf8(allowlistFile);
5439
5439
  if (content === void 0 || recordedHash === void 0) {
5440
5440
  return false;
5441
5441
  }
@@ -5704,7 +5704,7 @@ function verifyAllowlistFile(allowlistFile, ports) {
5704
5704
  const replaceable = fileStat === void 0 || fileStat.kind === "file" || fileStat.kind === "symlink";
5705
5705
  return { message: refusal2, repairable: replaceable };
5706
5706
  }
5707
- function prepareHeadroomSocket(fs15, ports, paths, supervisorPid) {
5707
+ function prepareHeadroomSocket(fs16, ports, paths, supervisorPid) {
5708
5708
  const unsupported = platformRefusal(ports.platform);
5709
5709
  if (unsupported !== void 0) {
5710
5710
  return { refused: unsupported };
@@ -5719,18 +5719,18 @@ function prepareHeadroomSocket(fs15, ports, paths, supervisorPid) {
5719
5719
  if (ports.lstat(paths.headroomSocketDir)?.kind === "symlink") {
5720
5720
  return { refused: `the headroom socket directory ${paths.headroomSocketDir} is a symlink; it must be the real directory` };
5721
5721
  }
5722
- fs15.mkdirPrivate(paths.headroomSocketDir);
5722
+ fs16.mkdirPrivate(paths.headroomSocketDir);
5723
5723
  const refusal2 = ownerOnlyRefusal("socket directory", paths.headroomSocketDir, ports.lstat(paths.headroomSocketDir), "dir", ports.currentUid());
5724
5724
  return refusal2 === void 0 ? { socketPath } : { refused: refusal2 };
5725
5725
  }
5726
- function pruneStaleHeadroomSockets(fs15, paths, isRunning) {
5726
+ function pruneStaleHeadroomSockets(fs16, paths, isRunning) {
5727
5727
  const removed = [];
5728
- for (const name of fs15.readdir(paths.headroomSocketDir)) {
5728
+ for (const name of fs16.readdir(paths.headroomSocketDir)) {
5729
5729
  const pid = HEADROOM_SOCKET_NAME.exec(name)?.[1];
5730
5730
  if (pid === void 0 || isRunning(Number.parseInt(pid, 10))) {
5731
5731
  continue;
5732
5732
  }
5733
- fs15.removeRecursive(path15.join(paths.headroomSocketDir, name));
5733
+ fs16.removeRecursive(path15.join(paths.headroomSocketDir, name));
5734
5734
  removed.push(name);
5735
5735
  }
5736
5736
  return removed;
@@ -5842,37 +5842,37 @@ function compareVersions2(a, b) {
5842
5842
  return 0;
5843
5843
  }
5844
5844
  async function runSupervisor(initialConfig, ports, options = {}) {
5845
- const { fs: fs15, paths } = ports;
5845
+ const { fs: fs16, paths } = ports;
5846
5846
  let config = initialConfig;
5847
- migrateHeadroomState(fs15, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
5848
- const previousState = resolveServingHeadroomState(fs15, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
5847
+ migrateHeadroomState(fs16, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning);
5848
+ const previousState = resolveServingHeadroomState(fs16, { stateFile: paths.headroomStateFile, legacyStateFile: paths.headroomLegacyStateFile }, ports.isRunning)?.state;
5849
5849
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
5850
5850
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
5851
5851
  return 0;
5852
5852
  }
5853
5853
  let installedSource = previousState?.installedSource;
5854
5854
  const ownsState = () => {
5855
- const owner = readHeadroomState(fs15, paths.headroomStateFile)?.supervisorPid;
5855
+ const owner = readHeadroomState(fs16, paths.headroomStateFile)?.supervisorPid;
5856
5856
  return owner === void 0 || owner === ports.ownPid || !ports.isRunning(owner);
5857
5857
  };
5858
5858
  const writeOwnState = (state) => {
5859
5859
  if (!ownsState()) {
5860
5860
  return false;
5861
5861
  }
5862
- writeHeadroomState(fs15, paths.headroomStateFile, state);
5862
+ writeHeadroomState(fs16, paths.headroomStateFile, state);
5863
5863
  return true;
5864
5864
  };
5865
5865
  const fail = (message) => {
5866
5866
  if (writeOwnState({ lastError: message })) {
5867
- fs15.removeRecursive(paths.headroomLockFile);
5867
+ fs16.removeRecursive(paths.headroomLockFile);
5868
5868
  }
5869
5869
  ports.log(`agent-shim headroom supervisor: ${message}`);
5870
5870
  return 1;
5871
5871
  };
5872
5872
  const syncAllowlistFile = (allowlist) => {
5873
5873
  try {
5874
- if (fs15.readFileUtf8(paths.headroomAllowlistFile) !== formatAllowlistFile(allowlist)) {
5875
- writeAllowlistFile(fs15, paths.headroomAllowlistFile, allowlist);
5874
+ if (fs16.readFileUtf8(paths.headroomAllowlistFile) !== formatAllowlistFile(allowlist)) {
5875
+ writeAllowlistFile(fs16, paths.headroomAllowlistFile, allowlist);
5876
5876
  ports.log(`agent-shim headroom supervisor: wrote allowlist [${allowlist.join(", ")}] to ${paths.headroomAllowlistFile}`);
5877
5877
  }
5878
5878
  return void 0;
@@ -5890,9 +5890,9 @@ async function runSupervisor(initialConfig, ports, options = {}) {
5890
5890
  }
5891
5891
  ports.log(`agent-shim headroom supervisor: repairing the allowlist file: ${problem.message}`);
5892
5892
  try {
5893
- fs15.mkdirPrivate(paths.headroomDir);
5894
- fs15.mkdirPrivate(path16.dirname(paths.headroomAllowlistFile));
5895
- writeAllowlistFile(fs15, paths.headroomAllowlistFile, allowlist);
5893
+ fs16.mkdirPrivate(paths.headroomDir);
5894
+ fs16.mkdirPrivate(path16.dirname(paths.headroomAllowlistFile));
5895
+ writeAllowlistFile(fs16, paths.headroomAllowlistFile, allowlist);
5896
5896
  } catch (error) {
5897
5897
  return `could not write the headroom allowlist file ${paths.headroomAllowlistFile}: ${error instanceof Error ? error.message : String(error)}`;
5898
5898
  }
@@ -5917,20 +5917,20 @@ async function runSupervisor(initialConfig, ports, options = {}) {
5917
5917
  installedSource = config.source;
5918
5918
  return void 0;
5919
5919
  };
5920
- const socket = prepareHeadroomSocket(fs15, ports.socketTrust, paths, ports.ownPid);
5920
+ const socket = prepareHeadroomSocket(fs16, ports.socketTrust, paths, ports.ownPid);
5921
5921
  if (socket.refused !== void 0) {
5922
5922
  return fail(socket.refused);
5923
5923
  }
5924
5924
  const { socketPath } = socket;
5925
- pruneStaleHeadroomSockets(fs15, paths, ports.isRunning);
5926
- pruneStaleAllowlistTemporaries(fs15, paths.headroomAllowlistFile, ports.isRunning);
5925
+ pruneStaleHeadroomSockets(fs16, paths, ports.isRunning);
5926
+ pruneStaleAllowlistTemporaries(fs16, paths.headroomAllowlistFile, ports.isRunning);
5927
5927
  const installFailure = ensureInstalled();
5928
5928
  if (installFailure !== void 0) {
5929
5929
  return fail(installFailure);
5930
5930
  }
5931
5931
  const version = ports.headroomVersion() ?? "unknown";
5932
5932
  writeOwnState({ supervisorPid: ports.ownPid, version, installedSource });
5933
- ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: managing headroom on allowlist [${currentHeadroomAllowlistInputs(fs15, paths, ports.frontDoorLiveness).frontDoorOrigins.join(", ")}]`);
5933
+ ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: managing headroom on allowlist [${currentHeadroomAllowlistInputs(fs16, paths, ports.frontDoorLiveness).frontDoorOrigins.join(", ")}]`);
5934
5934
  const orphanPid = previousState?.headroomPid;
5935
5935
  const orphanSocket = previousState?.socketPath ?? (previousState?.supervisorPid === void 0 ? void 0 : headroomSocketPath(paths, previousState.supervisorPid));
5936
5936
  const orphanIdentity = orphanPid === void 0 || orphanSocket === void 0 || !ports.isRunning(orphanPid) ? void 0 : daemonIdentity(ports.daemonCommandLine(orphanPid), orphanSocket);
@@ -5968,12 +5968,12 @@ async function runSupervisor(initialConfig, ports, options = {}) {
5968
5968
  }
5969
5969
  config = ports.readConfig();
5970
5970
  const settingsHash = hashSettings(config.settings);
5971
- const inputs = currentHeadroomAllowlistInputs(fs15, paths, ports.frontDoorLiveness);
5972
- pruneDeadFrontDoorDirectRecords(fs15, paths.frontdoorDirectRecordsDir, inputs.frontDoorRecords, inputs.frontDoorLiveness);
5973
- pruneMalformedFrontDoorDirectFiles(fs15, paths.frontdoorDirectRecordsDir, ports.isRunning);
5971
+ const inputs = currentHeadroomAllowlistInputs(fs16, paths, ports.frontDoorLiveness);
5972
+ pruneDeadFrontDoorDirectRecords(fs16, paths.frontdoorDirectRecordsDir, inputs.frontDoorRecords, inputs.frontDoorLiveness);
5973
+ pruneMalformedFrontDoorDirectFiles(fs16, paths.frontdoorDirectRecordsDir, ports.isRunning);
5974
5974
  const allowlist = inputs.frontDoorOrigins;
5975
5975
  const allowlistHash = hashAllowlist(allowlist);
5976
- pruneDeadSessions(fs15, paths.headroomSessionsDir, ports.isRunning);
5976
+ pruneDeadSessions(fs16, paths.headroomSessionsDir, ports.isRunning);
5977
5977
  const ownsNow = ownsState();
5978
5978
  if (!ownsNow && !superseded) {
5979
5979
  ports.log("agent-shim headroom supervisor: another supervisor now owns the state file; serving this daemon's own sessions until they end");
@@ -6020,7 +6020,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
6020
6020
  runningSettingsHash = settingsHash;
6021
6021
  const recorded = writeOwnState(servingState(pid));
6022
6022
  if (recorded) {
6023
- fs15.removeRecursive(paths.headroomLockFile);
6023
+ fs16.removeRecursive(paths.headroomLockFile);
6024
6024
  }
6025
6025
  idleSince = void 0;
6026
6026
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(pid)} ready on unix socket ${socketPath}`);
@@ -6048,7 +6048,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
6048
6048
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(headroomPid)} now serves allowlist [${allowlist.join(", ")}]`);
6049
6049
  }
6050
6050
  if (runningSettingsHash !== settingsHash || installedSource !== config.source) {
6051
- if (sessionsForSupervisor(fs15, paths.headroomSessionsDir, ports.ownPid).length === 0) {
6051
+ if (sessionsForSupervisor(fs16, paths.headroomSessionsDir, ports.ownPid).length === 0) {
6052
6052
  ports.log("agent-shim headroom supervisor: configuration drifted and no sessions are live; restarting headroom");
6053
6053
  ports.stopProcess(headroomPid);
6054
6054
  headroomPid = void 0;
@@ -6057,7 +6057,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
6057
6057
  continue;
6058
6058
  }
6059
6059
  }
6060
- const sessions = sessionsForSupervisor(fs15, paths.headroomSessionsDir, ports.ownPid);
6060
+ const sessions = sessionsForSupervisor(fs16, paths.headroomSessionsDir, ports.ownPid);
6061
6061
  if (sessions.length === 0) {
6062
6062
  idleSince ??= ports.now();
6063
6063
  const idleMs = ports.now() - idleSince;
@@ -6082,9 +6082,9 @@ function undeterminedFrontDoors(inputs) {
6082
6082
  return reason === void 0 ? [] : [{ pid: record.pid, origin: directOrigin(record.directPort), reason }];
6083
6083
  });
6084
6084
  }
6085
- function currentHeadroomAllowlistInputs(fs15, paths, frontDoorLiveness) {
6086
- const named = frontDoorOrigin(readFrontDoorState(fs15, paths.frontdoorStateFile));
6087
- const records = listFrontDoorDirectRecords(fs15, paths.frontdoorDirectRecordsDir);
6085
+ function currentHeadroomAllowlistInputs(fs16, paths, frontDoorLiveness) {
6086
+ const named = frontDoorOrigin(readFrontDoorState(fs16, paths.frontdoorStateFile));
6087
+ const records = listFrontDoorDirectRecords(fs16, paths.frontdoorDirectRecordsDir);
6088
6088
  const liveness = frontDoorLiveness(records.map((record) => record.pid));
6089
6089
  const live = liveFrontDoorDirectRecords(records, liveness).map((record) => directOrigin(record.directPort));
6090
6090
  return {
@@ -6093,8 +6093,8 @@ function currentHeadroomAllowlistInputs(fs15, paths, frontDoorLiveness) {
6093
6093
  frontDoorOrigins: [.../* @__PURE__ */ new Set([...named === void 0 ? [] : [named], ...live])].sort()
6094
6094
  };
6095
6095
  }
6096
- function launchRequiredUpstreams(fs15, paths) {
6097
- const door = frontDoorOrigin(readFrontDoorState(fs15, paths.frontdoorStateFile));
6096
+ function launchRequiredUpstreams(fs16, paths) {
6097
+ const door = frontDoorOrigin(readFrontDoorState(fs16, paths.frontdoorStateFile));
6098
6098
  return door === void 0 ? [] : [door];
6099
6099
  }
6100
6100
  async function waitUntilReady(ports, socketPath, pid) {
@@ -6884,8 +6884,8 @@ import path20 from "node:path";
6884
6884
  function poolNameOf(selector) {
6885
6885
  return selector.startsWith(POOL_SELECTOR_PREFIX) ? selector.slice(POOL_SELECTOR_PREFIX.length) : void 0;
6886
6886
  }
6887
- function readActiveIdentity(fs15, activeIdentityFile) {
6888
- const trimmed = fs15.readFileUtf8(activeIdentityFile)?.trim();
6887
+ function readActiveIdentity(fs16, activeIdentityFile) {
6888
+ const trimmed = fs16.readFileUtf8(activeIdentityFile)?.trim();
6889
6889
  return trimmed === void 0 || trimmed === "" ? void 0 : trimmed;
6890
6890
  }
6891
6891
  function isNonEmpty(value) {
@@ -6935,11 +6935,11 @@ function decideConfigProfile(params) {
6935
6935
  }
6936
6936
  return { source: "none" };
6937
6937
  }
6938
- function loadIdentity(identitiesDir, name, fs15) {
6938
+ function loadIdentity(identitiesDir, name, fs16) {
6939
6939
  if (!isFileName(name)) {
6940
6940
  throw new UnsafeNameError(name, "identity", FILE_NAME_RULE);
6941
6941
  }
6942
- return loadConfigFile(path20.join(identitiesDir, name, "identity.json"), IdentitySchema, fs15.readConfigFile);
6942
+ return loadConfigFile(path20.join(identitiesDir, name, "identity.json"), IdentitySchema, fs16.readConfigFile);
6943
6943
  }
6944
6944
  var IDENTITY_DECISION_SOURCES, IDENTITY_SOURCE_LABELS, CONFIG_PROFILE_DECISION_SOURCES;
6945
6945
  var init_identity = __esm({
@@ -7193,14 +7193,14 @@ function isIdentityName(name) {
7193
7193
  function claudeJsonPath(identitiesDir, identity) {
7194
7194
  return path21.join(identitiesDir, identity, CLAUDE_JSON);
7195
7195
  }
7196
- function readAccountMetadata(fs15, identitiesDir, identity) {
7196
+ function readAccountMetadata(fs16, identitiesDir, identity) {
7197
7197
  if (!isIdentityName(identity)) {
7198
7198
  throw new Error(`"${identity}" is not a valid identity name.`);
7199
7199
  }
7200
- return readAccountMetadataFile(fs15, claudeJsonPath(identitiesDir, identity));
7200
+ return readAccountMetadataFile(fs16, claudeJsonPath(identitiesDir, identity));
7201
7201
  }
7202
- function readAccountMetadataFile(fs15, file) {
7203
- const raw = fs15.readFileUtf8(file);
7202
+ function readAccountMetadataFile(fs16, file) {
7203
+ const raw = fs16.readFileUtf8(file);
7204
7204
  if (raw === void 0) {
7205
7205
  return void 0;
7206
7206
  }
@@ -7230,19 +7230,19 @@ function readAccountMetadataFile(fs15, file) {
7230
7230
  }
7231
7231
  return account.data;
7232
7232
  }
7233
- function createAccountReader(fs15, identitiesDir) {
7233
+ function createAccountReader(fs16, identitiesDir) {
7234
7234
  const cache = /* @__PURE__ */ new Map();
7235
7235
  return (identity) => {
7236
7236
  if (!isIdentityName(identity)) {
7237
7237
  throw new Error(`"${identity}" is not a valid identity name.`);
7238
7238
  }
7239
- const stat = fs15.lstat(claudeJsonPath(identitiesDir, identity));
7239
+ const stat = fs16.lstat(claudeJsonPath(identitiesDir, identity));
7240
7240
  const stamp = stat === void 0 ? "absent" : `${String(stat.mtimeMs)}:${String(stat.sizeBytes)}`;
7241
7241
  const cached = cache.get(identity);
7242
7242
  if (cached?.stamp === stamp) {
7243
7243
  return cached.account;
7244
7244
  }
7245
- const account = readAccountMetadata(fs15, identitiesDir, identity);
7245
+ const account = readAccountMetadata(fs16, identitiesDir, identity);
7246
7246
  cache.set(identity, { stamp, account });
7247
7247
  return account;
7248
7248
  };
@@ -7278,9 +7278,9 @@ var init_accountDescription = __esm({
7278
7278
  });
7279
7279
 
7280
7280
  // src/identityAccounts.ts
7281
- function readIdentityAccount(fs15, identitiesDir, identity) {
7281
+ function readIdentityAccount(fs16, identitiesDir, identity) {
7282
7282
  try {
7283
- const account = readAccountMetadata(fs15, identitiesDir, identity);
7283
+ const account = readAccountMetadata(fs16, identitiesDir, identity);
7284
7284
  return account === void 0 ? void 0 : { account };
7285
7285
  } catch (error) {
7286
7286
  if (error instanceof AccountMetadataError) {
@@ -7919,8 +7919,8 @@ function segmentDay(epochMs) {
7919
7919
  function segmentName(day, pid) {
7920
7920
  return `${day}.${String(pid)}.jsonl`;
7921
7921
  }
7922
- function listLogSegments(fs15, logDir) {
7923
- return fs15.readdir(logDir).flatMap((name) => {
7922
+ function listLogSegments(fs16, logDir) {
7923
+ return fs16.readdir(logDir).flatMap((name) => {
7924
7924
  const match = SEGMENT_RE.exec(name);
7925
7925
  const day = match?.[1];
7926
7926
  if (day === void 0) {
@@ -7929,15 +7929,15 @@ function listLogSegments(fs15, logDir) {
7929
7929
  return [{ name, day, endsAt: Date.parse(`${day}T00:00:00.000Z`) + DAY_MS }];
7930
7930
  }).sort((left, right) => left.day.localeCompare(right.day) || left.name.localeCompare(right.name));
7931
7931
  }
7932
- function readUsageLog(fs15, logDir, options = {}) {
7932
+ function readUsageLog(fs16, logDir, options = {}) {
7933
7933
  const { sinceMs } = options;
7934
7934
  const records = [];
7935
7935
  let invalidLines = 0;
7936
- for (const segment of listLogSegments(fs15, logDir)) {
7936
+ for (const segment of listLogSegments(fs16, logDir)) {
7937
7937
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
7938
7938
  continue;
7939
7939
  }
7940
- const read = readSegment(fs15, logDir, segment);
7940
+ const read = readSegment(fs16, logDir, segment);
7941
7941
  if (read === void 0) {
7942
7942
  continue;
7943
7943
  }
@@ -7951,8 +7951,8 @@ function readUsageLog(fs15, logDir, options = {}) {
7951
7951
  records.sort((left, right) => left.at.localeCompare(right.at));
7952
7952
  return { records, invalidLines };
7953
7953
  }
7954
- function readSegment(fs15, logDir, segment) {
7955
- const contents = fs15.readFileUtf8(path22.join(logDir, segment.name));
7954
+ function readSegment(fs16, logDir, segment) {
7955
+ const contents = fs16.readFileUtf8(path22.join(logDir, segment.name));
7956
7956
  if (contents === void 0) {
7957
7957
  return void 0;
7958
7958
  }
@@ -7986,9 +7986,9 @@ function snapshotPath(snapshotsDir, identity) {
7986
7986
  }
7987
7987
  return path22.join(snapshotsDir, `${identity}.json`);
7988
7988
  }
7989
- function readUsageSnapshot(fs15, snapshotsDir, identity) {
7989
+ function readUsageSnapshot(fs16, snapshotsDir, identity) {
7990
7990
  const file = snapshotPath(snapshotsDir, identity);
7991
- const raw = fs15.readFileUtf8(file);
7991
+ const raw = fs16.readFileUtf8(file);
7992
7992
  if (raw === void 0) {
7993
7993
  return void 0;
7994
7994
  }
@@ -8004,8 +8004,8 @@ function readUsageSnapshot(fs15, snapshotsDir, identity) {
8004
8004
  }
8005
8005
  return snapshot.data;
8006
8006
  }
8007
- function listUsageSnapshots(fs15, snapshotsDir) {
8008
- return fs15.readdir(snapshotsDir).flatMap((name) => {
8007
+ function listUsageSnapshots(fs16, snapshotsDir) {
8008
+ return fs16.readdir(snapshotsDir).flatMap((name) => {
8009
8009
  if (!name.endsWith(".json")) {
8010
8010
  return [];
8011
8011
  }
@@ -8013,7 +8013,7 @@ function listUsageSnapshots(fs15, snapshotsDir) {
8013
8013
  if (!isIdentityName(identity)) {
8014
8014
  return [];
8015
8015
  }
8016
- const snapshot = readUsageSnapshot(fs15, snapshotsDir, identity);
8016
+ const snapshot = readUsageSnapshot(fs16, snapshotsDir, identity);
8017
8017
  return snapshot === void 0 ? [] : [snapshot];
8018
8018
  }).sort((left, right) => left.identity.localeCompare(right.identity));
8019
8019
  }
@@ -8038,11 +8038,11 @@ var init_read = __esm({
8038
8038
 
8039
8039
  // src/usage/store.ts
8040
8040
  import path23 from "node:path";
8041
- function pruneUsageLog(fs15, logDir, nowMs) {
8041
+ function pruneUsageLog(fs16, logDir, nowMs) {
8042
8042
  const cutoff = nowMs - USAGE_RETENTION_MS;
8043
- for (const segment of listLogSegments(fs15, logDir)) {
8043
+ for (const segment of listLogSegments(fs16, logDir)) {
8044
8044
  if (segment.endsAt <= cutoff) {
8045
- fs15.removeRecursive(path23.join(logDir, segment.name));
8045
+ fs16.removeRecursive(path23.join(logDir, segment.name));
8046
8046
  }
8047
8047
  }
8048
8048
  }
@@ -8071,7 +8071,7 @@ function foldProviderState(current, record) {
8071
8071
  };
8072
8072
  }
8073
8073
  function createUsageStore(deps) {
8074
- const { fs: fs15, paths } = deps;
8074
+ const { fs: fs16, paths } = deps;
8075
8075
  let prunedDay;
8076
8076
  const rewriteSnapshot = (identity, fold) => {
8077
8077
  if (!isIdentityName(identity)) {
@@ -8080,7 +8080,7 @@ function createUsageStore(deps) {
8080
8080
  }
8081
8081
  let current;
8082
8082
  try {
8083
- current = readUsageSnapshot(fs15, paths.usageSnapshotsDir, identity);
8083
+ current = readUsageSnapshot(fs16, paths.usageSnapshotsDir, identity);
8084
8084
  } catch (error) {
8085
8085
  if (!(error instanceof UsageSnapshotError)) {
8086
8086
  throw error;
@@ -8107,8 +8107,8 @@ function createUsageStore(deps) {
8107
8107
  ...account === void 0 ? {} : { account },
8108
8108
  providers
8109
8109
  });
8110
- fs15.mkdirPrivate(paths.usageSnapshotsDir);
8111
- fs15.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
8110
+ fs16.mkdirPrivate(paths.usageSnapshotsDir);
8111
+ fs16.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
8112
8112
  `);
8113
8113
  deps.publish?.(snapshot);
8114
8114
  return true;
@@ -8117,14 +8117,14 @@ function createUsageStore(deps) {
8117
8117
  record: (input) => {
8118
8118
  const record = UsageRecordSchema.parse(input);
8119
8119
  const nowMs = deps.now();
8120
- fs15.mkdirPrivate(paths.usageDir);
8121
- fs15.mkdirPrivate(paths.usageLogDir);
8120
+ fs16.mkdirPrivate(paths.usageDir);
8121
+ fs16.mkdirPrivate(paths.usageLogDir);
8122
8122
  const day = segmentDay(nowMs);
8123
8123
  if (prunedDay !== day) {
8124
- pruneUsageLog(fs15, paths.usageLogDir, nowMs);
8124
+ pruneUsageLog(fs16, paths.usageLogDir, nowMs);
8125
8125
  prunedDay = day;
8126
8126
  }
8127
- fs15.appendFilePrivate(path23.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record)}
8127
+ fs16.appendFilePrivate(path23.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record)}
8128
8128
  `);
8129
8129
  deps.onRecord?.(record);
8130
8130
  if (record.identity !== void 0) {
@@ -8168,14 +8168,14 @@ import { z as z17 } from "zod";
8168
8168
  function errorMessage(error) {
8169
8169
  return error instanceof Error ? error.message : String(error);
8170
8170
  }
8171
- function loadPoolMembers(fs15, paths, identities, nowMs) {
8171
+ function loadPoolMembers(fs16, paths, identities, nowMs) {
8172
8172
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
8173
- const log = readUsageLog(fs15, paths.usageLogDir, { sinceMs: windowStartMs });
8173
+ const log = readUsageLog(fs16, paths.usageLogDir, { sinceMs: windowStartMs });
8174
8174
  return identities.map((identity) => {
8175
8175
  const records = log.records.filter((record) => record.identity === identity && record.provider === ANTHROPIC_PROVIDER && Date.parse(record.at) >= windowStartMs);
8176
8176
  try {
8177
- const snapshot = readUsageSnapshot(fs15, paths.usageSnapshotsDir, identity);
8178
- const account = readAccountMetadata(fs15, paths.identitiesDir, identity) ?? snapshot?.account;
8177
+ const snapshot = readUsageSnapshot(fs16, paths.usageSnapshotsDir, identity);
8178
+ const account = readAccountMetadata(fs16, paths.identitiesDir, identity) ?? snapshot?.account;
8179
8179
  return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
8180
8180
  } catch (error) {
8181
8181
  if (error instanceof UsageSnapshotError || error instanceof AccountMetadataError) {
@@ -8294,9 +8294,9 @@ function collectPoolIdentities(pools, poolName, stack, found) {
8294
8294
  collectPoolIdentities(pools, nestedName, childStack, found);
8295
8295
  }
8296
8296
  }
8297
- function readPicksFile(fs15, file) {
8297
+ function readPicksFile(fs16, file) {
8298
8298
  const empty = { schemaVersion: SCHEMA_VERSION, picks: {} };
8299
- const raw = fs15.readFileUtf8(file);
8299
+ const raw = fs16.readFileUtf8(file);
8300
8300
  if (raw === void 0) {
8301
8301
  return { file: empty };
8302
8302
  }
@@ -8309,17 +8309,17 @@ function readPicksFile(fs15, file) {
8309
8309
  const result = PicksFileSchema.safeParse(parsed);
8310
8310
  return result.success ? { file: result.data } : { file: empty, problem: `${file} is not a picks file this agent-shim can read` };
8311
8311
  }
8312
- function readStickyPick(fs15, picksFile, directory) {
8313
- const read = readPicksFile(fs15, picksFile);
8312
+ function readStickyPick(fs16, picksFile, directory) {
8313
+ const read = readPicksFile(fs16, picksFile);
8314
8314
  const entry = read.file.picks[directory];
8315
8315
  return { ...entry === void 0 ? {} : { sticky: entry }, ...read.problem === void 0 ? {} : { problem: read.problem } };
8316
8316
  }
8317
- function recordStickyPick(fs15, picksFile, directory, identity, nowMs) {
8318
- const current = readPicksFile(fs15, picksFile).file.picks;
8317
+ function recordStickyPick(fs16, picksFile, directory, identity, nowMs) {
8318
+ const current = readPicksFile(fs16, picksFile).file.picks;
8319
8319
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
8320
8320
  const next = { schemaVersion: SCHEMA_VERSION, picks: { ...Object.fromEntries(kept), [directory]: { identity, at: new Date(nowMs).toISOString() } } };
8321
- fs15.mkdirPrivate(path24.dirname(picksFile));
8322
- fs15.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
8321
+ fs16.mkdirPrivate(path24.dirname(picksFile));
8322
+ fs16.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
8323
8323
  `);
8324
8324
  }
8325
8325
  var PoolGraphError, SCHEMA_VERSION, PickEntrySchema, PicksFileSchema;
@@ -8352,9 +8352,9 @@ var init_poolPick = __esm({
8352
8352
 
8353
8353
  // src/statusline/keys.ts
8354
8354
  import { z as z18 } from "zod";
8355
- function valueAt(source, path48) {
8355
+ function valueAt(source, path49) {
8356
8356
  let current = source;
8357
- for (const part of path48) {
8357
+ for (const part of path49) {
8358
8358
  if (!isPlainObject(current)) {
8359
8359
  return void 0;
8360
8360
  }
@@ -8362,14 +8362,14 @@ function valueAt(source, path48) {
8362
8362
  }
8363
8363
  return current;
8364
8364
  }
8365
- function acceptsNull(path48) {
8366
- const layer = path48.reduceRight((inner, part) => ({ [part]: inner }), null);
8365
+ function acceptsNull(path49) {
8366
+ const layer = path49.reduceRight((inner, part) => ({ [part]: inner }), null);
8367
8367
  return StatuslineSchema.safeParse(layer).success;
8368
8368
  }
8369
- function keyOf(path48, declared) {
8369
+ function keyOf(path49, declared) {
8370
8370
  const optional = declared instanceof z18.ZodOptional;
8371
8371
  const leaf = optional ? declared.unwrap() : declared;
8372
- const common = { path: path48.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path48), optional, unsettable: acceptsNull(path48) };
8372
+ const common = { path: path49.join("."), description: declared.description ?? "", defaultValue: valueAt(STATUSLINE_DEFAULTS, path49), optional, unsettable: acceptsNull(path49) };
8373
8373
  if (leaf instanceof z18.ZodNumber) {
8374
8374
  return { ...common, kind: "integer", choices: [] };
8375
8375
  }
@@ -8394,7 +8394,7 @@ function keyOf(path48, declared) {
8394
8394
  if (leaf instanceof z18.ZodArray && leaf.element instanceof z18.ZodString) {
8395
8395
  return { ...common, kind: "textList", choices: [] };
8396
8396
  }
8397
- throw new TypeError(`statusline setting ${path48.join(".")} has a kind the key listing does not describe`);
8397
+ throw new TypeError(`statusline setting ${path49.join(".")} has a kind the key listing does not describe`);
8398
8398
  }
8399
8399
  function walk(shape, prefix) {
8400
8400
  return Object.entries(shape).flatMap(([name, schema]) => schema instanceof z18.ZodObject ? walk(schema.shape, [...prefix, name]) : [keyOf([...prefix, name], schema)]);
@@ -8410,15 +8410,15 @@ var init_keys = __esm({
8410
8410
  });
8411
8411
 
8412
8412
  // src/statusline/change.ts
8413
- function keyNamed(path48) {
8414
- const found = statuslineKeys().find((key) => key.path === path48);
8413
+ function keyNamed(path49) {
8414
+ const found = statuslineKeys().find((key) => key.path === path49);
8415
8415
  if (found === void 0) {
8416
- throw new UsageError(`"${path48}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
8416
+ throw new UsageError(`"${path49}" is not a statusline setting; \`agent-shim statusline keys\` lists them.`);
8417
8417
  }
8418
8418
  return found;
8419
8419
  }
8420
- function setAt(target, path48, value) {
8421
- const [head, ...rest] = path48;
8420
+ function setAt(target, path49, value) {
8421
+ const [head, ...rest] = path49;
8422
8422
  if (head === void 0) {
8423
8423
  return;
8424
8424
  }
@@ -8431,8 +8431,8 @@ function setAt(target, path48, value) {
8431
8431
  target[head] = next;
8432
8432
  setAt(next, rest, value);
8433
8433
  }
8434
- function removeAt(target, path48) {
8435
- const [head, ...rest] = path48;
8434
+ function removeAt(target, path49) {
8435
+ const [head, ...rest] = path49;
8436
8436
  if (head === void 0) {
8437
8437
  return;
8438
8438
  }
@@ -8450,13 +8450,13 @@ function removeAt(target, path48) {
8450
8450
  }
8451
8451
  function applyStatuslineChange(existing, change) {
8452
8452
  const draft = structuredClone(existing ?? {});
8453
- for (const [path48, value] of Object.entries(change.set ?? {})) {
8454
- keyNamed(path48);
8455
- setAt(draft, path48.split("."), value);
8453
+ for (const [path49, value] of Object.entries(change.set ?? {})) {
8454
+ keyNamed(path49);
8455
+ setAt(draft, path49.split("."), value);
8456
8456
  }
8457
- for (const path48 of change.unset ?? []) {
8458
- keyNamed(path48);
8459
- removeAt(draft, path48.split("."));
8457
+ for (const path49 of change.unset ?? []) {
8458
+ keyNamed(path49);
8459
+ removeAt(draft, path49.split("."));
8460
8460
  }
8461
8461
  const result = StatuslineSchema.safeParse(draft);
8462
8462
  if (!result.success) {
@@ -9835,13 +9835,13 @@ function decideSignIn(facts) {
9835
9835
  function credentialsFilePath(farmRoot) {
9836
9836
  return path27.join(farmRoot, CREDENTIALS_FILE);
9837
9837
  }
9838
- function identitySignIn(fs15, probe, identity) {
9838
+ function identitySignIn(fs16, probe, identity) {
9839
9839
  const probing = !identity.hasCredentialBlock && identity.provider === void 0;
9840
9840
  return decideSignIn({
9841
9841
  hasCredentialBlock: identity.hasCredentialBlock,
9842
9842
  provider: identity.provider,
9843
9843
  keychainItem: probing && probe.platform === "darwin" && probe.run !== void 0 ? keychainHasItem(probe.run, identity.farmRoot) : void 0,
9844
- credentialsFile: probing && fs15.lstat(credentialsFilePath(identity.farmRoot)) !== void 0,
9844
+ credentialsFile: probing && fs16.lstat(credentialsFilePath(identity.farmRoot)) !== void 0,
9845
9845
  platform: probe.platform
9846
9846
  });
9847
9847
  }
@@ -10270,7 +10270,7 @@ var init_modelsStore = __esm({
10270
10270
 
10271
10271
  // src/codex/catalogueCredential.ts
10272
10272
  import { createHash as createHash7 } from "node:crypto";
10273
- import path33 from "node:path";
10273
+ import path34 from "node:path";
10274
10274
  import { z as z30 } from "zod";
10275
10275
  function parseCatalogueBinding(raw) {
10276
10276
  if (raw === void 0) return void 0;
@@ -10304,8 +10304,8 @@ function signInCatalogueFingerprint(raw, filePath) {
10304
10304
  function savedCatalogueFingerprint(provider, paths, env, home, read) {
10305
10305
  if (provider.codex?.login === "chatgpt-sign-in") return signInCatalogueFingerprint(read(paths.chatgptSignInFile), paths.chatgptSignInFile);
10306
10306
  const configuredHome = env.CODEX_HOME;
10307
- const codexHome = configuredHome === void 0 || configuredHome === "" ? path33.join(home, ".codex") : configuredHome;
10308
- return cliCatalogueFingerprint(read(path33.join(codexHome, "auth.json")));
10307
+ const codexHome = configuredHome === void 0 || configuredHome === "" ? path34.join(home, ".codex") : configuredHome;
10308
+ return cliCatalogueFingerprint(read(path34.join(codexHome, "auth.json")));
10309
10309
  }
10310
10310
  var CatalogueBindingSchema;
10311
10311
  var init_catalogueCredential = __esm({
@@ -11412,16 +11412,16 @@ var init_cliOverride = __esm({
11412
11412
  });
11413
11413
 
11414
11414
  // src/launcher/launchRecords.ts
11415
- import path41 from "node:path";
11415
+ import path42 from "node:path";
11416
11416
  import { z as z39 } from "zod";
11417
11417
  function recordFile(directory, pid, identity) {
11418
- return path41.join(directory, `${String(pid)}.${identity}${RECORD_SUFFIX}`);
11418
+ return path42.join(directory, `${String(pid)}.${identity}${RECORD_SUFFIX}`);
11419
11419
  }
11420
- function readRecord(fs15, directory, name) {
11420
+ function readRecord(fs16, directory, name) {
11421
11421
  if (!name.endsWith(RECORD_SUFFIX)) {
11422
11422
  return void 0;
11423
11423
  }
11424
- const raw = fs15.readFileUtf8(path41.join(directory, name));
11424
+ const raw = fs16.readFileUtf8(path42.join(directory, name));
11425
11425
  if (raw === void 0) {
11426
11426
  return void 0;
11427
11427
  }
@@ -11434,20 +11434,20 @@ function readRecord(fs15, directory, name) {
11434
11434
  const result = LaunchRecordSchema.safeParse(parsed);
11435
11435
  return result.success ? result.data : void 0;
11436
11436
  }
11437
- function registerLaunch(fs15, directory, owner, isRunning) {
11438
- fs15.mkdirPrivate(directory);
11439
- for (const name of fs15.readdir(directory)) {
11440
- const record2 = readRecord(fs15, directory, name);
11437
+ function registerLaunch(fs16, directory, owner, isRunning) {
11438
+ fs16.mkdirPrivate(directory);
11439
+ for (const name of fs16.readdir(directory)) {
11440
+ const record2 = readRecord(fs16, directory, name);
11441
11441
  if (record2 !== void 0 && !isRunning(record2.pid)) {
11442
- fs15.removeRecursive(path41.join(directory, name));
11442
+ fs16.removeRecursive(path42.join(directory, name));
11443
11443
  }
11444
11444
  }
11445
11445
  const file = recordFile(directory, owner.pid, owner.identity);
11446
11446
  const record = { pid: owner.pid, identity: owner.identity, startedAt: new Date(owner.startedAtMs).toISOString() };
11447
- fs15.writeFilePrivate(file, `${JSON.stringify(record)}
11447
+ fs16.writeFilePrivate(file, `${JSON.stringify(record)}
11448
11448
  `);
11449
11449
  return () => {
11450
- fs15.removeRecursive(file);
11450
+ fs16.removeRecursive(file);
11451
11451
  };
11452
11452
  }
11453
11453
  var LaunchRecordSchema, RECORD_SUFFIX;
@@ -11532,7 +11532,7 @@ var init_settings2 = __esm({
11532
11532
  });
11533
11533
 
11534
11534
  // src/launcher/flags.ts
11535
- import path42 from "node:path";
11535
+ import path43 from "node:path";
11536
11536
  function resolveLaunchFlags(params) {
11537
11537
  const statusline = resolveStatuslineSettings(params);
11538
11538
  return {
@@ -11588,7 +11588,7 @@ function buildEnv(params) {
11588
11588
  const parentCustomHeaders = params.baseEnv.ANTHROPIC_CUSTOM_HEADERS;
11589
11589
  let providerCustomHeaders;
11590
11590
  if (!params.configDirEscapeHatch && params.resolvedIdentityName !== void 0) {
11591
- env.CLAUDE_CONFIG_DIR = path42.join(params.identitiesDir, params.resolvedIdentityName);
11591
+ env.CLAUDE_CONFIG_DIR = path43.join(params.identitiesDir, params.resolvedIdentityName);
11592
11592
  }
11593
11593
  if (params.provider !== void 0) {
11594
11594
  const providerEnv = params.provider.definition.kind !== void 0 && params.provider.definition.kind !== "http" ? {} : params.provider.definition.env ?? {};
@@ -11680,7 +11680,7 @@ var init_extraFlags = __esm({
11680
11680
  });
11681
11681
 
11682
11682
  // src/usage/resumeContext.ts
11683
- import path43 from "node:path";
11683
+ import path44 from "node:path";
11684
11684
  function projectDirNameOf(cwd) {
11685
11685
  return cwd.replace(/[^A-Za-z0-9]/g, "-");
11686
11686
  }
@@ -11731,15 +11731,15 @@ function contextTokensOfTranscript(text) {
11731
11731
  }
11732
11732
  return void 0;
11733
11733
  }
11734
- function newestTranscript(fs15, projectDir) {
11734
+ function newestTranscript(fs16, projectDir) {
11735
11735
  let newest;
11736
11736
  let newestMs = -Infinity;
11737
- for (const name of fs15.readdir(projectDir)) {
11737
+ for (const name of fs16.readdir(projectDir)) {
11738
11738
  if (!name.endsWith(".jsonl")) {
11739
11739
  continue;
11740
11740
  }
11741
- const candidate = path43.join(projectDir, name);
11742
- const stat = fs15.lstat(candidate);
11741
+ const candidate = path44.join(projectDir, name);
11742
+ const stat = fs16.lstat(candidate);
11743
11743
  if (stat?.kind === "file" && stat.mtimeMs > newestMs) {
11744
11744
  newestMs = stat.mtimeMs;
11745
11745
  newest = candidate;
@@ -11747,14 +11747,14 @@ function newestTranscript(fs15, projectDir) {
11747
11747
  }
11748
11748
  return newest;
11749
11749
  }
11750
- function resumedContextTokens(fs15, params) {
11750
+ function resumedContextTokens(fs16, params) {
11751
11751
  const target = resumeTargetOf(params.passthrough);
11752
11752
  if (target === void 0) {
11753
11753
  return void 0;
11754
11754
  }
11755
- const projectDir = path43.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
11756
- const file = target.kind === "id" ? path43.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs15, projectDir);
11757
- const text = file === void 0 ? void 0 : fs15.readFileUtf8(file);
11755
+ const projectDir = path44.join(params.claudeHome, "projects", projectDirNameOf(params.cwd));
11756
+ const file = target.kind === "id" ? path44.join(projectDir, `${target.id}.jsonl`) : newestTranscript(fs16, projectDir);
11757
+ const text = file === void 0 ? void 0 : fs16.readFileUtf8(file);
11758
11758
  return text === void 0 ? void 0 : contextTokensOfTranscript(text);
11759
11759
  }
11760
11760
  var init_resumeContext = __esm({
@@ -12351,7 +12351,7 @@ var init_launchHook = __esm({
12351
12351
  import { randomUUID as randomUUID4 } from "node:crypto";
12352
12352
  import os9 from "node:os";
12353
12353
  import { isDeepStrictEqual } from "node:util";
12354
- import path44 from "node:path";
12354
+ import path45 from "node:path";
12355
12355
  function resolveIdentityCredential(identity, credential, env, port) {
12356
12356
  if (port === void 0) {
12357
12357
  return { ok: false, status: 1, message: `agent-shim: identity ${identity} needs its credential resolved, but this launcher has no credential port wired` };
@@ -12360,7 +12360,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
12360
12360
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: resolution.message };
12361
12361
  }
12362
12362
  function pickFromPool(decided, params, parsedArgv, readOnly) {
12363
- const { paths, fs: fs15, proc, log } = params;
12363
+ const { paths, fs: fs16, proc, log } = params;
12364
12364
  if (decided.pool === void 0) {
12365
12365
  return { identityDecision: decided };
12366
12366
  }
@@ -12379,7 +12379,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
12379
12379
  selectedVia: decided.source,
12380
12380
  pools: params.pools,
12381
12381
  paths,
12382
- fs: fs15,
12382
+ fs: fs16,
12383
12383
  usageFs: farmRuntime.fs,
12384
12384
  cwd: farmRuntime.cwd,
12385
12385
  now: farmRuntime.now,
@@ -12403,7 +12403,7 @@ function pickFromPool(decided, params, parsedArgv, readOnly) {
12403
12403
  };
12404
12404
  }
12405
12405
  function decideLaunch(params, readOnly) {
12406
- const { paths, fs: fs15, proc, log } = params;
12406
+ const { paths, fs: fs16, proc, log } = params;
12407
12407
  const { env, argv } = proc;
12408
12408
  const parsedArgv = parseLauncherArgv(argv);
12409
12409
  const cliOverride = buildCliOverride({
@@ -12418,7 +12418,7 @@ function decideLaunch(params, readOnly) {
12418
12418
  argv0Identity: params.pickedIdentity ?? parsedArgv.identity,
12419
12419
  directoryPinnedIdentity: params.directoryPinnedIdentity,
12420
12420
  readActiveIdentityFile: () => {
12421
- const raw = fs15.readFileUtf8(paths.activeIdentityFile);
12421
+ const raw = fs16.readFileUtf8(paths.activeIdentityFile);
12422
12422
  if (raw === void 0) {
12423
12423
  return void 0;
12424
12424
  }
@@ -12453,7 +12453,7 @@ function decideLaunch(params, readOnly) {
12453
12453
  }
12454
12454
  let loadedIdentity;
12455
12455
  if (identityDecision.name !== void 0) {
12456
- loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs15);
12456
+ loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs16);
12457
12457
  if (loadedIdentity === void 0) {
12458
12458
  log.error(
12459
12459
  `agent-shim: no identity named "${identityDecision.name}" (selected via ${identityDecision.source}). Run \`agent-shim identity add ${identityDecision.name}\` first.`
@@ -12468,7 +12468,7 @@ function decideLaunch(params, readOnly) {
12468
12468
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
12469
12469
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
12470
12470
  });
12471
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs15.readConfigFile(profileFilePath(paths.configProfilesDir, configProfileDecision.name, `the configuration profile selected via ${configProfileDecision.source}`)) === void 0) {
12471
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs16.readConfigFile(profileFilePath(paths.configProfilesDir, configProfileDecision.name, `the configuration profile selected via ${configProfileDecision.source}`)) === void 0) {
12472
12472
  log.error(
12473
12473
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
12474
12474
  );
@@ -12477,7 +12477,7 @@ function decideLaunch(params, readOnly) {
12477
12477
  const farmContext = farm !== void 0 && farmIdentity !== void 0 ? { farm, identity: farmIdentity, cascade: farm.loadCascade(configProfileDecision.name, cliOverride) } : void 0;
12478
12478
  const providerParams = {
12479
12479
  paths,
12480
- port: fs15,
12480
+ port: fs16,
12481
12481
  ...parsedArgv.provider === void 0 || parsedArgv.provider === false ? {} : { cliProvider: parsedArgv.provider },
12482
12482
  ...farmContext === void 0 ? {} : { cascade: farmContext.cascade },
12483
12483
  ...loadedIdentity?.config.provider === void 0 ? {} : { identityProvider: loadedIdentity.config.provider }
@@ -12598,9 +12598,9 @@ function decideLaunch(params, readOnly) {
12598
12598
  const doorRecord = doorPid === void 0 ? void 0 : readFrontDoorCodexRecord(params.fs, paths.frontdoorDir, doorPid);
12599
12599
  const doorHome = doorRecord?.codexHome;
12600
12600
  const catalogueEnv = doorHome === void 0 ? proc.env : { ...proc.env, CODEX_HOME: doorHome };
12601
- const listedProviders = listProviderNames(fs15.readdir, paths.providersDir).flatMap((name) => {
12601
+ const listedProviders = listProviderNames(fs16.readdir, paths.providersDir).flatMap((name) => {
12602
12602
  try {
12603
- const definition = loadProvider(paths.providersDir, name, fs15);
12603
+ const definition = loadProvider(paths.providersDir, name, fs16);
12604
12604
  if (definition === void 0) return [];
12605
12605
  const catalogueOwner = definition.kind === "codex" ? doorPid : void 0;
12606
12606
  const generation = definition.kind === "codex" ? doorRecord?.generation : void 0;
@@ -12610,8 +12610,8 @@ function decideLaunch(params, readOnly) {
12610
12610
  if (definition.kind === "codex" && readOnly && cache !== void 0) {
12611
12611
  const binding = parseCatalogueBinding(params.fs.readFileUtf8(catalogueBindingPath(paths, name, catalogueOwner, generation)));
12612
12612
  const configuredHome = catalogueEnv.CODEX_HOME;
12613
- const home = configuredHome === void 0 || configuredHome === "" ? path44.join(os9.homedir(), ".codex") : configuredHome;
12614
- const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : path44.resolve(home, "auth.json");
12613
+ const home = configuredHome === void 0 || configuredHome === "" ? path45.join(os9.homedir(), ".codex") : configuredHome;
12614
+ const source = definition.codex?.login === "chatgpt-sign-in" ? paths.chatgptSignInFile : path45.resolve(home, "auth.json");
12615
12615
  const revision = params.fs.fileRevision?.(source);
12616
12616
  if (binding === void 0 || binding.fingerprint !== cache.credentialFingerprint || binding.source !== source || revision === void 0 || revision !== binding.revision) return [];
12617
12617
  }
@@ -12632,7 +12632,7 @@ function decideLaunch(params, readOnly) {
12632
12632
  return { args: args2, pickerSuppressed: startsSession && pickerSettings !== void 0 && callerSettings };
12633
12633
  };
12634
12634
  const args = argsForSupervisor().args;
12635
- const configDir = configDirEscapeHatchApplies || identityDecision.name === void 0 ? env.CLAUDE_CONFIG_DIR : path44.join(paths.identitiesDir, identityDecision.name);
12635
+ const configDir = configDirEscapeHatchApplies || identityDecision.name === void 0 ? env.CLAUDE_CONFIG_DIR : path45.join(paths.identitiesDir, identityDecision.name);
12636
12636
  const decision = {
12637
12637
  identitySource: identityDecision.source,
12638
12638
  configDirEscapeHatch: identityDecision.configDirEscapeHatch,
@@ -12707,7 +12707,7 @@ function prepareRegisteredLaunch(params, onRecorded) {
12707
12707
  let unregisterLaunch;
12708
12708
  const updateCheck = runLaunchUpdateCheck({
12709
12709
  mode: params.updateMode ?? "off",
12710
- checkPath: path44.join(paths.root, "update.check"),
12710
+ checkPath: path45.join(paths.root, "update.check"),
12711
12711
  currentVersion: package_default.version,
12712
12712
  port: params.update
12713
12713
  });
@@ -12918,12 +12918,12 @@ var init_launcher = __esm({
12918
12918
  });
12919
12919
 
12920
12920
  // src/ownCli.ts
12921
- import path45 from "node:path";
12921
+ import path46 from "node:path";
12922
12922
  function agentShimCliPath(distDir = typeof __AGENT_SHIM_DIST_DIR__ === "string" ? __AGENT_SHIM_DIST_DIR__ : void 0) {
12923
12923
  if (distDir === void 0) {
12924
12924
  throw new OwnCliPathUnknownError();
12925
12925
  }
12926
- return path45.join(distDir, OWN_CLI_FILE_NAME);
12926
+ return path46.join(distDir, OWN_CLI_FILE_NAME);
12927
12927
  }
12928
12928
  var OWN_CLI_FILE_NAME, OwnCliPathUnknownError;
12929
12929
  var init_ownCli = __esm({
@@ -12951,10 +12951,10 @@ var init_childRun = __esm({
12951
12951
  });
12952
12952
 
12953
12953
  // src/frontdoor/doorLog.ts
12954
- import fs13 from "node:fs";
12954
+ import fs14 from "node:fs";
12955
12955
  function appendDoorLog(paths, line) {
12956
- fs13.mkdirSync(paths.logsDir, { recursive: true });
12957
- fs13.appendFileSync(paths.frontdoorLogPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
12956
+ fs14.mkdirSync(paths.logsDir, { recursive: true });
12957
+ fs14.appendFileSync(paths.frontdoorLogPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
12958
12958
  `);
12959
12959
  }
12960
12960
  var init_doorLog = __esm({
@@ -12979,16 +12979,16 @@ var init_selfIdentity = __esm({
12979
12979
 
12980
12980
  // src/frontdoor/trust.ts
12981
12981
  import { createHash as createHash8 } from "node:crypto";
12982
- import path46 from "node:path";
12982
+ import path47 from "node:path";
12983
12983
  function resolveTrustBundle(params) {
12984
- const { caCertFile, bundlesDir, variable, inherited, fs: fs15 } = params;
12985
- if (inherited === void 0 || inherited === "" || path46.resolve(inherited) === path46.resolve(caCertFile)) {
12984
+ const { caCertFile, bundlesDir, variable, inherited, fs: fs16 } = params;
12985
+ if (inherited === void 0 || inherited === "" || path47.resolve(inherited) === path47.resolve(caCertFile)) {
12986
12986
  return { path: caCertFile };
12987
12987
  }
12988
- const caPem = fs15.readFileUtf8(caCertFile);
12988
+ const caPem = fs16.readFileUtf8(caCertFile);
12989
12989
  let inheritedPem;
12990
12990
  try {
12991
- inheritedPem = fs15.readFileUtf8(inherited);
12991
+ inheritedPem = fs16.readFileUtf8(inherited);
12992
12992
  } catch (error) {
12993
12993
  return {
12994
12994
  path: caCertFile,
@@ -13000,10 +13000,10 @@ function resolveTrustBundle(params) {
13000
13000
  }
13001
13001
  const combined = `${inheritedPem.trimEnd()}
13002
13002
  ${caPem}`;
13003
- const bundle = path46.join(bundlesDir, `${createHash8("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
13004
- if (!fs15.exists(bundle)) {
13005
- fs15.mkdirp(bundlesDir);
13006
- fs15.writeFileAtomic(bundle, combined);
13003
+ const bundle = path47.join(bundlesDir, `${createHash8("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
13004
+ if (!fs16.exists(bundle)) {
13005
+ fs16.mkdirp(bundlesDir);
13006
+ fs16.writeFileAtomic(bundle, combined);
13007
13007
  }
13008
13008
  return { path: bundle };
13009
13009
  }
@@ -13016,7 +13016,7 @@ var init_trust = __esm({
13016
13016
  });
13017
13017
 
13018
13018
  // src/frontdoor/realFrontDoorPort.ts
13019
- import fs14 from "node:fs";
13019
+ import fs15 from "node:fs";
13020
13020
  import os10 from "node:os";
13021
13021
  function realEnsurePorts(paths, spawnDaemon) {
13022
13022
  return {
@@ -13043,7 +13043,7 @@ function realEnsurePorts(paths, spawnDaemon) {
13043
13043
  }
13044
13044
  },
13045
13045
  // Read fresh for each probe: a replacement supervisor may have regenerated an unparseable CA, and the probe must trust exactly what the serving door's leaf chains to.
13046
- verifyListener: (port) => probeFrontDoorSync(port, fs14.readFileSync(paths.frontdoorCaCertFile, "utf8"))
13046
+ verifyListener: (port) => probeFrontDoorSync(port, fs15.readFileSync(paths.frontdoorCaCertFile, "utf8"))
13047
13047
  };
13048
13048
  }
13049
13049
  function realFrontDoorPort(paths, spawnDaemon) {
@@ -13130,10 +13130,10 @@ var init_realFrontDoorPort = __esm({
13130
13130
  init_selfIdentity();
13131
13131
  init_trust();
13132
13132
  realTrustBundleFs = {
13133
- readFileUtf8: (file) => fs14.readFileSync(file, "utf8"),
13134
- exists: (file) => fs14.existsSync(file),
13133
+ readFileUtf8: (file) => fs15.readFileSync(file, "utf8"),
13134
+ exists: (file) => fs15.existsSync(file),
13135
13135
  mkdirp: (dir) => {
13136
- fs14.mkdirSync(dir, { recursive: true });
13136
+ fs15.mkdirSync(dir, { recursive: true });
13137
13137
  },
13138
13138
  writeFileAtomic: (file, contents) => {
13139
13139
  realFarmFs.writeFilePrivate(file, contents);
@@ -13144,7 +13144,7 @@ var init_realFrontDoorPort = __esm({
13144
13144
 
13145
13145
  // src/launchWiring.ts
13146
13146
  import os11 from "node:os";
13147
- import path47 from "node:path";
13147
+ import path48 from "node:path";
13148
13148
  import { randomUUID as randomUUID5 } from "node:crypto";
13149
13149
  function buildFarmRuntime(paths, cwd, run = realRunPort) {
13150
13150
  const home = os11.homedir();
@@ -13199,7 +13199,7 @@ function realPrepareLaunchParams(paths, options) {
13199
13199
  frontdoor: realFrontDoorPort(paths, options.spawnDaemon),
13200
13200
  credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
13201
13201
  hold: realHoldPort,
13202
- hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: path47.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
13202
+ hasStoredLogin: (identity) => identitySignIn(realFarmFs, { platform: process.platform, run: options.run ?? realRunPort }, { farmRoot: path48.join(paths.identitiesDir, identity), hasCredentialBlock: false, provider: void 0 }).state !== "signed-out",
13203
13203
  ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
13204
13204
  ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
13205
13205
  ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
@@ -13935,8 +13935,8 @@ function pathnameOf(url) {
13935
13935
  return new URL(url ?? "/", "http://127.0.0.1").pathname;
13936
13936
  }
13937
13937
  function isRcSessionExchange(url) {
13938
- const path48 = pathnameOf(url);
13939
- return path48 === RC_SESSIONS_PATH_PREFIX || path48.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
13938
+ const path49 = pathnameOf(url);
13939
+ return path49 === RC_SESSIONS_PATH_PREFIX || path49.startsWith(`${RC_SESSIONS_PATH_PREFIX}/`);
13940
13940
  }
13941
13941
  var RC_SESSION_ID_PREFIX = "cse_";
13942
13942
  var RC_IDLE_EXPIRY_MS = 45e3;
@@ -14495,8 +14495,8 @@ var RC_READ_FILE_ENCODINGS = ["utf-8", "base64"];
14495
14495
  function isRcReadFileEncoding(value) {
14496
14496
  return RC_READ_FILE_ENCODINGS.some((encoding) => encoding === value);
14497
14497
  }
14498
- function buildRcReadFilePayload(requestId, path48, options) {
14499
- return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path48, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
14498
+ function buildRcReadFilePayload(requestId, path49, options) {
14499
+ return buildRcControlRequestPayload(requestId, { subtype: "read_file", path: path49, ...options?.maxBytes === void 0 ? {} : { max_bytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } });
14500
14500
  }
14501
14501
  function buildRcFileSuggestionsPayload(requestId, query) {
14502
14502
  return buildRcControlRequestPayload(requestId, { subtype: "file_suggestions", query });
@@ -14598,15 +14598,15 @@ async function getRcSessionContextUsage(deps, sessionId, detail) {
14598
14598
  const result = await deliverRcClientPayload(deps, sessionId, buildRcGetContextUsagePayload(requestId, detail), `request the context usage of session ${sessionId}`);
14599
14599
  return result.ok ? { ...result, requestId } : result;
14600
14600
  }
14601
- async function readRcSessionFile(deps, sessionId, path48, options) {
14602
- if (path48 === "") {
14601
+ async function readRcSessionFile(deps, sessionId, path49, options) {
14602
+ if (path49 === "") {
14603
14603
  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" };
14604
14604
  }
14605
14605
  if (options?.maxBytes !== void 0 && (!Number.isInteger(options.maxBytes) || options.maxBytes <= 0)) {
14606
14606
  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" };
14607
14607
  }
14608
14608
  const requestId = deps.newUuid();
14609
- const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path48, options), `read ${path48} from session ${sessionId}`);
14609
+ const result = await deliverRcClientPayload(deps, sessionId, buildRcReadFilePayload(requestId, path49, options), `read ${path49} from session ${sessionId}`);
14610
14610
  return result.ok ? { ...result, requestId } : result;
14611
14611
  }
14612
14612
  async function suggestRcSessionFiles(deps, sessionId, query) {
@@ -14775,11 +14775,11 @@ function createRcControlHandler(deps) {
14775
14775
  path: "read-file",
14776
14776
  read: (body) => {
14777
14777
  const session = bodyString(body, "session");
14778
- const path48 = bodyString(body, "path");
14778
+ const path49 = bodyString(body, "path");
14779
14779
  const maxBytes = "maxBytes" in body ? bodyPositiveInteger(body, "maxBytes") : void 0;
14780
14780
  const encoding = "encoding" in body && isRcReadFileEncoding(body.encoding) ? body.encoding : void 0;
14781
- const refused2 = session === void 0 || path48 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
14782
- 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, path48, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
14781
+ const refused2 = session === void 0 || path49 === void 0 || "maxBytes" in body && maxBytes === void 0 || "encoding" in body && encoding === void 0;
14782
+ 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, path49, { ...maxBytes === void 0 ? {} : { maxBytes }, ...encoding === void 0 ? {} : { encoding } }) };
14783
14783
  }
14784
14784
  },
14785
14785
  {
@@ -15089,9 +15089,9 @@ function requestIdOfBody(body) {
15089
15089
  }
15090
15090
  function frontDoorRcControl(transport, token) {
15091
15091
  const headers = { authorization: `Bearer ${token}` };
15092
- const listAnswerOf = async (path48, what) => {
15092
+ const listAnswerOf = async (path49, what) => {
15093
15093
  try {
15094
- return await transport.request({ method: "GET", path: path48, headers });
15094
+ return await transport.request({ method: "GET", path: path49, headers });
15095
15095
  } catch (error) {
15096
15096
  throw new Error(`${what}: could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
15097
15097
  }
@@ -15163,10 +15163,10 @@ function frontDoorRcControl(transport, token) {
15163
15163
  }
15164
15164
  return pending;
15165
15165
  };
15166
- const writeOf = async (path48, body, describeFailure2) => {
15166
+ const writeOf = async (path49, body, describeFailure2) => {
15167
15167
  let answer;
15168
15168
  try {
15169
- answer = await transport.request({ method: "POST", path: path48, headers: { ...headers, "content-type": "application/json" }, body });
15169
+ answer = await transport.request({ method: "POST", path: path49, headers: { ...headers, "content-type": "application/json" }, body });
15170
15170
  } catch (error) {
15171
15171
  return { ok: false, message: `could not reach the front door's control listener: ${error instanceof Error ? error.message : String(error)}` };
15172
15172
  }
@@ -15197,10 +15197,10 @@ function frontDoorRcControl(transport, token) {
15197
15197
  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}`),
15198
15198
  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}`),
15199
15199
  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}`),
15200
- readFile: async (sessionId, path48, options) => await writeOf(
15200
+ readFile: async (sessionId, path49, options) => await writeOf(
15201
15201
  `${CONTROL_PATH_PREFIX}/read-file`,
15202
- JSON.stringify({ session: sessionId, path: path48, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
15203
- (status, message) => `reading ${path48} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
15202
+ JSON.stringify({ session: sessionId, path: path49, ...options?.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes }, ...options?.encoding === void 0 ? {} : { encoding: options.encoding } }),
15203
+ (status, message) => `reading ${path49} from ${sessionId} failed (HTTP ${String(status)}): ${message}`
15204
15204
  ),
15205
15205
  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}`),
15206
15206
  keepAlive: async (sessionId) => await writeOf(`${CONTROL_PATH_PREFIX}/keep-alive`, JSON.stringify({ session: sessionId }), (status, message) => `keeping ${sessionId} alive failed (HTTP ${String(status)}): ${message}`),
@@ -15359,12 +15359,12 @@ function tlsFacts(options) {
15359
15359
  }
15360
15360
  function realRcEventDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
15361
15361
  const agent = new ExemptTlsAgent();
15362
- const post = async (path48, headers, body) => await new Promise((resolve, reject) => {
15362
+ const post = async (path49, headers, body) => await new Promise((resolve, reject) => {
15363
15363
  const options = {
15364
15364
  host: target.host,
15365
15365
  port: target.port,
15366
15366
  method: "POST",
15367
- path: path48,
15367
+ path: path49,
15368
15368
  // 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.
15369
15369
  headers: { ...headers, host: target.servername ?? target.host, "content-length": String(Buffer.byteLength(body, "utf8")) },
15370
15370
  agent
@@ -15429,12 +15429,12 @@ function lateRcStreamDial(resolve) {
15429
15429
  }
15430
15430
  function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_PORT }) {
15431
15431
  const agent = new ExemptTlsAgent();
15432
- const request4 = async (method, path48, headers, body, signal) => await new Promise((resolve, reject) => {
15432
+ const request4 = async (method, path49, headers, body, signal) => await new Promise((resolve, reject) => {
15433
15433
  const options = {
15434
15434
  host: target.host,
15435
15435
  port: target.port,
15436
15436
  method,
15437
- path: path48,
15437
+ path: path49,
15438
15438
  // 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.
15439
15439
  headers: { ...headers, host: target.servername ?? target.host, ...body === void 0 ? {} : { "content-length": String(Buffer.byteLength(body, "utf8")) } },
15440
15440
  agent,
@@ -15476,9 +15476,9 @@ function realRcStreamDial(target = { host: CONNECT_INTERCEPT_HOST, port: HTTPS_P
15476
15476
  return { status, body: await readAll(response) };
15477
15477
  },
15478
15478
  openStream: async (sessionId, headers, resume, signal) => {
15479
- const path48 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
15479
+ const path49 = resume === void 0 ? `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream` : `/v1/code/sessions/${encodeURIComponent(sessionId)}/events/stream?from_sequence_num=${String(resume.fromSequenceNum)}`;
15480
15480
  const streamHeaders = resume === void 0 ? headers : { ...headers, "last-event-id": String(resume.fromSequenceNum) };
15481
- const { status, response } = await request4("GET", path48, streamHeaders, void 0, signal);
15481
+ const { status, response } = await request4("GET", path49, streamHeaders, void 0, signal);
15482
15482
  if (!isSuccessful2(status)) {
15483
15483
  await readAll(response);
15484
15484
  return { status, chunks: NO_CHUNKS };
@@ -15728,11 +15728,11 @@ function credentialOfJson(parsed) {
15728
15728
  function sequenceNumOfJson(value) {
15729
15729
  return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
15730
15730
  }
15731
- function createRcCredentialStore(fs15, dir) {
15732
- fs15.mkdirPrivate(dir);
15731
+ function createRcCredentialStore(fs16, dir) {
15732
+ fs16.mkdirPrivate(dir);
15733
15733
  const fileFor = (sessionId) => path13.join(dir, `${sessionId}.json`);
15734
15734
  const readParsed = (sessionId) => {
15735
- const raw = fs15.readFileUtf8(fileFor(sessionId));
15735
+ const raw = fs16.readFileUtf8(fileFor(sessionId));
15736
15736
  if (raw === void 0) {
15737
15737
  return void 0;
15738
15738
  }
@@ -15757,7 +15757,7 @@ function createRcCredentialStore(fs15, dir) {
15757
15757
  }
15758
15758
  const cursor = sequenceNumOfJson(readParsed(sessionId)?.highestSequenceNum);
15759
15759
  const record = { ...credential, ...cursor === void 0 ? {} : { highestSequenceNum: cursor } };
15760
- fs15.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record, null, 2)}
15760
+ fs16.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record, null, 2)}
15761
15761
  `);
15762
15762
  },
15763
15763
  readCursor: (sessionId) => {
@@ -15772,14 +15772,14 @@ function createRcCredentialStore(fs15, dir) {
15772
15772
  }
15773
15773
  const credential = credentialOfJson(readParsed(sessionId));
15774
15774
  const record = credential === void 0 ? { highestSequenceNum } : { ...credential, highestSequenceNum };
15775
- fs15.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record, null, 2)}
15775
+ fs16.writeFilePrivate(fileFor(sessionId), `${JSON.stringify(record, null, 2)}
15776
15776
  `);
15777
15777
  },
15778
15778
  remove: (sessionId) => {
15779
15779
  if (!isSafeSessionId(sessionId)) {
15780
15780
  return;
15781
15781
  }
15782
- fs15.removeRecursive(fileFor(sessionId));
15782
+ fs16.removeRecursive(fileFor(sessionId));
15783
15783
  }
15784
15784
  };
15785
15785
  }
@@ -16471,19 +16471,19 @@ function writePools(paths, pools) {
16471
16471
  applyPatch(paths.globalConfigFile, GlobalConfigSchema, { pools }, { defaults: {} });
16472
16472
  }
16473
16473
  function poolCycleOf(pools, name) {
16474
- const walk2 = (current, path48) => {
16474
+ const walk2 = (current, path49) => {
16475
16475
  for (const entry of pools[current]?.identities ?? []) {
16476
16476
  const nested = poolNameOf(poolMemberIdentity(entry));
16477
16477
  if (nested === void 0) {
16478
16478
  continue;
16479
16479
  }
16480
16480
  if (nested === name) {
16481
- return [...path48, nested];
16481
+ return [...path49, nested];
16482
16482
  }
16483
- if (path48.includes(nested)) {
16483
+ if (path49.includes(nested)) {
16484
16484
  continue;
16485
16485
  }
16486
- const found = walk2(nested, [...path48, nested]);
16486
+ const found = walk2(nested, [...path49, nested]);
16487
16487
  if (found !== void 0) {
16488
16488
  return found;
16489
16489
  }
@@ -17195,7 +17195,7 @@ var ResetRowSchema = z24.strictObject({
17195
17195
  var ResetScheduleSchema = z24.strictObject({ resets: z24.readonly(z24.array(ResetRowSchema)) });
17196
17196
 
17197
17197
  // src/frontdoor/controlSchemas.ts
17198
- import path35 from "node:path";
17198
+ import path36 from "node:path";
17199
17199
  import { z as z32 } from "zod";
17200
17200
 
17201
17201
  // src/doctorReport.ts
@@ -17244,8 +17244,8 @@ var RenameJournalUnreadableError = class extends CliError {
17244
17244
  }
17245
17245
  detail;
17246
17246
  };
17247
- function readRenameJournal(fs15, file) {
17248
- const raw = fs15.readFileUtf8(file);
17247
+ function readRenameJournal(fs16, file) {
17248
+ const raw = fs16.readFileUtf8(file);
17249
17249
  if (raw === void 0) {
17250
17250
  return void 0;
17251
17251
  }
@@ -17261,16 +17261,16 @@ function readRenameJournal(fs15, file) {
17261
17261
  }
17262
17262
  return result.data;
17263
17263
  }
17264
- function listRenameJournals(fs15, directory) {
17264
+ function listRenameJournals(fs16, directory) {
17265
17265
  const journals = [];
17266
17266
  const unreadable = [];
17267
- for (const name of [...fs15.readdir(directory)].sort()) {
17267
+ for (const name of [...fs16.readdir(directory)].sort()) {
17268
17268
  if (!name.endsWith(JOURNAL_SUFFIX)) {
17269
17269
  continue;
17270
17270
  }
17271
17271
  const file = path30.join(directory, name);
17272
17272
  try {
17273
- const journal = readRenameJournal(fs15, file);
17273
+ const journal = readRenameJournal(fs16, file);
17274
17274
  if (journal !== void 0) {
17275
17275
  journals.push(journal);
17276
17276
  }
@@ -17313,8 +17313,8 @@ var NameHeldByUnfinishedRenameError = class extends CliError {
17313
17313
  this.name = "NameHeldByUnfinishedRenameError";
17314
17314
  }
17315
17315
  };
17316
- function requireNameFreeOfUnfinishedRename(fs15, directory, name, action, sameName, exists) {
17317
- const held = listRenameJournals(fs15, directory).journals.find((journal) => [journal.from, journal.to].some((heldName) => heldName === name || sameName(name, heldName)));
17316
+ function requireNameFreeOfUnfinishedRename(fs16, directory, name, action, sameName, exists) {
17317
+ const held = listRenameJournals(fs16, directory).journals.find((journal) => [journal.from, journal.to].some((heldName) => heldName === name || sameName(name, heldName)));
17318
17318
  if (held !== void 0) {
17319
17319
  throw new NameHeldByUnfinishedRenameError(action, name, held, finishabilityOf(held, exists));
17320
17320
  }
@@ -17664,8 +17664,46 @@ function removeIdentity(paths, name) {
17664
17664
 
17665
17665
  // src/doctorReport.ts
17666
17666
  init_realPorts();
17667
- import fs12 from "node:fs";
17668
- import path34 from "node:path";
17667
+ import fs13 from "node:fs";
17668
+
17669
+ // src/doctorPath.ts
17670
+ init_blockingSpawn();
17671
+ init_realPorts();
17672
+ import fs11 from "node:fs";
17673
+ import path33 from "node:path";
17674
+ function realpathOrSelf(target) {
17675
+ try {
17676
+ return fs11.realpathSync(target);
17677
+ } catch {
17678
+ return target;
17679
+ }
17680
+ }
17681
+ var MAX_FORWARDING_SCRIPT_BYTES = 8192;
17682
+ function resolveMiseDispatcher(target, pathDirs, env, trustedExecutable) {
17683
+ const executable = realpathOrSelf(target);
17684
+ const trustedMise = path33.join(path33.dirname(trustedExecutable), "mise");
17685
+ if (path33.basename(executable) !== "mise" || realpathOrSelf(trustedMise) !== executable) return void 0;
17686
+ const result = spawnSyncBlocking("a mise shim lookup", executable, ["which", path33.basename(target)], { encoding: "utf8", env });
17687
+ if (result.error !== void 0) return void 0;
17688
+ if (result.status === 0 && result.stdout.trim() !== "") return result.stdout.trim();
17689
+ if (!result.stderr.includes("not currently active")) return void 0;
17690
+ for (const dir of pathDirs) {
17691
+ const candidate = findExecutableInDir(dir, path33.basename(target));
17692
+ if (candidate !== void 0 && realpathOrSelf(candidate) !== executable) {
17693
+ try {
17694
+ const script = fs11.statSync(candidate).size <= MAX_FORWARDING_SCRIPT_BYTES ? realFsPort.readFileUtf8(candidate) : void 0;
17695
+ const forwarded = script === void 0 ? void 0 : /^#!\/bin\/sh\r?\nexec (\/[A-Za-z0-9_./+-]+) "\$@"\r?\n?$/.exec(script)?.[1];
17696
+ return forwarded ?? candidate;
17697
+ } catch {
17698
+ return candidate;
17699
+ }
17700
+ }
17701
+ }
17702
+ return void 0;
17703
+ }
17704
+
17705
+ // src/doctorReport.ts
17706
+ import path35 from "node:path";
17669
17707
  init_signIn();
17670
17708
  init_identityAccounts();
17671
17709
  init_read();
@@ -17912,7 +17950,7 @@ function pushFrontDoorListeners(push, readings) {
17912
17950
 
17913
17951
  // src/frontdoor/listenerReadings.ts
17914
17952
  init_probe();
17915
- import fs11 from "node:fs";
17953
+ import fs12 from "node:fs";
17916
17954
  function readFrontDoorListeners(state, supervisorAlive, probes) {
17917
17955
  if (!supervisorAlive) {
17918
17956
  return [];
@@ -17932,7 +17970,7 @@ function readFrontDoorListeners(state, supervisorAlive, probes) {
17932
17970
  }
17933
17971
  function realFrontDoorListenerProbes(paths) {
17934
17972
  return {
17935
- authenticateProvider: (port) => probeFrontDoorSync(port, fs11.readFileSync(paths.frontdoorCaCertFile, "utf8")),
17973
+ authenticateProvider: (port) => probeFrontDoorSync(port, fs12.readFileSync(paths.frontdoorCaCertFile, "utf8")),
17936
17974
  connect: probeListenerAcceptSync,
17937
17975
  now: () => performance.now()
17938
17976
  };
@@ -18064,11 +18102,12 @@ var DOCTOR_SECTIONS = [
18064
18102
  "frontdoor",
18065
18103
  "models"
18066
18104
  ];
18067
- function refinePathShadow(status, ownExecutablePath, realpath) {
18105
+ function refinePathShadow(status, ownExecutablePath, realpath, resolveDispatcher) {
18068
18106
  if (status.status !== "shadowed") {
18069
18107
  return status;
18070
18108
  }
18071
- return realpath(status.by) === realpath(ownExecutablePath) ? { status: "ok" } : status;
18109
+ const resolved = resolveDispatcher?.(status.by) ?? status.by;
18110
+ return realpath(resolved) === realpath(ownExecutablePath) ? { status: "ok" } : status;
18072
18111
  }
18073
18112
  function validateJson(schema, input) {
18074
18113
  if (input.raw === void 0) {
@@ -18097,7 +18136,7 @@ function tcpPortEraRecord(raw) {
18097
18136
  return (has("port") || has("lastPort")) && !has("socketPath");
18098
18137
  }
18099
18138
  function pushPathResolution(push, resolution) {
18100
- const ownDir = path34.dirname(resolution.ownExecutablePath);
18139
+ const ownDir = path35.dirname(resolution.ownExecutablePath);
18101
18140
  switch (resolution.agentShim.status) {
18102
18141
  case "ok":
18103
18142
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -18217,14 +18256,14 @@ function pushProvider(push, entry, cacheEnv, signIn) {
18217
18256
  }
18218
18257
  function pushLegacyName(push, params) {
18219
18258
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
18220
- if (legacyVariables.length === 0 && path34.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
18259
+ if (legacyVariables.length === 0 && path35.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
18221
18260
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
18222
18261
  return;
18223
18262
  }
18224
18263
  for (const name of legacyVariables) {
18225
18264
  push("legacy-name", "warn", `${name} is the former name of ${name.replace(LEGACY_ENV_PREFIX, ENV_PREFIX)}. Rename it; the old name still works but is only a fallback.`, name);
18226
18265
  }
18227
- if (path34.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
18266
+ if (path35.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
18228
18267
  push(
18229
18268
  "legacy-name",
18230
18269
  "warn",
@@ -18318,7 +18357,7 @@ function runDoctor(params) {
18318
18357
  push("identity", "warn", `identities/${name} cannot be reached (${code}), so it is not counted as an identity. Repair the permissions of the directory or of what a symlink points through, or remove the entry.`, name);
18319
18358
  }
18320
18359
  for (const { file, detail } of params.renameJournals?.unreadable ?? []) {
18321
- push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, path34.basename(file));
18360
+ push("identity", "fail", `${file} is not a rename journal this agent-shim can read (${detail}), so no identity can be renamed until it is fixed or removed, and it may be the trace of a rename that was left unfinished.`, path35.basename(file));
18322
18361
  }
18323
18362
  const validIdentityNames = /* @__PURE__ */ new Set();
18324
18363
  const signedInAccounts = [];
@@ -18668,13 +18707,6 @@ function formatDoctorReport(report) {
18668
18707
  lines.push("", report.ok ? "All checks passed." : `${String(failCount)} check(s) failed.`);
18669
18708
  return lines;
18670
18709
  }
18671
- function realpathOrSelf(target) {
18672
- try {
18673
- return fs12.realpathSync(target);
18674
- } catch {
18675
- return target;
18676
- }
18677
- }
18678
18710
  function servingDoorListeners(paths) {
18679
18711
  const state = readFrontDoorState(realFarmFs, paths.frontdoorStateFile) ?? {};
18680
18712
  const alive = state.supervisorPid !== void 0 && realIsProcessRunning(state.supervisorPid);
@@ -18684,9 +18716,9 @@ function collectDoctorReport(params) {
18684
18716
  const { paths } = params;
18685
18717
  const { names: identityNames, unreachable: unreachableIdentities } = listIdentityDirectories(paths);
18686
18718
  const identities = identityNames.map((name) => {
18687
- const farmRoot = path34.join(paths.identitiesDir, name);
18688
- const identityPath = path34.join(farmRoot, "identity.json");
18689
- return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: fs12.existsSync(credentialsFilePath(farmRoot)), account: readIdentityAccount(realFsPort, paths.identitiesDir, name)?.account };
18719
+ const farmRoot = path35.join(paths.identitiesDir, name);
18720
+ const identityPath = path35.join(farmRoot, "identity.json");
18721
+ return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot, credentialsFilePresent: fs13.existsSync(credentialsFilePath(farmRoot)), account: readIdentityAccount(realFsPort, paths.identitiesDir, name)?.account };
18690
18722
  });
18691
18723
  const usageSnapshots = {};
18692
18724
  for (const name of identityNames) {
@@ -18701,14 +18733,14 @@ function collectDoctorReport(params) {
18701
18733
  }
18702
18734
  }
18703
18735
  }
18704
- const profileNames = fs12.existsSync(paths.configProfilesDir) ? fs12.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
18736
+ const profileNames = fs13.existsSync(paths.configProfilesDir) ? fs13.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
18705
18737
  const configProfiles = profileNames.map((name) => {
18706
- const profilePath = path34.join(paths.configProfilesDir, `${name}.json`);
18738
+ const profilePath = path35.join(paths.configProfilesDir, `${name}.json`);
18707
18739
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
18708
18740
  });
18709
- const providerNames = fs12.existsSync(paths.providersDir) ? fs12.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
18741
+ const providerNames = fs13.existsSync(paths.providersDir) ? fs13.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
18710
18742
  const providers = providerNames.map((name) => {
18711
- const providerPath = path34.join(paths.providersDir, `${name}.json`);
18743
+ const providerPath = path35.join(paths.providersDir, `${name}.json`);
18712
18744
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
18713
18745
  });
18714
18746
  const ownExecutablePath = realOwnExecutablePath();
@@ -18720,16 +18752,17 @@ function collectDoctorReport(params) {
18720
18752
  binaryDiscovery = { ok: false, message: error instanceof Error ? error.message : String(error) };
18721
18753
  }
18722
18754
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
18723
- const pathDirs = (params.env.PATH ?? "").split(path34.delimiter).filter((dir) => dir !== "");
18755
+ const pathDirs = (params.env.PATH ?? "").split(path35.delimiter).filter((dir) => dir !== "");
18724
18756
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
18725
18757
  findPathShadow({
18726
18758
  pathDirs,
18727
- targetDir: path34.dirname(shimState.targetPath),
18728
- targetFilename: path34.basename(shimState.targetPath),
18759
+ targetDir: path35.dirname(shimState.targetPath),
18760
+ targetFilename: path35.basename(shimState.targetPath),
18729
18761
  findExecutableInDir
18730
18762
  }),
18731
18763
  shimState.targetPath,
18732
- realpathOrSelf
18764
+ realpathOrSelf,
18765
+ (target) => resolveMiseDispatcher(target, pathDirs, params.env, shimState.targetPath)
18733
18766
  );
18734
18767
  const uid = process.getuid?.();
18735
18768
  const allowlistContent = realFarmFs.readFileUtf8(paths.headroomAllowlistFile);
@@ -18757,19 +18790,20 @@ function collectDoctorReport(params) {
18757
18790
  categoriesLocal: { path: paths.categoriesLocalFile, raw: realFsPort.readFileUtf8(paths.categoriesLocalFile) },
18758
18791
  activeIdentity: { path: paths.activeIdentityFile, raw: realFsPort.readFileUtf8(paths.activeIdentityFile) },
18759
18792
  binaryDiscovery,
18760
- claudeShim: { state: shimState, targetExists: shimState !== void 0 && fs12.existsSync(shimState.targetPath) },
18793
+ claudeShim: { state: shimState, targetExists: shimState !== void 0 && fs13.existsSync(shimState.targetPath) },
18761
18794
  rootPath: paths.root,
18762
18795
  pathResolution: {
18763
18796
  ownExecutablePath,
18764
18797
  agentShim: refinePathShadow(
18765
18798
  findPathShadow({
18766
18799
  pathDirs,
18767
- targetDir: path34.dirname(ownExecutablePath),
18800
+ targetDir: path35.dirname(ownExecutablePath),
18768
18801
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
18769
18802
  findExecutableInDir
18770
18803
  }),
18771
18804
  ownExecutablePath,
18772
- realpathOrSelf
18805
+ realpathOrSelf,
18806
+ (target) => resolveMiseDispatcher(target, pathDirs, params.env, ownExecutablePath)
18773
18807
  ),
18774
18808
  ...claudeShimShadow === void 0 ? {} : { claude: claudeShimShadow }
18775
18809
  },
@@ -18854,11 +18888,11 @@ var FrontDoorSessionsOutputSchema = z32.strictObject({ sessions: z32.readonly(z3
18854
18888
  var CheckRunInputSchema = z32.strictObject({
18855
18889
  path: z32.string().min(1),
18856
18890
  identity: z32.string().min(1).optional()
18857
- }).refine((input) => path35.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
18891
+ }).refine((input) => path36.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
18858
18892
  var PoolPickInputSchema = z32.strictObject({
18859
18893
  pool: z32.string().min(1),
18860
18894
  path: z32.string().min(1)
18861
- }).refine((input) => path35.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
18895
+ }).refine((input) => path36.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
18862
18896
  var DoctorFindingSchema = z32.strictObject({
18863
18897
  section: z32.enum(DOCTOR_SECTIONS),
18864
18898
  subject: z32.string().optional(),
@@ -19282,7 +19316,7 @@ function profileValue(name, paths) {
19282
19316
  function createConfigApiRouter(deps) {
19283
19317
  const authed = doorApiAuth(deps.expectedToken);
19284
19318
  const { paths } = deps;
19285
- const route = (path48, summary) => authed.meta(openapi3({ method: "POST", path: path48, summary, tags: [CONFIG_API_TAG] }));
19319
+ const route = (path49, summary) => authed.meta(openapi3({ method: "POST", path: path49, summary, tags: [CONFIG_API_TAG] }));
19286
19320
  return {
19287
19321
  config: {
19288
19322
  identity: {
@@ -19669,7 +19703,7 @@ import { ORPCError as ORPCError5 } from "@orpc/client";
19669
19703
  import { openapi as openapi6 } from "@orpc/openapi";
19670
19704
 
19671
19705
  // src/frontdoor/launchSchemas.ts
19672
- import path36 from "node:path";
19706
+ import path37 from "node:path";
19673
19707
  import { z as z36 } from "zod";
19674
19708
  init_statusline();
19675
19709
  init_claudeVersion();
@@ -19680,7 +19714,7 @@ var LaunchResolveInputSchema = z36.strictObject({
19680
19714
  argv: z36.readonly(z36.array(z36.string())).optional(),
19681
19715
  /** The launch's inherited environment. Absent means an empty one: the door's own environment is never a substitute for the caller's, so a caller that wants `AGENT_SHIM_*` switches or a `CLAUDE_CONFIG_DIR` considered names them here. Values are read, never reported. */
19682
19716
  env: z36.record(z36.string(), z36.string()).optional()
19683
- }).refine((input) => path36.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
19717
+ }).refine((input) => path37.isAbsolute(input.path), { message: "path must be absolute: the door cannot resolve a relative path against the caller's working directory" });
19684
19718
  var LaunchPoolDecisionSchema = z36.strictObject({
19685
19719
  name: z36.string(),
19686
19720
  reasons: z36.readonly(z36.array(z36.string())),
@@ -21861,7 +21895,7 @@ data: ${JSON.stringify(envelope)}
21861
21895
 
21862
21896
  // src/frontdoor/rcSelfHostMint.ts
21863
21897
  init_account();
21864
- import path37 from "node:path";
21898
+ import path38 from "node:path";
21865
21899
  var CREDENTIALS_FILE2 = ".credentials.json";
21866
21900
  var CLAUDE_JSON2 = ".claude.json";
21867
21901
  var RC_SELF_HOST_RECORD_DIR = "rc-selfhost";
@@ -21871,8 +21905,8 @@ var SELF_HOST_SUBSCRIPTION_TYPE = "max";
21871
21905
  function isRecord14(value) {
21872
21906
  return typeof value === "object" && value !== null && !Array.isArray(value);
21873
21907
  }
21874
- function readJsonObject(fs15, file) {
21875
- const raw = fs15.readFileUtf8(file);
21908
+ function readJsonObject(fs16, file) {
21909
+ const raw = fs16.readFileUtf8(file);
21876
21910
  if (raw === void 0) {
21877
21911
  return void 0;
21878
21912
  }
@@ -21884,8 +21918,8 @@ function readJsonObject(fs15, file) {
21884
21918
  }
21885
21919
  return isRecord14(parsed) ? parsed : void 0;
21886
21920
  }
21887
- function readRcSelfHostRecord(fs15, frontdoorDir) {
21888
- const parsed = readJsonObject(fs15, path37.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
21921
+ function readRcSelfHostRecord(fs16, frontdoorDir) {
21922
+ const parsed = readJsonObject(fs16, path38.join(frontdoorDir, RC_SELF_HOST_RECORD_DIR, RC_SELF_HOST_RECORD_FILE));
21889
21923
  if (parsed === void 0) {
21890
21924
  return void 0;
21891
21925
  }
@@ -21899,11 +21933,11 @@ function mintRcSelfHostCredential(deps) {
21899
21933
  if (!isIdentityName(deps.identity)) {
21900
21934
  throw new Error(`"${deps.identity}" is not a valid identity name.`);
21901
21935
  }
21902
- const identityDir = path37.join(deps.identitiesDir, deps.identity);
21903
- const credentialsFile = path37.join(identityDir, CREDENTIALS_FILE2);
21904
- const claudeJsonFile = path37.join(identityDir, CLAUDE_JSON2);
21905
- const recordDir = path37.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
21906
- const recordFile2 = path37.join(recordDir, RC_SELF_HOST_RECORD_FILE);
21936
+ const identityDir = path38.join(deps.identitiesDir, deps.identity);
21937
+ const credentialsFile = path38.join(identityDir, CREDENTIALS_FILE2);
21938
+ const claudeJsonFile = path38.join(identityDir, CLAUDE_JSON2);
21939
+ const recordDir = path38.join(deps.frontdoorDir, RC_SELF_HOST_RECORD_DIR);
21940
+ const recordFile2 = path38.join(recordDir, RC_SELF_HOST_RECORD_FILE);
21907
21941
  const previousRecord = readRcSelfHostRecord(deps.fs, deps.frontdoorDir);
21908
21942
  const existingCredentials = readJsonObject(deps.fs, credentialsFile);
21909
21943
  const existingOauth = isRecord14(existingCredentials?.claudeAiOauth) ? existingCredentials.claudeAiOauth : void 0;
@@ -21919,7 +21953,7 @@ function mintRcSelfHostCredential(deps) {
21919
21953
  const organizationUuid = deps.newUuid();
21920
21954
  const accountUuid = deps.newUuid();
21921
21955
  const mintedAt = new Date(deps.now()).toISOString();
21922
- deps.fs.mkdirPrivate(path37.dirname(credentialsFile));
21956
+ deps.fs.mkdirPrivate(path38.dirname(credentialsFile));
21923
21957
  deps.fs.writeFilePrivate(credentialsFile, `${JSON.stringify({ ...existingCredentials, claudeAiOauth: { accessToken, refreshToken, expiresAt: null, scopes: [...RC_SELF_HOST_SCOPE_LIST], subscriptionType: SELF_HOST_SUBSCRIPTION_TYPE, rateLimitTier: null } }, null, 2)}
21924
21958
  `);
21925
21959
  const claudeJson = readJsonObject(deps.fs, claudeJsonFile) ?? {};
@@ -21957,25 +21991,25 @@ init_ensure2();
21957
21991
  // src/frontdoor/liveSessionRegistry.ts
21958
21992
  init_capability();
21959
21993
  init_state();
21960
- import path38 from "node:path";
21994
+ import path39 from "node:path";
21961
21995
  function sameStat(recorded, current) {
21962
21996
  return recorded?.mtimeMs === current.mtimeMs && recorded.sizeBytes === current.sizeBytes;
21963
21997
  }
21964
21998
  function createLiveSessionRegistry(ports) {
21965
- const { fs: fs15, sessionsDir } = ports;
21999
+ const { fs: fs16, sessionsDir } = ports;
21966
22000
  const known = /* @__PURE__ */ new Map();
21967
22001
  let tokens = /* @__PURE__ */ new Set();
21968
22002
  let bySessionId = /* @__PURE__ */ new Map();
21969
- const recordNames = () => fs15.readdir(sessionsDir).filter(isSessionRecordName);
22003
+ const recordNames = () => fs16.readdir(sessionsDir).filter(isSessionRecordName);
21970
22004
  const rebuildIndexes = () => {
21971
22005
  const records = [...known.values()].flatMap(({ record }) => record === void 0 ? [] : [record]);
21972
22006
  tokens = new Set(records.map((record) => record.token));
21973
22007
  bySessionId = new Map(records.flatMap((record) => record.sessionId === void 0 ? [] : [[record.sessionId, record]]));
21974
22008
  };
21975
22009
  const load = (name, stat) => {
21976
- known.set(name, { stat: { mtimeMs: stat.mtimeMs, sizeBytes: stat.sizeBytes }, record: readFrontDoorSessionRecord(fs15, sessionsDir, name) });
22010
+ known.set(name, { stat: { mtimeMs: stat.mtimeMs, sizeBytes: stat.sizeBytes }, record: readFrontDoorSessionRecord(fs16, sessionsDir, name) });
21977
22011
  };
21978
- const statOf = (name) => fs15.lstat(path38.join(sessionsDir, name));
22012
+ const statOf = (name) => fs16.lstat(path39.join(sessionsDir, name));
21979
22013
  const reconcile = () => {
21980
22014
  const names = new Set(recordNames());
21981
22015
  let changed = false;
@@ -22042,7 +22076,7 @@ init_plan2();
22042
22076
  init_poolPick();
22043
22077
 
22044
22078
  // src/agents/read.ts
22045
- import path39 from "node:path";
22079
+ import path40 from "node:path";
22046
22080
  import { z as z38 } from "zod";
22047
22081
  var PROJECTS_DIR = "projects";
22048
22082
  var TASKS_DIR = "tasks";
@@ -22066,17 +22100,17 @@ function parseEntry2(project, entry) {
22066
22100
  const base = match?.[1];
22067
22101
  return base === void 0 ? { project, sessionId: entry, superseded: false, entry } : { project, sessionId: base, superseded: true, entry };
22068
22102
  }
22069
- function listSessions2(fs15, configDir) {
22103
+ function listSessions2(fs16, configDir) {
22070
22104
  const found = [];
22071
- for (const project of fs15.readdir(path39.join(configDir, PROJECTS_DIR))) {
22072
- const projectDir = path39.join(configDir, PROJECTS_DIR, project);
22105
+ for (const project of fs16.readdir(path40.join(configDir, PROJECTS_DIR))) {
22106
+ const projectDir = path40.join(configDir, PROJECTS_DIR, project);
22073
22107
  const entries = /* @__PURE__ */ new Set();
22074
- for (const name of fs15.readdir(projectDir)) {
22108
+ for (const name of fs16.readdir(projectDir)) {
22075
22109
  if (name.endsWith(TRANSCRIPT_SUFFIX)) {
22076
22110
  entries.add(name.slice(0, -TRANSCRIPT_SUFFIX.length));
22077
22111
  continue;
22078
22112
  }
22079
- const children = fs15.readdir(path39.join(projectDir, name));
22113
+ const children = fs16.readdir(path40.join(projectDir, name));
22080
22114
  if (children.includes(SUBAGENTS_DIR) || children.includes(WORKFLOWS_DIR)) {
22081
22115
  entries.add(name);
22082
22116
  }
@@ -22087,17 +22121,17 @@ function listSessions2(fs15, configDir) {
22087
22121
  }
22088
22122
  return found.sort((left, right) => left.project.localeCompare(right.project) || left.entry.localeCompare(right.entry));
22089
22123
  }
22090
- function locateAgents(fs15, configDir, relativeDir, workflowRunId, report) {
22124
+ function locateAgents(fs16, configDir, relativeDir, workflowRunId, report) {
22091
22125
  const located = [];
22092
- for (const name of listDirOrReport(fs15, configDir, relativeDir, report)) {
22126
+ for (const name of listDirOrReport(fs16, configDir, relativeDir, report)) {
22093
22127
  if (!name.startsWith(AGENT_FILE_PREFIX) || !name.endsWith(META_SUFFIX)) {
22094
22128
  continue;
22095
22129
  }
22096
22130
  const id = name.slice(AGENT_FILE_PREFIX.length, -META_SUFFIX.length);
22097
22131
  located.push({
22098
22132
  id,
22099
- metaPath: path39.join(relativeDir, name),
22100
- transcriptPath: path39.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
22133
+ metaPath: path40.join(relativeDir, name),
22134
+ transcriptPath: path40.join(relativeDir, `${AGENT_FILE_PREFIX}${id}${TRANSCRIPT_SUFFIX}`),
22101
22135
  workflowRunId
22102
22136
  });
22103
22137
  }
@@ -22138,17 +22172,17 @@ function toNode(read, children) {
22138
22172
  function describeFailure(error) {
22139
22173
  return error instanceof Error ? error.message : String(error);
22140
22174
  }
22141
- function readFileOrReport(fs15, configDir, relative, report) {
22175
+ function readFileOrReport(fs16, configDir, relative, report) {
22142
22176
  try {
22143
- return fs15.readFileUtf8(path39.join(configDir, relative));
22177
+ return fs16.readFileUtf8(path40.join(configDir, relative));
22144
22178
  } catch (error) {
22145
22179
  report({ path: relative, reason: `could not be read: ${describeFailure(error)}` });
22146
22180
  return void 0;
22147
22181
  }
22148
22182
  }
22149
- function listDirOrReport(fs15, configDir, relative, report) {
22183
+ function listDirOrReport(fs16, configDir, relative, report) {
22150
22184
  try {
22151
- return fs15.readdir(path39.join(configDir, relative));
22185
+ return fs16.readdir(path40.join(configDir, relative));
22152
22186
  } catch (error) {
22153
22187
  report({ path: relative, reason: `could not be listed: ${describeFailure(error)}` });
22154
22188
  return [];
@@ -22171,38 +22205,38 @@ var WorkflowRunFileSchema = z38.object({
22171
22205
  phases: z38.array(z38.object({ title: z38.string() })).default([]),
22172
22206
  summary: z38.string().optional()
22173
22207
  });
22174
- function summariseSession(fs15, configDir, ref) {
22175
- const sessionRelative = path39.join(PROJECTS_DIR, ref.project, ref.entry);
22176
- const subagentsRelative = path39.join(sessionRelative, SUBAGENTS_DIR);
22177
- const workflowsUnderSubagents = path39.join(subagentsRelative, WORKFLOWS_DIR);
22208
+ function summariseSession(fs16, configDir, ref) {
22209
+ const sessionRelative = path40.join(PROJECTS_DIR, ref.project, ref.entry);
22210
+ const subagentsRelative = path40.join(sessionRelative, SUBAGENTS_DIR);
22211
+ const workflowsUnderSubagents = path40.join(subagentsRelative, WORKFLOWS_DIR);
22178
22212
  const isMeta = (name) => name.startsWith(AGENT_FILE_PREFIX) && name.endsWith(META_SUFFIX);
22179
- let agentCount = fs15.readdir(path39.join(configDir, subagentsRelative)).filter(isMeta).length;
22180
- for (const runDir of fs15.readdir(path39.join(configDir, workflowsUnderSubagents))) {
22213
+ let agentCount = fs16.readdir(path40.join(configDir, subagentsRelative)).filter(isMeta).length;
22214
+ for (const runDir of fs16.readdir(path40.join(configDir, workflowsUnderSubagents))) {
22181
22215
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
22182
- agentCount += fs15.readdir(path39.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
22216
+ agentCount += fs16.readdir(path40.join(configDir, workflowsUnderSubagents, runDir)).filter(isMeta).length;
22183
22217
  }
22184
22218
  }
22185
- const workflowRunCount = fs15.readdir(path39.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
22186
- const transcript = fs15.lstat(path39.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
22219
+ const workflowRunCount = fs16.readdir(path40.join(configDir, sessionRelative, WORKFLOWS_DIR)).filter((name) => name.startsWith(WORKFLOW_RUN_PREFIX) && name.endsWith(JSON_SUFFIX)).length;
22220
+ const transcript = fs16.lstat(path40.join(configDir, PROJECTS_DIR, ref.project, `${ref.entry}${TRANSCRIPT_SUFFIX}`));
22187
22221
  return { ...ref, agentCount, workflowRunCount, ...transcript === void 0 ? {} : { updatedAt: new Date(transcript.mtimeMs).toISOString() } };
22188
22222
  }
22189
- function readSessionAgentTree(fs15, configDir, ref, options = {}) {
22223
+ function readSessionAgentTree(fs16, configDir, ref, options = {}) {
22190
22224
  const problems = [];
22191
22225
  const report = (problem) => {
22192
22226
  problems.push(problem);
22193
22227
  };
22194
- const sessionRelative = path39.join(PROJECTS_DIR, ref.project, ref.entry);
22195
- const subagentsRelative = path39.join(sessionRelative, SUBAGENTS_DIR);
22196
- const workflowsUnderSubagents = path39.join(subagentsRelative, WORKFLOWS_DIR);
22197
- const located = locateAgents(fs15, configDir, subagentsRelative, void 0, report);
22198
- for (const runDir of listDirOrReport(fs15, configDir, workflowsUnderSubagents, report)) {
22228
+ const sessionRelative = path40.join(PROJECTS_DIR, ref.project, ref.entry);
22229
+ const subagentsRelative = path40.join(sessionRelative, SUBAGENTS_DIR);
22230
+ const workflowsUnderSubagents = path40.join(subagentsRelative, WORKFLOWS_DIR);
22231
+ const located = locateAgents(fs16, configDir, subagentsRelative, void 0, report);
22232
+ for (const runDir of listDirOrReport(fs16, configDir, workflowsUnderSubagents, report)) {
22199
22233
  if (runDir.startsWith(WORKFLOW_RUN_PREFIX)) {
22200
- located.push(...locateAgents(fs15, configDir, path39.join(workflowsUnderSubagents, runDir), runDir, report));
22234
+ located.push(...locateAgents(fs16, configDir, path40.join(workflowsUnderSubagents, runDir), runDir, report));
22201
22235
  }
22202
22236
  }
22203
22237
  const agents = /* @__PURE__ */ new Map();
22204
22238
  for (const candidate of located) {
22205
- const text = readFileOrReport(fs15, configDir, candidate.metaPath, report);
22239
+ const text = readFileOrReport(fs16, configDir, candidate.metaPath, report);
22206
22240
  if (text === void 0) {
22207
22241
  continue;
22208
22242
  }
@@ -22214,7 +22248,7 @@ function readSessionAgentTree(fs15, configDir, ref, options = {}) {
22214
22248
  agents.set(candidate.id, { located: candidate, meta: parsed.data });
22215
22249
  }
22216
22250
  const teamNames = [...new Set([...agents.values()].flatMap((agent) => agent.meta.teamName === void 0 ? [] : [agent.meta.teamName]))].sort();
22217
- const parentOf3 = resolveParents(fs15, configDir, agents, report);
22251
+ const parentOf3 = resolveParents(fs16, configDir, agents, report);
22218
22252
  const childrenOf = /* @__PURE__ */ new Map();
22219
22253
  const roots = [];
22220
22254
  for (const id of agents.keys()) {
@@ -22237,12 +22271,12 @@ function readSessionAgentTree(fs15, configDir, ref, options = {}) {
22237
22271
  sessionId: ref.sessionId,
22238
22272
  superseded: ref.superseded,
22239
22273
  agents: roots.sort().map(build),
22240
- tasks: readTasks(fs15, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id) => !ownTaskLists(ref.sessionId).includes(id)), report),
22241
- workflowRuns: readWorkflowRuns(fs15, configDir, path39.join(sessionRelative, WORKFLOWS_DIR), report),
22274
+ tasks: readTasks(fs16, configDir, ownTaskLists(ref.sessionId), [.../* @__PURE__ */ new Set([...teamNames, ...options.taskListIds ?? []])].filter((id) => !ownTaskLists(ref.sessionId).includes(id)), report),
22275
+ workflowRuns: readWorkflowRuns(fs16, configDir, path40.join(sessionRelative, WORKFLOWS_DIR), report),
22242
22276
  problems
22243
22277
  };
22244
22278
  }
22245
- function resolveParents(fs15, configDir, agents, report) {
22279
+ function resolveParents(fs16, configDir, agents, report) {
22246
22280
  const parentOf3 = /* @__PURE__ */ new Map();
22247
22281
  const transcriptCache = /* @__PURE__ */ new Map();
22248
22282
  const transcriptOf = (agent) => {
@@ -22250,7 +22284,7 @@ function resolveParents(fs15, configDir, agents, report) {
22250
22284
  if (cached !== void 0) {
22251
22285
  return cached;
22252
22286
  }
22253
- const text = readFileOrReport(fs15, configDir, agent.located.transcriptPath, report) ?? "";
22287
+ const text = readFileOrReport(fs16, configDir, agent.located.transcriptPath, report) ?? "";
22254
22288
  transcriptCache.set(agent.located.id, text);
22255
22289
  return text;
22256
22290
  };
@@ -22300,16 +22334,16 @@ function resolveParents(fs15, configDir, agents, report) {
22300
22334
  function ownTaskLists(sessionId) {
22301
22335
  return [sessionId, `${SHORT_SESSION_LIST_PREFIX}${sessionId.slice(0, SHORT_SESSION_ID_LENGTH)}`];
22302
22336
  }
22303
- function readTasks(fs15, configDir, ownLists, sharedLists, report) {
22337
+ function readTasks(fs16, configDir, ownLists, sharedLists, report) {
22304
22338
  const tasks = [];
22305
22339
  [...ownLists, ...sharedLists].forEach((scope, index) => {
22306
- const relativeDir = path39.join(TASKS_DIR, scope);
22307
- for (const name of [...listDirOrReport(fs15, configDir, relativeDir, report)].sort()) {
22340
+ const relativeDir = path40.join(TASKS_DIR, scope);
22341
+ for (const name of [...listDirOrReport(fs16, configDir, relativeDir, report)].sort()) {
22308
22342
  if (name.startsWith(".") || !name.endsWith(JSON_SUFFIX)) {
22309
22343
  continue;
22310
22344
  }
22311
- const relative = path39.join(relativeDir, name);
22312
- const text = readFileOrReport(fs15, configDir, relative, report);
22345
+ const relative = path40.join(relativeDir, name);
22346
+ const text = readFileOrReport(fs16, configDir, relative, report);
22313
22347
  const parsed = TaskFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
22314
22348
  if (parsed.success) {
22315
22349
  tasks.push(index < ownLists.length ? parsed.data : { ...parsed.data, taskList: scope });
@@ -22320,14 +22354,14 @@ function readTasks(fs15, configDir, ownLists, sharedLists, report) {
22320
22354
  });
22321
22355
  return tasks;
22322
22356
  }
22323
- function readWorkflowRuns(fs15, configDir, relativeDir, report) {
22357
+ function readWorkflowRuns(fs16, configDir, relativeDir, report) {
22324
22358
  const runs = [];
22325
- for (const name of [...listDirOrReport(fs15, configDir, relativeDir, report)].sort()) {
22359
+ for (const name of [...listDirOrReport(fs16, configDir, relativeDir, report)].sort()) {
22326
22360
  if (!name.startsWith(WORKFLOW_RUN_PREFIX) || !name.endsWith(JSON_SUFFIX)) {
22327
22361
  continue;
22328
22362
  }
22329
- const relative = path39.join(relativeDir, name);
22330
- const text = readFileOrReport(fs15, configDir, relative, report);
22363
+ const relative = path40.join(relativeDir, name);
22364
+ const text = readFileOrReport(fs16, configDir, relative, report);
22331
22365
  const parsed = WorkflowRunFileSchema.safeParse(text === void 0 ? void 0 : parseJson2(text));
22332
22366
  if (!parsed.success) {
22333
22367
  if (text !== void 0) {
@@ -22343,7 +22377,7 @@ function readWorkflowRuns(fs15, configDir, relativeDir, report) {
22343
22377
 
22344
22378
  // src/agents/sessions.ts
22345
22379
  init_cliError();
22346
- import path40 from "node:path";
22380
+ import path41 from "node:path";
22347
22381
  var SessionLookupError = class extends CliError {
22348
22382
  constructor(message) {
22349
22383
  super(message);
@@ -22351,13 +22385,13 @@ var SessionLookupError = class extends CliError {
22351
22385
  }
22352
22386
  };
22353
22387
  function identityConfigDir(identitiesDir, identity) {
22354
- return path40.join(identitiesDir, identity);
22388
+ return path41.join(identitiesDir, identity);
22355
22389
  }
22356
- function historyStores(fs15, identitiesDir, identities) {
22390
+ function historyStores(fs16, identitiesDir, identities) {
22357
22391
  const byRealPath = /* @__PURE__ */ new Map();
22358
22392
  for (const identity of identities) {
22359
22393
  const configDir = identityConfigDir(identitiesDir, identity);
22360
- const real = fs15.realpath(path40.join(configDir, "projects"));
22394
+ const real = fs16.realpath(path41.join(configDir, "projects"));
22361
22395
  if (real === void 0) {
22362
22396
  continue;
22363
22397
  }
@@ -22370,15 +22404,15 @@ function historyStores(fs15, identitiesDir, identities) {
22370
22404
  }
22371
22405
  return [...byRealPath.values()];
22372
22406
  }
22373
- function collectSessionList(fs15, identitiesDir, identities, filters) {
22407
+ function collectSessionList(fs16, identitiesDir, identities, filters) {
22374
22408
  const names = filters.identity === void 0 ? identities : identities.filter((name) => name === filters.identity);
22375
22409
  if (filters.identity !== void 0 && names.length === 0) {
22376
22410
  throw new SessionLookupError(`no identity named "${filters.identity}"`);
22377
22411
  }
22378
22412
  const sessions = [];
22379
- for (const store of historyStores(fs15, identitiesDir, names)) {
22380
- for (const ref of listSessions2(fs15, store.configDir)) {
22381
- const summary = summariseSession(fs15, store.configDir, ref);
22413
+ for (const store of historyStores(fs16, identitiesDir, names)) {
22414
+ for (const ref of listSessions2(fs16, store.configDir)) {
22415
+ const summary = summariseSession(fs16, store.configDir, ref);
22382
22416
  if (filters.all === true || summary.agentCount > 0 || summary.workflowRunCount > 0) {
22383
22417
  sessions.push({ ...summary, identities: store.identities });
22384
22418
  }
@@ -22386,14 +22420,14 @@ function collectSessionList(fs15, identitiesDir, identities, filters) {
22386
22420
  }
22387
22421
  return sessions.sort((left, right) => (right.updatedAt ?? "").localeCompare(left.updatedAt ?? "") || left.sessionId.localeCompare(right.sessionId));
22388
22422
  }
22389
- function locateSession(fs15, identitiesDir, identities, query, onlyIdentity) {
22423
+ function locateSession(fs16, identitiesDir, identities, query, onlyIdentity) {
22390
22424
  const names = onlyIdentity === void 0 ? identities : identities.filter((name) => name === onlyIdentity);
22391
22425
  if (onlyIdentity !== void 0 && names.length === 0) {
22392
22426
  throw new SessionLookupError(`no identity named "${onlyIdentity}"`);
22393
22427
  }
22394
22428
  const matches = [];
22395
- for (const store of historyStores(fs15, identitiesDir, names)) {
22396
- for (const ref of listSessions2(fs15, store.configDir)) {
22429
+ for (const store of historyStores(fs16, identitiesDir, names)) {
22430
+ for (const ref of listSessions2(fs16, store.configDir)) {
22397
22431
  if (ref.sessionId.startsWith(query)) {
22398
22432
  matches.push({ identities: store.identities, configDir: store.configDir, ref });
22399
22433
  }
@@ -22410,9 +22444,9 @@ function locateSession(fs15, identitiesDir, identities, query, onlyIdentity) {
22410
22444
  }
22411
22445
  throw new SessionLookupError(`"${query}" matches ${String(candidates.length)} sessions: ${candidates.map((match) => `${match.ref.sessionId} (${match.identities.join(", ")})`).join("; ")}; give more of the id or pass --identity`);
22412
22446
  }
22413
- function showSession(fs15, identitiesDir, identities, query, onlyIdentity) {
22414
- const located = locateSession(fs15, identitiesDir, identities, query, onlyIdentity);
22415
- return { identities: located.identities, tree: readSessionAgentTree(fs15, located.configDir, located.ref) };
22447
+ function showSession(fs16, identitiesDir, identities, query, onlyIdentity) {
22448
+ const located = locateSession(fs16, identitiesDir, identities, query, onlyIdentity);
22449
+ return { identities: located.identities, tree: readSessionAgentTree(fs16, located.configDir, located.ref) };
22416
22450
  }
22417
22451
 
22418
22452
  // src/agents/realFs.ts