agent-shim 7.12.1 → 7.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -55406,16 +55406,16 @@ function parseJson(raw, schema) {
55406
55406
  const parsed = schema.safeParse(JSON.parse(raw));
55407
55407
  return parsed.success ? parsed.data : void 0;
55408
55408
  }
55409
- function readHeadroomState(fs18, stateFile) {
55409
+ function readHeadroomState(fs19, stateFile) {
55410
55410
  try {
55411
- return parseJson(fs18.readFileUtf8(stateFile), HeadroomStateSchema);
55411
+ return parseJson(fs19.readFileUtf8(stateFile), HeadroomStateSchema);
55412
55412
  } catch {
55413
55413
  return void 0;
55414
55414
  }
55415
55415
  }
55416
- function writeHeadroomState(fs18, stateFile, state) {
55417
- fs18.mkdirp(import_node_path5.default.dirname(stateFile));
55418
- fs18.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55416
+ function writeHeadroomState(fs19, stateFile, state) {
55417
+ fs19.mkdirp(import_node_path5.default.dirname(stateFile));
55418
+ fs19.writeFilePrivate(stateFile, `${JSON.stringify(state, null, 2)}
55419
55419
  `);
55420
55420
  }
55421
55421
  function headroomAllowlist(providers) {
@@ -55435,14 +55435,14 @@ function headroomUpstreams(providers, frontDoorOrigin2) {
55435
55435
  function hashAllowlist(allowlist) {
55436
55436
  return (0, import_node_crypto2.createHash)("sha256").update(allowlist.join("\n")).digest("hex");
55437
55437
  }
55438
- function readAllProviders(fs18, providersDir) {
55438
+ function readAllProviders(fs19, providersDir) {
55439
55439
  const result = [];
55440
- for (const name of fs18.readdir(providersDir)) {
55440
+ for (const name of fs19.readdir(providersDir)) {
55441
55441
  if (!name.endsWith(".json")) {
55442
55442
  continue;
55443
55443
  }
55444
55444
  try {
55445
- const parsed = parseJson(fs18.readFileUtf8(import_node_path5.default.join(providersDir, name)), ProviderSchema);
55445
+ const parsed = parseJson(fs19.readFileUtf8(import_node_path5.default.join(providersDir, name)), ProviderSchema);
55446
55446
  if (parsed !== void 0) {
55447
55447
  result.push({ name: name.slice(0, -".json".length), provider: parsed });
55448
55448
  }
@@ -55452,22 +55452,22 @@ function readAllProviders(fs18, providersDir) {
55452
55452
  }
55453
55453
  return result;
55454
55454
  }
55455
- function writeSession(fs18, sessionsDir, session) {
55456
- fs18.mkdirp(sessionsDir);
55457
- fs18.writeFileUtf8(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55455
+ function writeSession(fs19, sessionsDir, session) {
55456
+ fs19.mkdirp(sessionsDir);
55457
+ fs19.writeFileUtf8(import_node_path5.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
55458
55458
  `);
55459
55459
  }
55460
- function removeSession(fs18, sessionsDir, pid) {
55461
- fs18.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
55460
+ function removeSession(fs19, sessionsDir, pid) {
55461
+ fs19.removeRecursive(import_node_path5.default.join(sessionsDir, `${String(pid)}.json`));
55462
55462
  }
55463
- function listSessions(fs18, sessionsDir) {
55463
+ function listSessions(fs19, sessionsDir) {
55464
55464
  const sessions = [];
55465
- for (const name of fs18.readdir(sessionsDir)) {
55465
+ for (const name of fs19.readdir(sessionsDir)) {
55466
55466
  if (!name.endsWith(".json")) {
55467
55467
  continue;
55468
55468
  }
55469
55469
  try {
55470
- const parsed = parseJson(fs18.readFileUtf8(import_node_path5.default.join(sessionsDir, name)), HeadroomSessionSchema);
55470
+ const parsed = parseJson(fs19.readFileUtf8(import_node_path5.default.join(sessionsDir, name)), HeadroomSessionSchema);
55471
55471
  if (parsed !== void 0) {
55472
55472
  sessions.push(parsed);
55473
55473
  }
@@ -55477,22 +55477,22 @@ function listSessions(fs18, sessionsDir) {
55477
55477
  }
55478
55478
  return sessions.sort((a2, b) => a2.pid - b.pid);
55479
55479
  }
55480
- function sessionsForSupervisor(fs18, sessionsDir, supervisorPid) {
55481
- return listSessions(fs18, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
55480
+ function sessionsForSupervisor(fs19, sessionsDir, supervisorPid) {
55481
+ return listSessions(fs19, sessionsDir).filter((session) => session.supervisorPid === supervisorPid);
55482
55482
  }
55483
- function pruneDeadSessions(fs18, sessionsDir, isRunning) {
55483
+ function pruneDeadSessions(fs19, sessionsDir, isRunning) {
55484
55484
  const removed = [];
55485
- for (const session of listSessions(fs18, sessionsDir)) {
55485
+ for (const session of listSessions(fs19, sessionsDir)) {
55486
55486
  if (!isRunning(session.pid)) {
55487
- removeSession(fs18, sessionsDir, session.pid);
55487
+ removeSession(fs19, sessionsDir, session.pid);
55488
55488
  removed.push(session.pid);
55489
55489
  }
55490
55490
  }
55491
55491
  return removed;
55492
55492
  }
55493
- function readStartLock(fs18, lockFile) {
55493
+ function readStartLock(fs19, lockFile) {
55494
55494
  try {
55495
- return parseJson(fs18.readFileUtf8(lockFile), HeadroomLockSchema);
55495
+ return parseJson(fs19.readFileUtf8(lockFile), HeadroomLockSchema);
55496
55496
  } catch {
55497
55497
  return void 0;
55498
55498
  }
@@ -55783,10 +55783,12 @@ function detachedDaemonSpawnOptions(logFd, env) {
55783
55783
  return { detached: true, stdio: ["ignore", logFd, logFd], env };
55784
55784
  }
55785
55785
  function spawnDetachedSupervisor(paths, subcommand, logPath) {
55786
+ return spawnDetachedDaemon(selfInvocation([subcommand]), paths, subcommand, logPath);
55787
+ }
55788
+ function spawnDetachedDaemon(invocation, paths, subcommand, logPath) {
55786
55789
  import_node_fs3.default.mkdirSync(import_node_path6.default.dirname(logPath), { recursive: true });
55787
55790
  const logFd = import_node_fs3.default.openSync(logPath, "a");
55788
55791
  try {
55789
- const invocation = selfInvocation([subcommand]);
55790
55792
  const child = (0, import_node_child_process2.spawn)(invocation.command, invocation.args, detachedDaemonSpawnOptions(logFd, { ...process.env, AGENT_SHIM_HOME: paths.root }));
55791
55793
  child.unref();
55792
55794
  if (child.pid === void 0) {
@@ -55797,8 +55799,8 @@ function spawnDetachedSupervisor(paths, subcommand, logPath) {
55797
55799
  import_node_fs3.default.closeSync(logFd);
55798
55800
  }
55799
55801
  }
55800
- function spawnHeadroomSupervisor(paths) {
55801
- return spawnDetachedSupervisor(paths, "__headroom-supervisor", paths.headroomLogPath);
55802
+ function spawnHeadroomSupervisor(paths, spawnDaemon) {
55803
+ return spawnDaemon(paths, "__headroom-supervisor", paths.headroomLogPath);
55802
55804
  }
55803
55805
  async function realIsPortFree(port) {
55804
55806
  return await new Promise((resolve) => {
@@ -55815,7 +55817,7 @@ async function realIsPortFree(port) {
55815
55817
  });
55816
55818
  });
55817
55819
  }
55818
- function realHeadroomPort(paths) {
55820
+ function realHeadroomPort(paths, options) {
55819
55821
  return {
55820
55822
  ensure: () => {
55821
55823
  const up = ensureHeadroom({
@@ -55827,12 +55829,12 @@ function realHeadroomPort(paths) {
55827
55829
  isRunning: realIsProcessRunning,
55828
55830
  now: () => Date.now(),
55829
55831
  sleep: realSleepSync,
55830
- spawnSupervisor: spawnHeadroomSupervisor
55832
+ spawnSupervisor: (layout) => spawnHeadroomSupervisor(layout, options.spawnDaemon)
55831
55833
  }
55832
55834
  });
55833
55835
  return {
55834
55836
  port: up.port,
55835
- projectId: resolveGitRoot(realRunPort, process.cwd()) ?? process.cwd()
55837
+ projectId: resolveGitRoot(realRunPort, options.cwd) ?? options.cwd
55836
55838
  };
55837
55839
  },
55838
55840
  release: () => {
@@ -57521,8 +57523,8 @@ function decideConfigProfile(params) {
57521
57523
  }
57522
57524
  return { source: "none" };
57523
57525
  }
57524
- function loadIdentity(identitiesDir, name, fs18) {
57525
- return loadConfigFile(import_node_path8.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs18.readConfigFile);
57526
+ function loadIdentity(identitiesDir, name, fs19) {
57527
+ return loadConfigFile(import_node_path8.default.join(identitiesDir, name, "identity.json"), IdentitySchema, fs19.readConfigFile);
57526
57528
  }
57527
57529
 
57528
57530
  // src/configProfilesStore.ts
@@ -59109,8 +59111,8 @@ var FarmManifestSchema = external_exports.strictObject({
59109
59111
  materialised: external_exports.array(external_exports.string()),
59110
59112
  links: external_exports.array(external_exports.strictObject({ rel: external_exports.string(), target: external_exports.string() }))
59111
59113
  });
59112
- function readFarmManifest(fs18, farmRoot) {
59113
- const raw = fs18.readFileUtf8(import_node_path16.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs18.readFileUtf8(import_node_path16.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
59114
+ function readFarmManifest(fs19, farmRoot) {
59115
+ const raw = fs19.readFileUtf8(import_node_path16.default.join(farmRoot, FARM_MANIFEST_FILENAME)) ?? fs19.readFileUtf8(import_node_path16.default.join(farmRoot, LEGACY_FARM_MANIFEST_FILENAME));
59114
59116
  if (raw === void 0) {
59115
59117
  return void 0;
59116
59118
  }
@@ -59168,9 +59170,9 @@ function buildEntryFacts(params) {
59168
59170
  entries
59169
59171
  };
59170
59172
  }
59171
- function listSubtree(fs18, root, rel) {
59173
+ function listSubtree(fs19, root, rel) {
59172
59174
  const absolute = import_node_path16.default.join(root, rel);
59173
- const stat = fs18.lstat(absolute);
59175
+ const stat = fs19.lstat(absolute);
59174
59176
  if (stat === void 0) {
59175
59177
  return [];
59176
59178
  }
@@ -59178,10 +59180,10 @@ function listSubtree(fs18, root, rel) {
59178
59180
  return [{ rel, kind: "symlink" }];
59179
59181
  }
59180
59182
  if (stat.kind === "dir") {
59181
- const children = [...fs18.readdir(absolute)].sort().flatMap((name) => listSubtree(fs18, root, `${rel}/${name}`));
59183
+ const children = [...fs19.readdir(absolute)].sort().flatMap((name) => listSubtree(fs19, root, `${rel}/${name}`));
59182
59184
  return [{ rel, kind: "dir" }, ...children];
59183
59185
  }
59184
- const contentHash = fs18.hashFile(absolute);
59186
+ const contentHash = fs19.hashFile(absolute);
59185
59187
  return [{ rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } }];
59186
59188
  }
59187
59189
  function topLevelScopeRoots(roots) {
@@ -59195,25 +59197,25 @@ function topLevelScopeRoots(roots) {
59195
59197
  }
59196
59198
  return kept;
59197
59199
  }
59198
- function reconciliationScope(fs18, farmRoot, manifest) {
59200
+ function reconciliationScope(fs19, farmRoot, manifest) {
59199
59201
  if (manifest !== void 0) {
59200
59202
  return topLevelScopeRoots(manifest.materialised);
59201
59203
  }
59202
- return [...fs18.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs18.lstat(import_node_path16.default.join(farmRoot, name))?.kind === "dir").sort();
59204
+ return [...fs19.readdir(farmRoot)].filter((name) => name !== FARM_MANIFEST_FILENAME && name !== LEGACY_FARM_MANIFEST_FILENAME && fs19.lstat(import_node_path16.default.join(farmRoot, name))?.kind === "dir").sort();
59203
59205
  }
59204
- function collectFarmListing(fs18, farmRoot, scopeRoots) {
59205
- return scopeRoots.flatMap((root) => listSubtree(fs18, farmRoot, root));
59206
+ function collectFarmListing(fs19, farmRoot, scopeRoots) {
59207
+ return scopeRoots.flatMap((root) => listSubtree(fs19, farmRoot, root));
59206
59208
  }
59207
- function collectCanonicalCounterparts(fs18, claudeHome, farmListing) {
59209
+ function collectCanonicalCounterparts(fs19, claudeHome, farmListing) {
59208
59210
  const out = [];
59209
59211
  for (const entry of farmListing) {
59210
59212
  const absolute = import_node_path16.default.join(claudeHome, entry.rel);
59211
- const stat = fs18.lstat(absolute);
59213
+ const stat = fs19.lstat(absolute);
59212
59214
  if (stat === void 0) {
59213
59215
  continue;
59214
59216
  }
59215
59217
  if (stat.kind === "file") {
59216
- const contentHash = fs18.hashFile(absolute);
59218
+ const contentHash = fs19.hashFile(absolute);
59217
59219
  out.push({ rel: entry.rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } });
59218
59220
  continue;
59219
59221
  }
@@ -60455,7 +60457,7 @@ async function resolveFarmConflicts(params) {
60455
60457
  return { resolved, autoResolved, removed, retained };
60456
60458
  }
60457
60459
 
60458
- // src/cli/parsers.ts
60460
+ // src/cli/pairs.ts
60459
60461
  function splitCommas(input2) {
60460
60462
  if (input2 === "") {
60461
60463
  return [];
@@ -60489,6 +60491,8 @@ function parseBoolPairList(input2) {
60489
60491
  }
60490
60492
  return result;
60491
60493
  }
60494
+
60495
+ // src/cli/parsers.ts
60492
60496
  function asInvalidArgument(parse3) {
60493
60497
  try {
60494
60498
  return parse3();
@@ -60985,7 +60989,7 @@ function registerIdentityCommand(program2, deps) {
60985
60989
  // package.json
60986
60990
  var package_default = {
60987
60991
  name: "agent-shim",
60988
- version: "7.12.1",
60992
+ version: "7.13.0",
60989
60993
  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.",
60990
60994
  license: "MIT",
60991
60995
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -61307,12 +61311,12 @@ function isIdentityName(name) {
61307
61311
  function claudeJsonPath(identitiesDir, identity) {
61308
61312
  return import_node_path21.default.join(identitiesDir, identity, CLAUDE_JSON);
61309
61313
  }
61310
- function readAccountMetadata(fs18, identitiesDir, identity) {
61314
+ function readAccountMetadata(fs19, identitiesDir, identity) {
61311
61315
  if (!isIdentityName(identity)) {
61312
61316
  throw new Error(`"${identity}" is not a valid identity name.`);
61313
61317
  }
61314
61318
  const file2 = claudeJsonPath(identitiesDir, identity);
61315
- const raw = fs18.readFileUtf8(file2);
61319
+ const raw = fs19.readFileUtf8(file2);
61316
61320
  if (raw === void 0) {
61317
61321
  return void 0;
61318
61322
  }
@@ -61342,19 +61346,19 @@ function readAccountMetadata(fs18, identitiesDir, identity) {
61342
61346
  }
61343
61347
  return account.data;
61344
61348
  }
61345
- function createAccountReader(fs18, identitiesDir) {
61349
+ function createAccountReader(fs19, identitiesDir) {
61346
61350
  const cache = /* @__PURE__ */ new Map();
61347
61351
  return (identity) => {
61348
61352
  if (!isIdentityName(identity)) {
61349
61353
  throw new Error(`"${identity}" is not a valid identity name.`);
61350
61354
  }
61351
- const stat = fs18.lstat(claudeJsonPath(identitiesDir, identity));
61355
+ const stat = fs19.lstat(claudeJsonPath(identitiesDir, identity));
61352
61356
  const stamp = stat === void 0 ? "absent" : `${String(stat.mtimeMs)}:${String(stat.sizeBytes)}`;
61353
61357
  const cached2 = cache.get(identity);
61354
61358
  if (cached2?.stamp === stamp) {
61355
61359
  return cached2.account;
61356
61360
  }
61357
- const account = readAccountMetadata(fs18, identitiesDir, identity);
61361
+ const account = readAccountMetadata(fs19, identitiesDir, identity);
61358
61362
  cache.set(identity, { stamp, account });
61359
61363
  return account;
61360
61364
  };
@@ -62122,8 +62126,8 @@ function segmentDay(epochMs) {
62122
62126
  function segmentName(day, pid) {
62123
62127
  return `${day}.${String(pid)}.jsonl`;
62124
62128
  }
62125
- function listLogSegments(fs18, logDir) {
62126
- return fs18.readdir(logDir).flatMap((name) => {
62129
+ function listLogSegments(fs19, logDir) {
62130
+ return fs19.readdir(logDir).flatMap((name) => {
62127
62131
  const match = SEGMENT_RE.exec(name);
62128
62132
  const day = match?.[1];
62129
62133
  if (day === void 0) {
@@ -62132,15 +62136,15 @@ function listLogSegments(fs18, logDir) {
62132
62136
  return [{ name, day, endsAt: Date.parse(`${day}T00:00:00.000Z`) + DAY_MS }];
62133
62137
  }).sort((left, right) => left.day.localeCompare(right.day) || left.name.localeCompare(right.name));
62134
62138
  }
62135
- function readUsageLog(fs18, logDir, options = {}) {
62139
+ function readUsageLog(fs19, logDir, options = {}) {
62136
62140
  const { sinceMs } = options;
62137
62141
  const records = [];
62138
62142
  let invalidLines = 0;
62139
- for (const segment of listLogSegments(fs18, logDir)) {
62143
+ for (const segment of listLogSegments(fs19, logDir)) {
62140
62144
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
62141
62145
  continue;
62142
62146
  }
62143
- const contents = fs18.readFileUtf8(import_node_path22.default.join(logDir, segment.name));
62147
+ const contents = fs19.readFileUtf8(import_node_path22.default.join(logDir, segment.name));
62144
62148
  if (contents === void 0) {
62145
62149
  continue;
62146
62150
  }
@@ -62184,9 +62188,9 @@ function snapshotPath(snapshotsDir, identity) {
62184
62188
  }
62185
62189
  return import_node_path22.default.join(snapshotsDir, `${identity}.json`);
62186
62190
  }
62187
- function readUsageSnapshot(fs18, snapshotsDir, identity) {
62191
+ function readUsageSnapshot(fs19, snapshotsDir, identity) {
62188
62192
  const file2 = snapshotPath(snapshotsDir, identity);
62189
- const raw = fs18.readFileUtf8(file2);
62193
+ const raw = fs19.readFileUtf8(file2);
62190
62194
  if (raw === void 0) {
62191
62195
  return void 0;
62192
62196
  }
@@ -62202,8 +62206,8 @@ function readUsageSnapshot(fs18, snapshotsDir, identity) {
62202
62206
  }
62203
62207
  return snapshot.data;
62204
62208
  }
62205
- function listUsageSnapshots(fs18, snapshotsDir) {
62206
- return fs18.readdir(snapshotsDir).flatMap((name) => {
62209
+ function listUsageSnapshots(fs19, snapshotsDir) {
62210
+ return fs19.readdir(snapshotsDir).flatMap((name) => {
62207
62211
  if (!name.endsWith(".json")) {
62208
62212
  return [];
62209
62213
  }
@@ -62211,7 +62215,7 @@ function listUsageSnapshots(fs18, snapshotsDir) {
62211
62215
  if (!isIdentityName(identity)) {
62212
62216
  return [];
62213
62217
  }
62214
- const snapshot = readUsageSnapshot(fs18, snapshotsDir, identity);
62218
+ const snapshot = readUsageSnapshot(fs19, snapshotsDir, identity);
62215
62219
  return snapshot === void 0 ? [] : [snapshot];
62216
62220
  }).sort((left, right) => left.identity.localeCompare(right.identity));
62217
62221
  }
@@ -62270,11 +62274,11 @@ var import_node_path23 = __toESM(require("node:path"), 1);
62270
62274
  var DAY_MS2 = 864e5;
62271
62275
  var DAYS_IN_WEEK = 7;
62272
62276
  var USAGE_RETENTION_MS = DAYS_IN_WEEK * DAY_MS2;
62273
- function pruneUsageLog(fs18, logDir, nowMs) {
62277
+ function pruneUsageLog(fs19, logDir, nowMs) {
62274
62278
  const cutoff = nowMs - USAGE_RETENTION_MS;
62275
- for (const segment of listLogSegments(fs18, logDir)) {
62279
+ for (const segment of listLogSegments(fs19, logDir)) {
62276
62280
  if (segment.endsAt <= cutoff) {
62277
- fs18.removeRecursive(import_node_path23.default.join(logDir, segment.name));
62281
+ fs19.removeRecursive(import_node_path23.default.join(logDir, segment.name));
62278
62282
  }
62279
62283
  }
62280
62284
  }
@@ -62303,7 +62307,7 @@ function foldProviderState(current, record2) {
62303
62307
  };
62304
62308
  }
62305
62309
  function createUsageStore(deps) {
62306
- const { fs: fs18, paths } = deps;
62310
+ const { fs: fs19, paths } = deps;
62307
62311
  let prunedDay;
62308
62312
  const rewriteSnapshot = (identity, fold) => {
62309
62313
  if (!isIdentityName(identity)) {
@@ -62312,7 +62316,7 @@ function createUsageStore(deps) {
62312
62316
  }
62313
62317
  let current;
62314
62318
  try {
62315
- current = readUsageSnapshot(fs18, paths.usageSnapshotsDir, identity);
62319
+ current = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
62316
62320
  } catch (error62) {
62317
62321
  if (!(error62 instanceof UsageSnapshotError)) {
62318
62322
  throw error62;
@@ -62339,8 +62343,8 @@ function createUsageStore(deps) {
62339
62343
  ...account === void 0 ? {} : { account },
62340
62344
  providers
62341
62345
  });
62342
- fs18.mkdirPrivate(paths.usageSnapshotsDir);
62343
- fs18.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
62346
+ fs19.mkdirPrivate(paths.usageSnapshotsDir);
62347
+ fs19.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
62344
62348
  `);
62345
62349
  return true;
62346
62350
  };
@@ -62348,14 +62352,14 @@ function createUsageStore(deps) {
62348
62352
  record: (input2) => {
62349
62353
  const record2 = UsageRecordSchema.parse(input2);
62350
62354
  const nowMs = deps.now();
62351
- fs18.mkdirPrivate(paths.usageDir);
62352
- fs18.mkdirPrivate(paths.usageLogDir);
62355
+ fs19.mkdirPrivate(paths.usageDir);
62356
+ fs19.mkdirPrivate(paths.usageLogDir);
62353
62357
  const day = segmentDay(nowMs);
62354
62358
  if (prunedDay !== day) {
62355
- pruneUsageLog(fs18, paths.usageLogDir, nowMs);
62359
+ pruneUsageLog(fs19, paths.usageLogDir, nowMs);
62356
62360
  prunedDay = day;
62357
62361
  }
62358
- fs18.appendFilePrivate(import_node_path23.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
62362
+ fs19.appendFilePrivate(import_node_path23.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
62359
62363
  `);
62360
62364
  if (record2.identity !== void 0) {
62361
62365
  rewriteSnapshot(record2.identity, (current) => ({ ...current?.providers, [record2.provider]: foldProviderState(current?.providers[record2.provider], record2) }));
@@ -62382,14 +62386,14 @@ var PicksFileSchema = external_exports.strictObject({
62382
62386
  function errorMessage(error62) {
62383
62387
  return error62 instanceof Error ? error62.message : String(error62);
62384
62388
  }
62385
- function loadPoolMembers(fs18, paths, identities, nowMs) {
62389
+ function loadPoolMembers(fs19, paths, identities, nowMs) {
62386
62390
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
62387
- const log = readUsageLog(fs18, paths.usageLogDir, { sinceMs: windowStartMs });
62391
+ const log = readUsageLog(fs19, paths.usageLogDir, { sinceMs: windowStartMs });
62388
62392
  return identities.map((identity) => {
62389
62393
  const records = log.records.filter((record2) => record2.identity === identity && record2.provider === ANTHROPIC_PROVIDER && Date.parse(record2.at) >= windowStartMs);
62390
62394
  try {
62391
- const snapshot = readUsageSnapshot(fs18, paths.usageSnapshotsDir, identity);
62392
- const account = readAccountMetadata(fs18, paths.identitiesDir, identity) ?? snapshot?.account;
62395
+ const snapshot = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
62396
+ const account = readAccountMetadata(fs19, paths.identitiesDir, identity) ?? snapshot?.account;
62393
62397
  return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
62394
62398
  } catch (error62) {
62395
62399
  if (error62 instanceof UsageSnapshotError || error62 instanceof AccountMetadataError) {
@@ -62407,9 +62411,9 @@ function rankPoolFromStore(params) {
62407
62411
  ...params.sticky === void 0 ? {} : { sticky: params.sticky }
62408
62412
  });
62409
62413
  }
62410
- function readPicksFile(fs18, file2) {
62414
+ function readPicksFile(fs19, file2) {
62411
62415
  const empty = { schemaVersion: SCHEMA_VERSION, picks: {} };
62412
- const raw = fs18.readFileUtf8(file2);
62416
+ const raw = fs19.readFileUtf8(file2);
62413
62417
  if (raw === void 0) {
62414
62418
  return { file: empty };
62415
62419
  }
@@ -62422,17 +62426,17 @@ function readPicksFile(fs18, file2) {
62422
62426
  const result = PicksFileSchema.safeParse(parsed);
62423
62427
  return result.success ? { file: result.data } : { file: empty, problem: `${file2} is not a picks file this agent-shim can read` };
62424
62428
  }
62425
- function readStickyPick(fs18, picksFile, directory) {
62426
- const read = readPicksFile(fs18, picksFile);
62429
+ function readStickyPick(fs19, picksFile, directory) {
62430
+ const read = readPicksFile(fs19, picksFile);
62427
62431
  const entry = read.file.picks[directory];
62428
62432
  return { ...entry === void 0 ? {} : { sticky: entry }, ...read.problem === void 0 ? {} : { problem: read.problem } };
62429
62433
  }
62430
- function recordStickyPick(fs18, picksFile, directory, identity, nowMs) {
62431
- const current = readPicksFile(fs18, picksFile).file.picks;
62434
+ function recordStickyPick(fs19, picksFile, directory, identity, nowMs) {
62435
+ const current = readPicksFile(fs19, picksFile).file.picks;
62432
62436
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
62433
62437
  const next = { schemaVersion: SCHEMA_VERSION, picks: { ...Object.fromEntries(kept), [directory]: { identity, at: new Date(nowMs).toISOString() } } };
62434
- fs18.mkdirPrivate(import_node_path24.default.dirname(picksFile));
62435
- fs18.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
62438
+ fs19.mkdirPrivate(import_node_path24.default.dirname(picksFile));
62439
+ fs19.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
62436
62440
  `);
62437
62441
  }
62438
62442
 
@@ -62440,8 +62444,8 @@ function recordStickyPick(fs18, picksFile, directory, identity, nowMs) {
62440
62444
  var RESUME_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c", "--resume", "-r"]);
62441
62445
  var TERMINATOR = "--";
62442
62446
  var REASONS_LOGGED = 3;
62443
- function splitMembers(pool, paths, fs18) {
62444
- const exists = (name) => loadIdentity(paths.identitiesDir, name, fs18) !== void 0;
62447
+ function splitMembers(pool, paths, fs19) {
62448
+ const exists = (name) => loadIdentity(paths.identitiesDir, name, fs19) !== void 0;
62445
62449
  return { present: pool.identities.filter(exists), missing: pool.identities.filter((name) => !exists(name)) };
62446
62450
  }
62447
62451
  function isResuming(passthrough) {
@@ -63284,10 +63288,10 @@ var FrontDoorStateSchema = external_exports.strictObject({
63284
63288
  /** The last fatal error, kept across shutdowns so `frontdoor status` can explain a front door that is not running. */
63285
63289
  lastError: external_exports.string().optional()
63286
63290
  });
63287
- function readFrontDoorState(fs18, stateFile) {
63291
+ function readFrontDoorState(fs19, stateFile) {
63288
63292
  let raw;
63289
63293
  try {
63290
- raw = fs18.readFileUtf8(stateFile);
63294
+ raw = fs19.readFileUtf8(stateFile);
63291
63295
  } catch {
63292
63296
  return void 0;
63293
63297
  }
@@ -63301,28 +63305,28 @@ function readFrontDoorState(fs18, stateFile) {
63301
63305
  return void 0;
63302
63306
  }
63303
63307
  }
63304
- function writeFrontDoorState(fs18, stateFile, state) {
63305
- fs18.mkdirp(import_node_path28.default.dirname(stateFile));
63306
- fs18.writeFileUtf8(stateFile, `${JSON.stringify(state, null, 2)}
63308
+ function writeFrontDoorState(fs19, stateFile, state) {
63309
+ fs19.mkdirp(import_node_path28.default.dirname(stateFile));
63310
+ fs19.writeFileUtf8(stateFile, `${JSON.stringify(state, null, 2)}
63307
63311
  `);
63308
63312
  }
63309
63313
  function frontDoorOrigin(state) {
63310
63314
  const port = state?.directPort ?? state?.lastDirectPort;
63311
63315
  return port === void 0 ? void 0 : `http://127.0.0.1:${String(port)}`;
63312
63316
  }
63313
- function writeFrontDoorSession(fs18, sessionsDir, session) {
63314
- fs18.mkdirPrivate(sessionsDir);
63315
- fs18.writeFilePrivate(import_node_path28.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
63317
+ function writeFrontDoorSession(fs19, sessionsDir, session) {
63318
+ fs19.mkdirPrivate(sessionsDir);
63319
+ fs19.writeFilePrivate(import_node_path28.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
63316
63320
  `);
63317
63321
  }
63318
- function listFrontDoorSessions(fs18, sessionsDir) {
63322
+ function listFrontDoorSessions(fs19, sessionsDir) {
63319
63323
  const sessions = [];
63320
- for (const name of fs18.readdir(sessionsDir)) {
63324
+ for (const name of fs19.readdir(sessionsDir)) {
63321
63325
  if (!name.endsWith(".json")) {
63322
63326
  continue;
63323
63327
  }
63324
63328
  try {
63325
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs18.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63329
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63326
63330
  if (parsed.success) {
63327
63331
  sessions.push({ pid: parsed.data.pid, startedAt: parsed.data.startedAt });
63328
63332
  }
@@ -63332,27 +63336,27 @@ function listFrontDoorSessions(fs18, sessionsDir) {
63332
63336
  }
63333
63337
  return sessions.sort((a2, b) => a2.pid - b.pid);
63334
63338
  }
63335
- function removeFrontDoorSession(fs18, sessionsDir, pid) {
63336
- fs18.removeRecursive(import_node_path28.default.join(sessionsDir, `${String(pid)}.json`));
63339
+ function removeFrontDoorSession(fs19, sessionsDir, pid) {
63340
+ fs19.removeRecursive(import_node_path28.default.join(sessionsDir, `${String(pid)}.json`));
63337
63341
  }
63338
- function pruneDeadFrontDoorSessions(fs18, sessionsDir, isRunning) {
63342
+ function pruneDeadFrontDoorSessions(fs19, sessionsDir, isRunning) {
63339
63343
  const removed = [];
63340
- for (const session of listFrontDoorSessions(fs18, sessionsDir)) {
63344
+ for (const session of listFrontDoorSessions(fs19, sessionsDir)) {
63341
63345
  if (!isRunning(session.pid)) {
63342
- removeFrontDoorSession(fs18, sessionsDir, session.pid);
63346
+ removeFrontDoorSession(fs19, sessionsDir, session.pid);
63343
63347
  removed.push(session.pid);
63344
63348
  }
63345
63349
  }
63346
63350
  return removed;
63347
63351
  }
63348
- function liveSessionTokens(fs18, sessionsDir) {
63352
+ function liveSessionTokens(fs19, sessionsDir) {
63349
63353
  const tokens = /* @__PURE__ */ new Set();
63350
- for (const name of fs18.readdir(sessionsDir)) {
63354
+ for (const name of fs19.readdir(sessionsDir)) {
63351
63355
  if (!name.endsWith(".json")) {
63352
63356
  continue;
63353
63357
  }
63354
63358
  try {
63355
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs18.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63359
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63356
63360
  if (parsed.success) {
63357
63361
  tokens.add(parsed.data.token);
63358
63362
  }
@@ -63717,8 +63721,8 @@ function registerCodexCommand(program2, deps) {
63717
63721
  }
63718
63722
 
63719
63723
  // src/frontdoor/commands.ts
63720
- var import_node_crypto13 = require("node:crypto");
63721
- var import_node_path31 = __toESM(require("node:path"), 1);
63724
+ var import_node_crypto11 = require("node:crypto");
63725
+ var import_node_path30 = __toESM(require("node:path"), 1);
63722
63726
  var import_node_fs11 = __toESM(require("node:fs"), 1);
63723
63727
 
63724
63728
  // src/frontdoor/custody.ts
@@ -64324,8 +64328,8 @@ var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
64324
64328
  var FRONTDOOR_POLL_MS = 1e3;
64325
64329
  var MS_PER_MINUTE = 6e4;
64326
64330
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
64327
- const { fs: fs18, paths } = ports;
64328
- const previous = readFrontDoorState(fs18, paths.frontdoorStateFile);
64331
+ const { fs: fs19, paths } = ports;
64332
+ const previous = readFrontDoorState(fs19, paths.frontdoorStateFile);
64329
64333
  let lastPort = previous?.lastPort;
64330
64334
  let lastConnectPort = previous?.lastConnectPort;
64331
64335
  let lastDirectPort = previous?.lastDirectPort;
@@ -64335,12 +64339,12 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64335
64339
  ...lastDirectPort === void 0 ? {} : { lastDirectPort }
64336
64340
  });
64337
64341
  const fail = (message) => {
64338
- writeFrontDoorState(fs18, paths.frontdoorStateFile, { lastError: message, ...sticky() });
64339
- fs18.removeRecursive(paths.frontdoorLockFile);
64342
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { lastError: message, ...sticky() });
64343
+ fs19.removeRecursive(paths.frontdoorLockFile);
64340
64344
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
64341
64345
  return 1;
64342
64346
  };
64343
- writeFrontDoorState(fs18, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
64347
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
64344
64348
  const previousSticky = lastPort;
64345
64349
  let http5;
64346
64350
  try {
@@ -64377,8 +64381,8 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64377
64381
  ports.log(`agent-shim frontdoor supervisor: sticky direct port ${String(previousStickyDirect)} was occupied; moving to ${String(direct.port)} (headroom must be restarted to admit the new address)`);
64378
64382
  }
64379
64383
  lastDirectPort = direct.port;
64380
- writeFrontDoorState(fs18, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http5.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
64381
- fs18.removeRecursive(paths.frontdoorLockFile);
64384
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http5.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
64385
+ fs19.removeRecursive(paths.frontdoorLockFile);
64382
64386
  ports.log(`agent-shim frontdoor supervisor ${String(ports.ownPid)}: front door on 127.0.0.1:${String(http5.port)}, CONNECT surface on 127.0.0.1:${String(connect3.port)}`);
64383
64387
  let idleSince;
64384
64388
  let ticks = 0;
@@ -64387,15 +64391,15 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64387
64391
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
64388
64392
  }
64389
64393
  ticks += 1;
64390
- pruneDeadFrontDoorSessions(fs18, paths.frontdoorSessionsDir, ports.isRunning);
64391
- if (listFrontDoorSessions(fs18, paths.frontdoorSessionsDir).length === 0) {
64394
+ pruneDeadFrontDoorSessions(fs19, paths.frontdoorSessionsDir, ports.isRunning);
64395
+ if (listFrontDoorSessions(fs19, paths.frontdoorSessionsDir).length === 0) {
64392
64396
  idleSince ??= ports.now();
64393
64397
  if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE) {
64394
64398
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
64395
64399
  await direct.close();
64396
64400
  await connect3.close();
64397
64401
  await http5.close();
64398
- writeFrontDoorState(fs18, paths.frontdoorStateFile, sticky());
64402
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, sticky());
64399
64403
  return 0;
64400
64404
  }
64401
64405
  } else {
@@ -64945,80 +64949,6 @@ function realConnectEffects() {
64945
64949
  };
64946
64950
  }
64947
64951
 
64948
- // src/frontdoor/ensure.ts
64949
- var import_node_crypto10 = require("node:crypto");
64950
- var FRONTDOOR_START_TIMEOUT_MS = 3e4;
64951
- var FRONTDOOR_LAUNCHER_POLL_MS = 100;
64952
- var FrontDoorStartError = class extends CliError {
64953
- constructor(message) {
64954
- super(message);
64955
- this.name = "FrontDoorStartError";
64956
- }
64957
- };
64958
- function ensureFrontDoor(params) {
64959
- const { paths, ports } = params;
64960
- const deadline = ports.now() + FRONTDOOR_START_TIMEOUT_MS;
64961
- let spawned = false;
64962
- let replaced = false;
64963
- const distrusted = /* @__PURE__ */ new Set();
64964
- let lastRejection;
64965
- for (; ; ) {
64966
- const state = readFrontDoorState(ports.fs, paths.frontdoorStateFile);
64967
- const supervisorPid = state?.supervisorPid;
64968
- if (supervisorPid !== void 0 && !distrusted.has(supervisorPid) && ports.isRunning(supervisorPid)) {
64969
- if (state?.port !== void 0 && state.connectPort !== void 0) {
64970
- const verdict = ports.verifyListener(state.port);
64971
- if (verdict.ok && (state.protocol ?? 0) < FRONT_DOOR_PROTOCOL && !replaced) {
64972
- ports.stopSupervisor(supervisorPid);
64973
- while (ports.isRunning(supervisorPid)) {
64974
- if (ports.now() >= deadline) {
64975
- throw new FrontDoorStartError(`agent-shim: the front door (pid ${String(supervisorPid)}, protocol ${String(state.protocol ?? 0)}) is older than this launcher (protocol ${String(FRONT_DOOR_PROTOCOL)}) and did not exit when asked. Daemon log: ${paths.frontdoorLogPath}`);
64976
- }
64977
- ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
64978
- }
64979
- replaced = true;
64980
- continue;
64981
- }
64982
- if (verdict.ok) {
64983
- const token = (0, import_node_crypto10.randomUUID)();
64984
- writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token });
64985
- return { port: state.port, connectPort: state.connectPort, token };
64986
- }
64987
- lastRejection = `the listener on 127.0.0.1:${String(state.port)} (recorded for pid ${String(supervisorPid)}) failed authentication: ${verdict.reason}`;
64988
- if (spawned) {
64989
- throw new FrontDoorStartError(`agent-shim: ${lastRejection}; refusing to send this session's credentials to it. Daemon log: ${paths.frontdoorLogPath}`);
64990
- }
64991
- distrusted.add(supervisorPid);
64992
- continue;
64993
- }
64994
- if (state?.lastError !== void 0) {
64995
- throw new FrontDoorStartError(`agent-shim: the front door reported a fatal error and is not serving: ${state.lastError} (daemon log: ${paths.frontdoorLogPath})`);
64996
- }
64997
- } else if (!spawned) {
64998
- ports.fs.mkdirp(paths.frontdoorDir);
64999
- const created = ports.fs.writeFileExclusive(paths.frontdoorLockFile, `${JSON.stringify({ pid: params.launcherPid, at: ports.now() })}
65000
- `);
65001
- if (created) {
65002
- ports.spawnSupervisor(paths);
65003
- spawned = true;
65004
- } else {
65005
- const lock = readStartLock(ports.fs, paths.frontdoorLockFile);
65006
- if (lock === void 0 || !ports.isRunning(lock.pid)) {
65007
- ports.fs.removeRecursive(paths.frontdoorLockFile);
65008
- continue;
65009
- }
65010
- }
65011
- }
65012
- if (ports.now() >= deadline) {
65013
- const lastError = state?.lastError;
65014
- throw new FrontDoorStartError(
65015
- `agent-shim: the front door did not become ready within ${String(FRONTDOOR_START_TIMEOUT_MS)}ms` + (lastError === void 0 ? "" : ` (last error: ${lastError})`) + (lastRejection === void 0 ? "" : ` (${lastRejection})`) + `. Daemon log: ${paths.frontdoorLogPath}`
65016
- );
65017
- }
65018
- ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
65019
- }
65020
- }
65021
-
65022
64952
  // src/frontdoor/headroomHop.ts
65023
64953
  var http3 = __toESM(require("node:http"), 1);
65024
64954
 
@@ -65411,72 +65341,8 @@ async function serveRouted(request6, deps) {
65411
65341
  }
65412
65342
  }
65413
65343
 
65414
- // src/frontdoor/probe.ts
65415
- var import_node_worker_threads = require("node:worker_threads");
65416
- var PROBE_TIMEOUT_MS = 2e3;
65417
- var PROBE_WAIT_MARGIN_MS = 1e3;
65418
- var REASON_BYTES = 1024;
65419
- var HEADER_SLOTS = 2;
65420
- var INT32_BYTES = 4;
65421
- var VERDICT_PENDING = 0;
65422
- var VERDICT_OK = 1;
65423
- var VERDICT_FAILED = 2;
65424
- var PROBE_SOURCE = `
65425
- const { workerData } = require("node:worker_threads");
65426
- const https = require("node:https");
65427
- const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
65428
- const header = new Int32Array(shared, 0, headerSlots);
65429
- const reason = new Uint8Array(shared, headerSlots * 4);
65430
- let done = false;
65431
- const finish = (verdict, message) => {
65432
- if (done) return;
65433
- done = true;
65434
- const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
65435
- reason.set(bytes);
65436
- Atomics.store(header, 1, bytes.length);
65437
- Atomics.store(header, 0, verdict);
65438
- Atomics.notify(header, 0);
65439
- };
65440
- const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
65441
- let body = "";
65442
- response.setEncoding("utf8");
65443
- response.on("data", (chunk) => { body += chunk; });
65444
- response.on("end", () => {
65445
- if (response.statusCode === 200 && body === "ok") finish(ok, "");
65446
- else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
65447
- });
65448
- response.on("error", (error) => finish(failed, error.message));
65449
- });
65450
- // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
65451
- setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
65452
- request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
65453
- `;
65454
- function probeFrontDoorSync(port, caPem) {
65455
- const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
65456
- const header = new Int32Array(shared, 0, HEADER_SLOTS);
65457
- const worker = new import_node_worker_threads.Worker(PROBE_SOURCE, {
65458
- eval: true,
65459
- workerData: { port, ca: caPem, timeoutMs: PROBE_TIMEOUT_MS, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
65460
- });
65461
- worker.unref();
65462
- try {
65463
- const waited = Atomics.wait(header, 0, VERDICT_PENDING, PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS);
65464
- const verdict = Atomics.load(header, 0);
65465
- if (waited === "timed-out" || verdict === VERDICT_PENDING) {
65466
- return { ok: false, reason: `the probe did not finish within ${String(PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS)}ms` };
65467
- }
65468
- if (verdict === VERDICT_OK) {
65469
- return { ok: true };
65470
- }
65471
- const length = Atomics.load(header, 1);
65472
- return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
65473
- } finally {
65474
- void worker.terminate();
65475
- }
65476
- }
65477
-
65478
65344
  // src/codex/translate.ts
65479
- var import_node_crypto11 = require("node:crypto");
65345
+ var import_node_crypto10 = require("node:crypto");
65480
65346
 
65481
65347
  // src/codex/anthropic.ts
65482
65348
  var TextBlockSchema = external_exports.looseObject({ type: external_exports.literal("text"), text: external_exports.string() });
@@ -65588,7 +65454,7 @@ function shortToolName(name, names) {
65588
65454
  if (name.length <= CODEX_TOOL_NAME_LIMIT) {
65589
65455
  return name;
65590
65456
  }
65591
- const hash2 = (0, import_node_crypto11.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
65457
+ const hash2 = (0, import_node_crypto10.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
65592
65458
  const shortened = `${name.slice(0, CODEX_TOOL_NAME_LIMIT - TOOL_NAME_HASH_CHARS - 1)}_${hash2}`;
65593
65459
  names.set(shortened, name);
65594
65460
  return shortened;
@@ -66429,38 +66295,6 @@ function createProviderRouteResolver(deps) {
66429
66295
  return async (request6) => await Promise.resolve(resolve(request6));
66430
66296
  }
66431
66297
 
66432
- // src/frontdoor/trust.ts
66433
- var import_node_crypto12 = require("node:crypto");
66434
- var import_node_path30 = __toESM(require("node:path"), 1);
66435
- var BUNDLE_NAME_HEX_DIGITS = 16;
66436
- function resolveTrustBundle(params) {
66437
- const { caCertFile, bundlesDir, inherited, fs: fs18 } = params;
66438
- if (inherited === void 0 || inherited === "" || import_node_path30.default.resolve(inherited) === import_node_path30.default.resolve(caCertFile)) {
66439
- return { path: caCertFile };
66440
- }
66441
- const caPem = fs18.readFileUtf8(caCertFile);
66442
- let inheritedPem;
66443
- try {
66444
- inheritedPem = fs18.readFileUtf8(inherited);
66445
- } catch (error62) {
66446
- return {
66447
- path: caCertFile,
66448
- warning: `agent-shim: NODE_EXTRA_CA_CERTS names ${inherited}, which could not be read (${error62 instanceof Error ? error62.message : String(error62)}); the child trusts agent-shim's front-door CA on top of the system store, and nothing from that file`
66449
- };
66450
- }
66451
- if (inheritedPem.includes(caPem.trim())) {
66452
- return { path: inherited };
66453
- }
66454
- const combined = `${inheritedPem.trimEnd()}
66455
- ${caPem}`;
66456
- const bundle = import_node_path30.default.join(bundlesDir, `${(0, import_node_crypto12.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
66457
- if (!fs18.exists(bundle)) {
66458
- fs18.mkdirp(bundlesDir);
66459
- fs18.writeFileAtomic(bundle, combined);
66460
- }
66461
- return { path: bundle };
66462
- }
66463
-
66464
66298
  // src/usage/providerQuota.ts
66465
66299
  var ProviderQuotaError = class extends Error {
66466
66300
  constructor(source, detail) {
@@ -66783,8 +66617,8 @@ function realFrontDoorSupervisorPorts(paths) {
66783
66617
  now: () => Date.now(),
66784
66618
  headroomPort: () => liveHeadroomPort(paths),
66785
66619
  // The per-generation capability the direct listener demands: held only in this process's memory, so a loopback process that discovers the direct port still cannot use it.
66786
- hopSecret: (0, import_node_crypto13.randomUUID)(),
66787
- custody: createCredentialCustody(() => (0, import_node_crypto13.randomUUID)()),
66620
+ hopSecret: (0, import_node_crypto11.randomUUID)(),
66621
+ custody: createCredentialCustody(() => (0, import_node_crypto11.randomUUID)()),
66788
66622
  log
66789
66623
  });
66790
66624
  let ca;
@@ -66821,14 +66655,14 @@ function realFrontDoorSupervisorPorts(paths) {
66821
66655
  },
66822
66656
  startConnectListener: async (preferredPort) => {
66823
66657
  const transparentPort = process.env.AGENT_SHIM_TRANSPARENT_SURFACE === void 0 ? void 0 : Number(process.env.AGENT_SHIM_TRANSPARENT_SURFACE);
66824
- const transparentCapability = transparentPort === void 0 || Number.isNaN(transparentPort) ? void 0 : (0, import_node_crypto13.randomUUID)();
66658
+ const transparentCapability = transparentPort === void 0 || Number.isNaN(transparentPort) ? void 0 : (0, import_node_crypto11.randomUUID)();
66825
66659
  if (transparentCapability !== void 0) {
66826
66660
  writeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, { pid: process.pid, startedAt: Date.now(), token: transparentCapability });
66827
66661
  }
66828
66662
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
66829
66663
  const capture = captureFromEnv(process.env, paths.logsDir);
66830
66664
  if (capture !== void 0) {
66831
- log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path31.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
66665
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path30.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
66832
66666
  }
66833
66667
  const server = await startConnectServer(
66834
66668
  {
@@ -66884,49 +66718,6 @@ function realFrontDoorSupervisorPorts(paths) {
66884
66718
  }
66885
66719
  };
66886
66720
  }
66887
- var realTrustBundleFs = {
66888
- readFileUtf8: (file2) => import_node_fs11.default.readFileSync(file2, "utf8"),
66889
- exists: (file2) => import_node_fs11.default.existsSync(file2),
66890
- mkdirp: (dir) => {
66891
- import_node_fs11.default.mkdirSync(dir, { recursive: true });
66892
- },
66893
- writeFileAtomic: (file2, contents) => {
66894
- realFarmFs.writeFilePrivate(file2, contents);
66895
- }
66896
- };
66897
- function realFrontDoorPort(paths) {
66898
- return {
66899
- ensure: (inheritedExtraCaCerts) => {
66900
- const up = ensureFrontDoor({
66901
- paths,
66902
- launcherPid: process.pid,
66903
- ports: {
66904
- fs: realFarmFs,
66905
- isRunning: realIsProcessRunning,
66906
- now: () => Date.now(),
66907
- sleep: realSleepSync,
66908
- spawnSupervisor: (layout) => spawnDetachedSupervisor(layout, "__frontdoor-supervisor", layout.frontdoorLogPath),
66909
- stopSupervisor: (pid) => {
66910
- process.kill(pid, "SIGTERM");
66911
- },
66912
- // 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.
66913
- verifyListener: (port) => probeFrontDoorSync(port, import_node_fs11.default.readFileSync(paths.frontdoorCaCertFile, "utf8"))
66914
- }
66915
- });
66916
- const trust = resolveTrustBundle({ caCertFile: paths.frontdoorCaCertFile, bundlesDir: paths.frontdoorCaBundlesDir, inherited: inheritedExtraCaCerts, fs: realTrustBundleFs });
66917
- return {
66918
- port: up.port,
66919
- connectPort: up.connectPort,
66920
- trustBundlePath: trust.path,
66921
- ...trust.warning === void 0 ? {} : { trustWarning: trust.warning },
66922
- sessionToken: up.token
66923
- };
66924
- },
66925
- release: () => {
66926
- removeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, process.pid);
66927
- }
66928
- };
66929
- }
66930
66721
  function collectFrontDoorStatus(fsPort, paths, isRunning) {
66931
66722
  const state = readFrontDoorState(fsPort, paths.frontdoorStateFile) ?? {};
66932
66723
  return {
@@ -67279,15 +67070,15 @@ var import_node_child_process4 = require("node:child_process");
67279
67070
 
67280
67071
  // src/identityToken.ts
67281
67072
  var import_node_fs12 = __toESM(require("node:fs"), 1);
67282
- var import_node_path32 = __toESM(require("node:path"), 1);
67073
+ var import_node_path31 = __toESM(require("node:path"), 1);
67283
67074
  var TOKEN_FILE_MODE = 384;
67284
67075
  var TOKEN_DIR_MODE = 448;
67285
67076
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
67286
67077
  function identityTokenDir(paths) {
67287
- return import_node_path32.default.join(paths.root, "credentials");
67078
+ return import_node_path31.default.join(paths.root, "credentials");
67288
67079
  }
67289
67080
  function identityTokenPath(paths, identityName) {
67290
- return import_node_path32.default.join(identityTokenDir(paths), `${identityName}.token`);
67081
+ return import_node_path31.default.join(identityTokenDir(paths), `${identityName}.token`);
67291
67082
  }
67292
67083
  function storeIdentityToken(paths, identityName, raw) {
67293
67084
  const token = raw.trim();
@@ -67298,7 +67089,7 @@ function storeIdentityToken(paths, identityName, raw) {
67298
67089
  import_node_fs12.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
67299
67090
  import_node_fs12.default.chmodSync(dir, TOKEN_DIR_MODE);
67300
67091
  const target = identityTokenPath(paths, identityName);
67301
- const temp = import_node_path32.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
67092
+ const temp = import_node_path31.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
67302
67093
  import_node_fs12.default.writeFileSync(temp, `${token}
67303
67094
  `, { mode: TOKEN_FILE_MODE });
67304
67095
  import_node_fs12.default.renameSync(temp, target);
@@ -67308,7 +67099,7 @@ function storeIdentityToken(paths, identityName, raw) {
67308
67099
  // src/realCredentialCache.ts
67309
67100
  var import_node_child_process3 = require("node:child_process");
67310
67101
  var import_node_fs13 = __toESM(require("node:fs"), 1);
67311
- var import_node_path33 = __toESM(require("node:path"), 1);
67102
+ var import_node_path32 = __toESM(require("node:path"), 1);
67312
67103
  var KEYCHAIN_CACHE_SERVICE = "agent-shim-credential-cache";
67313
67104
  var CACHE_DIR_MODE = 448;
67314
67105
  var CACHE_FILE_MODE = 384;
@@ -67335,8 +67126,8 @@ function security(args, stdin2) {
67335
67126
  return { status: result.status, stdout: result.stdout };
67336
67127
  }
67337
67128
  function createRealCredentialCache(root) {
67338
- const dir = import_node_path33.default.join(root, "credential-cache");
67339
- const filePath = (owner) => import_node_path33.default.join(dir, cacheFileNameFor(owner));
67129
+ const dir = import_node_path32.default.join(root, "credential-cache");
67130
+ const filePath = (owner) => import_node_path32.default.join(dir, cacheFileNameFor(owner));
67340
67131
  return {
67341
67132
  read(store, owner) {
67342
67133
  if (store === "file") {
@@ -67515,7 +67306,7 @@ function subjectName(positional, provider) {
67515
67306
 
67516
67307
  // src/doctorReport.ts
67517
67308
  var import_node_fs14 = __toESM(require("node:fs"), 1);
67518
- var import_node_path34 = __toESM(require("node:path"), 1);
67309
+ var import_node_path33 = __toESM(require("node:path"), 1);
67519
67310
 
67520
67311
  // src/headroom/source.ts
67521
67312
  var GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
@@ -67566,7 +67357,7 @@ function validateJson(schema, input2) {
67566
67357
  return { ok: true, data: result.data };
67567
67358
  }
67568
67359
  function pushPathResolution(push, resolution) {
67569
- const ownDir = import_node_path34.default.dirname(resolution.ownExecutablePath);
67360
+ const ownDir = import_node_path33.default.dirname(resolution.ownExecutablePath);
67570
67361
  switch (resolution.agentShim.status) {
67571
67362
  case "ok":
67572
67363
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -67634,14 +67425,14 @@ function pushProvider(push, entry) {
67634
67425
  }
67635
67426
  function pushLegacyName(push, params) {
67636
67427
  const legacyVariables = Object.keys(params.env).filter((name) => name.startsWith(LEGACY_ENV_PREFIX) && params.env[name] !== void 0).sort();
67637
- if (legacyVariables.length === 0 && import_node_path34.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
67428
+ if (legacyVariables.length === 0 && import_node_path33.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
67638
67429
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
67639
67430
  return;
67640
67431
  }
67641
67432
  for (const name of legacyVariables) {
67642
67433
  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);
67643
67434
  }
67644
- if (import_node_path34.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
67435
+ if (import_node_path33.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
67645
67436
  push(
67646
67437
  "legacy-name",
67647
67438
  "warn",
@@ -67949,18 +67740,18 @@ function collectDoctorReport(params) {
67949
67740
  const { paths } = params;
67950
67741
  const identityNames = import_node_fs14.default.existsSync(paths.identitiesDir) ? import_node_fs14.default.readdirSync(paths.identitiesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && isIdentityDirectoryName(entry.name)).map((entry) => entry.name).sort() : [];
67951
67742
  const identities = identityNames.map((name) => {
67952
- const farmRoot = import_node_path34.default.join(paths.identitiesDir, name);
67953
- const identityPath = import_node_path34.default.join(farmRoot, "identity.json");
67743
+ const farmRoot = import_node_path33.default.join(paths.identitiesDir, name);
67744
+ const identityPath = import_node_path33.default.join(farmRoot, "identity.json");
67954
67745
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
67955
67746
  });
67956
67747
  const profileNames = import_node_fs14.default.existsSync(paths.configProfilesDir) ? import_node_fs14.default.readdirSync(paths.configProfilesDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
67957
67748
  const configProfiles = profileNames.map((name) => {
67958
- const profilePath = import_node_path34.default.join(paths.configProfilesDir, `${name}.json`);
67749
+ const profilePath = import_node_path33.default.join(paths.configProfilesDir, `${name}.json`);
67959
67750
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
67960
67751
  });
67961
67752
  const providerNames = import_node_fs14.default.existsSync(paths.providersDir) ? import_node_fs14.default.readdirSync(paths.providersDir, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -".json".length)).sort() : [];
67962
67753
  const providers = providerNames.map((name) => {
67963
- const providerPath = import_node_path34.default.join(paths.providersDir, `${name}.json`);
67754
+ const providerPath = import_node_path33.default.join(paths.providersDir, `${name}.json`);
67964
67755
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
67965
67756
  });
67966
67757
  const ownExecutablePath = realOwnExecutablePath();
@@ -67972,12 +67763,12 @@ function collectDoctorReport(params) {
67972
67763
  binaryDiscovery = { ok: false, message: error62 instanceof Error ? error62.message : String(error62) };
67973
67764
  }
67974
67765
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
67975
- const pathDirs = (params.env.PATH ?? "").split(import_node_path34.default.delimiter).filter((dir) => dir !== "");
67766
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path33.default.delimiter).filter((dir) => dir !== "");
67976
67767
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
67977
67768
  findPathShadow({
67978
67769
  pathDirs,
67979
- targetDir: import_node_path34.default.dirname(shimState.targetPath),
67980
- targetFilename: import_node_path34.default.basename(shimState.targetPath),
67770
+ targetDir: import_node_path33.default.dirname(shimState.targetPath),
67771
+ targetFilename: import_node_path33.default.basename(shimState.targetPath),
67981
67772
  findExecutableInDir
67982
67773
  }),
67983
67774
  shimState.targetPath,
@@ -68000,7 +67791,7 @@ function collectDoctorReport(params) {
68000
67791
  agentShim: refinePathShadow(
68001
67792
  findPathShadow({
68002
67793
  pathDirs,
68003
- targetDir: import_node_path34.default.dirname(ownExecutablePath),
67794
+ targetDir: import_node_path33.default.dirname(ownExecutablePath),
68004
67795
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
68005
67796
  findExecutableInDir
68006
67797
  }),
@@ -68043,11 +67834,11 @@ function registerDoctorCommand(program2, deps) {
68043
67834
  // src/headroom/commands.ts
68044
67835
  var import_node_fs15 = __toESM(require("node:fs"), 1);
68045
67836
  var import_node_net3 = __toESM(require("node:net"), 1);
68046
- var import_node_path35 = __toESM(require("node:path"), 1);
67837
+ var import_node_path34 = __toESM(require("node:path"), 1);
68047
67838
  var import_node_child_process5 = require("node:child_process");
68048
67839
 
68049
67840
  // src/headroom/settings.ts
68050
- var import_node_crypto14 = require("node:crypto");
67841
+ var import_node_crypto12 = require("node:crypto");
68051
67842
  function settingsOf(config2) {
68052
67843
  return {
68053
67844
  ...config2.mode === void 0 ? {} : { mode: config2.mode },
@@ -68072,7 +67863,7 @@ function settingsEnv(settings2) {
68072
67863
  return settings2.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings2.rolloutChannel };
68073
67864
  }
68074
67865
  function hashSettings(settings2) {
68075
- return (0, import_node_crypto14.createHash)("sha256").update(JSON.stringify([...settingsArgs(settings2), JSON.stringify(settingsEnv(settings2))])).digest("hex");
67866
+ return (0, import_node_crypto12.createHash)("sha256").update(JSON.stringify([...settingsArgs(settings2), JSON.stringify(settingsEnv(settings2))])).digest("hex");
68076
67867
  }
68077
67868
 
68078
67869
  // src/headroom/supervisor.ts
@@ -68174,9 +67965,9 @@ function compareVersions2(a2, b) {
68174
67965
  }
68175
67966
  var HEADROOM_SUPERVISOR_STILL_RUNNING = -1;
68176
67967
  async function runSupervisor(initialConfig, ports, options = {}) {
68177
- const { fs: fs18, paths } = ports;
67968
+ const { fs: fs19, paths } = ports;
68178
67969
  let config2 = initialConfig;
68179
- const previousState = readHeadroomState(fs18, paths.headroomStateFile);
67970
+ const previousState = readHeadroomState(fs19, paths.headroomStateFile);
68180
67971
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
68181
67972
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
68182
67973
  return 0;
@@ -68185,19 +67976,19 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68185
67976
  let lastPort = previousState?.lastPort;
68186
67977
  const sticky = () => lastPort === void 0 ? {} : { lastPort };
68187
67978
  const ownsState = () => {
68188
- const owner = readHeadroomState(fs18, paths.headroomStateFile)?.supervisorPid;
67979
+ const owner = readHeadroomState(fs19, paths.headroomStateFile)?.supervisorPid;
68189
67980
  return owner === void 0 || owner === ports.ownPid || !ports.isRunning(owner);
68190
67981
  };
68191
67982
  const writeOwnState = (state) => {
68192
67983
  if (!ownsState()) {
68193
67984
  return false;
68194
67985
  }
68195
- writeHeadroomState(fs18, paths.headroomStateFile, state);
67986
+ writeHeadroomState(fs19, paths.headroomStateFile, state);
68196
67987
  return true;
68197
67988
  };
68198
67989
  const fail = (message) => {
68199
67990
  if (writeOwnState({ lastError: message, ...sticky() })) {
68200
- fs18.removeRecursive(paths.headroomLockFile);
67991
+ fs19.removeRecursive(paths.headroomLockFile);
68201
67992
  }
68202
67993
  ports.log(`agent-shim headroom supervisor: ${message}`);
68203
67994
  return 1;
@@ -68246,7 +68037,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68246
68037
  const settingsHash = hashSettings(config2.settings);
68247
68038
  const allowlist = allowlistOf(ports);
68248
68039
  const allowlistHash = hashAllowlist(allowlist);
68249
- pruneDeadSessions(fs18, paths.headroomSessionsDir, ports.isRunning);
68040
+ pruneDeadSessions(fs19, paths.headroomSessionsDir, ports.isRunning);
68250
68041
  const ownsNow = ownsState();
68251
68042
  if (!ownsNow && !superseded) {
68252
68043
  ports.log("agent-shim headroom supervisor: another supervisor now owns state.json; serving this daemon's own sessions until they end");
@@ -68298,7 +68089,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68298
68089
  ...sticky()
68299
68090
  });
68300
68091
  if (recorded) {
68301
- fs18.removeRecursive(paths.headroomLockFile);
68092
+ fs19.removeRecursive(paths.headroomLockFile);
68302
68093
  }
68303
68094
  idleSince = void 0;
68304
68095
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(pid)} ready on 127.0.0.1:${String(port)}`);
@@ -68313,7 +68104,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68313
68104
  }
68314
68105
  } else {
68315
68106
  if (runningHash !== allowlistHash || runningSettingsHash !== settingsHash || installedSource !== config2.source) {
68316
- if (sessionsForSupervisor(fs18, paths.headroomSessionsDir, ports.ownPid).length === 0) {
68107
+ if (sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid).length === 0) {
68317
68108
  ports.log("agent-shim headroom supervisor: configuration drifted and no sessions are live; restarting headroom");
68318
68109
  ports.stopProcess(headroomPid);
68319
68110
  headroomPid = void 0;
@@ -68322,7 +68113,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68322
68113
  continue;
68323
68114
  }
68324
68115
  }
68325
- const sessions = sessionsForSupervisor(fs18, paths.headroomSessionsDir, ports.ownPid);
68116
+ const sessions = sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid);
68326
68117
  if (sessions.length === 0) {
68327
68118
  idleSince ??= ports.now();
68328
68119
  const idleMs = ports.now() - idleSince;
@@ -68344,9 +68135,9 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68344
68135
  await ports.sleep(HEADROOM_POLL_MS);
68345
68136
  }
68346
68137
  }
68347
- function currentHeadroomAllowlist(fs18, paths) {
68348
- const providers = readAllProviders(fs18, paths.providersDir).map((entry) => entry.provider);
68349
- return headroomAllowlist(headroomUpstreams(providers, frontDoorOrigin(readFrontDoorState(fs18, paths.frontdoorStateFile))));
68138
+ function currentHeadroomAllowlist(fs19, paths) {
68139
+ const providers = readAllProviders(fs19, paths.providersDir).map((entry) => entry.provider);
68140
+ return headroomAllowlist(headroomUpstreams(providers, frontDoorOrigin(readFrontDoorState(fs19, paths.frontdoorStateFile))));
68350
68141
  }
68351
68142
  function allowlistOf(ports) {
68352
68143
  return currentHeadroomAllowlist(ports.fs, ports.paths);
@@ -68458,12 +68249,12 @@ function readInstalledHeadroomCommit() {
68458
68249
  if (toolDir.status !== 0) {
68459
68250
  return void 0;
68460
68251
  }
68461
- const libDir = import_node_path35.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
68252
+ const libDir = import_node_path34.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
68462
68253
  for (const python of realFarmFs.readdir(libDir)) {
68463
- const sitePackages = import_node_path35.default.join(libDir, python, "site-packages");
68254
+ const sitePackages = import_node_path34.default.join(libDir, python, "site-packages");
68464
68255
  for (const entry of realFarmFs.readdir(sitePackages)) {
68465
68256
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
68466
- const directUrl = realFarmFs.readFileUtf8(import_node_path35.default.join(sitePackages, entry, "direct_url.json"));
68257
+ const directUrl = realFarmFs.readFileUtf8(import_node_path34.default.join(sitePackages, entry, "direct_url.json"));
68467
68258
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
68468
68259
  }
68469
68260
  }
@@ -68993,14 +68784,14 @@ function requireIdentity(paths, name) {
68993
68784
  throw new IdentityNotFoundError(name);
68994
68785
  }
68995
68786
  }
68996
- function collectUsageReport(fs18, paths, filters) {
68787
+ function collectUsageReport(fs19, paths, filters) {
68997
68788
  const { identity, provider, sinceMs } = filters;
68998
68789
  if (identity !== void 0) {
68999
68790
  requireIdentity(paths, identity);
69000
68791
  }
69001
- const log = readUsageLog(fs18, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
68792
+ const log = readUsageLog(fs19, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
69002
68793
  const records = log.records.filter((record2) => (identity === void 0 || record2.identity === identity) && (provider === void 0 || record2.provider === provider));
69003
- const snapshots = (identity === void 0 ? listUsageSnapshots(fs18, paths.usageSnapshotsDir) : [readUsageSnapshot(fs18, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
68794
+ const snapshots = (identity === void 0 ? listUsageSnapshots(fs19, paths.usageSnapshotsDir) : [readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity)].flatMap((snapshot) => snapshot === void 0 ? [] : [snapshot])).map((snapshot) => provider === void 0 ? snapshot : { ...snapshot, providers: Object.fromEntries(Object.entries(snapshot.providers).filter(([name]) => name === provider)) }).filter((snapshot) => Object.keys(snapshot.providers).length > 0);
69004
68795
  return {
69005
68796
  since: sinceMs === void 0 ? void 0 : new Date(sinceMs).toISOString(),
69006
68797
  logDir: paths.usageLogDir,
@@ -69096,15 +68887,15 @@ function formatUsageReport(report) {
69096
68887
  }
69097
68888
  return lines;
69098
68889
  }
69099
- function collectAccounts(fs18, paths, identity) {
68890
+ function collectAccounts(fs19, paths, identity) {
69100
68891
  if (identity !== void 0) {
69101
68892
  requireIdentity(paths, identity);
69102
68893
  }
69103
68894
  const names = identity === void 0 ? listIdentities(paths).map((entry) => entry.name) : [identity];
69104
68895
  return names.map((name) => ({
69105
68896
  identity: name,
69106
- account: readAccountMetadata(fs18, paths.identitiesDir, name),
69107
- usage: readUsageSnapshot(fs18, paths.usageSnapshotsDir, name)
68897
+ account: readAccountMetadata(fs19, paths.identitiesDir, name),
68898
+ usage: readUsageSnapshot(fs19, paths.usageSnapshotsDir, name)
69108
68899
  }));
69109
68900
  }
69110
68901
  function formatAccounts(views) {
@@ -69265,10 +69056,228 @@ function buildProgram(deps) {
69265
69056
  return program2;
69266
69057
  }
69267
69058
 
69268
- // src/runClaude.ts
69059
+ // src/launchWiring.ts
69269
69060
  var import_node_os8 = __toESM(require("node:os"), 1);
69270
69061
  var import_node_crypto16 = require("node:crypto");
69271
69062
 
69063
+ // src/frontdoor/realFrontDoorPort.ts
69064
+ var import_node_fs16 = __toESM(require("node:fs"), 1);
69065
+
69066
+ // src/frontdoor/ensure.ts
69067
+ var import_node_crypto13 = require("node:crypto");
69068
+ var FRONTDOOR_START_TIMEOUT_MS = 3e4;
69069
+ var FRONTDOOR_LAUNCHER_POLL_MS = 100;
69070
+ var FrontDoorStartError = class extends CliError {
69071
+ constructor(message) {
69072
+ super(message);
69073
+ this.name = "FrontDoorStartError";
69074
+ }
69075
+ };
69076
+ function ensureFrontDoor(params) {
69077
+ const { paths, ports } = params;
69078
+ const deadline = ports.now() + FRONTDOOR_START_TIMEOUT_MS;
69079
+ let spawned = false;
69080
+ let replaced = false;
69081
+ const distrusted = /* @__PURE__ */ new Set();
69082
+ let lastRejection;
69083
+ for (; ; ) {
69084
+ const state = readFrontDoorState(ports.fs, paths.frontdoorStateFile);
69085
+ const supervisorPid = state?.supervisorPid;
69086
+ if (supervisorPid !== void 0 && !distrusted.has(supervisorPid) && ports.isRunning(supervisorPid)) {
69087
+ if (state?.port !== void 0 && state.connectPort !== void 0) {
69088
+ const verdict = ports.verifyListener(state.port);
69089
+ if (verdict.ok && (state.protocol ?? 0) < FRONT_DOOR_PROTOCOL && !replaced) {
69090
+ ports.stopSupervisor(supervisorPid);
69091
+ while (ports.isRunning(supervisorPid)) {
69092
+ if (ports.now() >= deadline) {
69093
+ throw new FrontDoorStartError(`agent-shim: the front door (pid ${String(supervisorPid)}, protocol ${String(state.protocol ?? 0)}) is older than this launcher (protocol ${String(FRONT_DOOR_PROTOCOL)}) and did not exit when asked. Daemon log: ${paths.frontdoorLogPath}`);
69094
+ }
69095
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
69096
+ }
69097
+ replaced = true;
69098
+ continue;
69099
+ }
69100
+ if (verdict.ok) {
69101
+ const token = (0, import_node_crypto13.randomUUID)();
69102
+ writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token });
69103
+ return { port: state.port, connectPort: state.connectPort, token };
69104
+ }
69105
+ lastRejection = `the listener on 127.0.0.1:${String(state.port)} (recorded for pid ${String(supervisorPid)}) failed authentication: ${verdict.reason}`;
69106
+ if (spawned) {
69107
+ throw new FrontDoorStartError(`agent-shim: ${lastRejection}; refusing to send this session's credentials to it. Daemon log: ${paths.frontdoorLogPath}`);
69108
+ }
69109
+ distrusted.add(supervisorPid);
69110
+ continue;
69111
+ }
69112
+ if (state?.lastError !== void 0) {
69113
+ throw new FrontDoorStartError(`agent-shim: the front door reported a fatal error and is not serving: ${state.lastError} (daemon log: ${paths.frontdoorLogPath})`);
69114
+ }
69115
+ } else if (!spawned) {
69116
+ ports.fs.mkdirp(paths.frontdoorDir);
69117
+ const created = ports.fs.writeFileExclusive(paths.frontdoorLockFile, `${JSON.stringify({ pid: params.launcherPid, at: ports.now() })}
69118
+ `);
69119
+ if (created) {
69120
+ ports.spawnSupervisor(paths);
69121
+ spawned = true;
69122
+ } else {
69123
+ const lock = readStartLock(ports.fs, paths.frontdoorLockFile);
69124
+ if (lock === void 0 || !ports.isRunning(lock.pid)) {
69125
+ ports.fs.removeRecursive(paths.frontdoorLockFile);
69126
+ continue;
69127
+ }
69128
+ }
69129
+ }
69130
+ if (ports.now() >= deadline) {
69131
+ const lastError = state?.lastError;
69132
+ throw new FrontDoorStartError(
69133
+ `agent-shim: the front door did not become ready within ${String(FRONTDOOR_START_TIMEOUT_MS)}ms` + (lastError === void 0 ? "" : ` (last error: ${lastError})`) + (lastRejection === void 0 ? "" : ` (${lastRejection})`) + `. Daemon log: ${paths.frontdoorLogPath}`
69134
+ );
69135
+ }
69136
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
69137
+ }
69138
+ }
69139
+
69140
+ // src/frontdoor/probe.ts
69141
+ var import_node_worker_threads = require("node:worker_threads");
69142
+ var PROBE_TIMEOUT_MS = 2e3;
69143
+ var PROBE_WAIT_MARGIN_MS = 1e3;
69144
+ var REASON_BYTES = 1024;
69145
+ var HEADER_SLOTS = 2;
69146
+ var INT32_BYTES = 4;
69147
+ var VERDICT_PENDING = 0;
69148
+ var VERDICT_OK = 1;
69149
+ var VERDICT_FAILED = 2;
69150
+ var PROBE_SOURCE = `
69151
+ const { workerData } = require("node:worker_threads");
69152
+ const https = require("node:https");
69153
+ const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
69154
+ const header = new Int32Array(shared, 0, headerSlots);
69155
+ const reason = new Uint8Array(shared, headerSlots * 4);
69156
+ let done = false;
69157
+ const finish = (verdict, message) => {
69158
+ if (done) return;
69159
+ done = true;
69160
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
69161
+ reason.set(bytes);
69162
+ Atomics.store(header, 1, bytes.length);
69163
+ Atomics.store(header, 0, verdict);
69164
+ Atomics.notify(header, 0);
69165
+ };
69166
+ const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
69167
+ let body = "";
69168
+ response.setEncoding("utf8");
69169
+ response.on("data", (chunk) => { body += chunk; });
69170
+ response.on("end", () => {
69171
+ if (response.statusCode === 200 && body === "ok") finish(ok, "");
69172
+ else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
69173
+ });
69174
+ response.on("error", (error) => finish(failed, error.message));
69175
+ });
69176
+ // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
69177
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
69178
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
69179
+ `;
69180
+ function probeFrontDoorSync(port, caPem) {
69181
+ const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
69182
+ const header = new Int32Array(shared, 0, HEADER_SLOTS);
69183
+ const worker = new import_node_worker_threads.Worker(PROBE_SOURCE, {
69184
+ eval: true,
69185
+ workerData: { port, ca: caPem, timeoutMs: PROBE_TIMEOUT_MS, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
69186
+ });
69187
+ worker.unref();
69188
+ try {
69189
+ const waited = Atomics.wait(header, 0, VERDICT_PENDING, PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS);
69190
+ const verdict = Atomics.load(header, 0);
69191
+ if (waited === "timed-out" || verdict === VERDICT_PENDING) {
69192
+ return { ok: false, reason: `the probe did not finish within ${String(PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS)}ms` };
69193
+ }
69194
+ if (verdict === VERDICT_OK) {
69195
+ return { ok: true };
69196
+ }
69197
+ const length = Atomics.load(header, 1);
69198
+ return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
69199
+ } finally {
69200
+ void worker.terminate();
69201
+ }
69202
+ }
69203
+
69204
+ // src/frontdoor/trust.ts
69205
+ var import_node_crypto14 = require("node:crypto");
69206
+ var import_node_path35 = __toESM(require("node:path"), 1);
69207
+ var BUNDLE_NAME_HEX_DIGITS = 16;
69208
+ function resolveTrustBundle(params) {
69209
+ const { caCertFile, bundlesDir, inherited, fs: fs19 } = params;
69210
+ if (inherited === void 0 || inherited === "" || import_node_path35.default.resolve(inherited) === import_node_path35.default.resolve(caCertFile)) {
69211
+ return { path: caCertFile };
69212
+ }
69213
+ const caPem = fs19.readFileUtf8(caCertFile);
69214
+ let inheritedPem;
69215
+ try {
69216
+ inheritedPem = fs19.readFileUtf8(inherited);
69217
+ } catch (error62) {
69218
+ return {
69219
+ path: caCertFile,
69220
+ warning: `agent-shim: NODE_EXTRA_CA_CERTS names ${inherited}, which could not be read (${error62 instanceof Error ? error62.message : String(error62)}); the child trusts agent-shim's front-door CA on top of the system store, and nothing from that file`
69221
+ };
69222
+ }
69223
+ if (inheritedPem.includes(caPem.trim())) {
69224
+ return { path: inherited };
69225
+ }
69226
+ const combined = `${inheritedPem.trimEnd()}
69227
+ ${caPem}`;
69228
+ const bundle = import_node_path35.default.join(bundlesDir, `${(0, import_node_crypto14.createHash)("sha256").update(combined).digest("hex").slice(0, BUNDLE_NAME_HEX_DIGITS)}.pem`);
69229
+ if (!fs19.exists(bundle)) {
69230
+ fs19.mkdirp(bundlesDir);
69231
+ fs19.writeFileAtomic(bundle, combined);
69232
+ }
69233
+ return { path: bundle };
69234
+ }
69235
+
69236
+ // src/frontdoor/realFrontDoorPort.ts
69237
+ var realTrustBundleFs = {
69238
+ readFileUtf8: (file2) => import_node_fs16.default.readFileSync(file2, "utf8"),
69239
+ exists: (file2) => import_node_fs16.default.existsSync(file2),
69240
+ mkdirp: (dir) => {
69241
+ import_node_fs16.default.mkdirSync(dir, { recursive: true });
69242
+ },
69243
+ writeFileAtomic: (file2, contents) => {
69244
+ realFarmFs.writeFilePrivate(file2, contents);
69245
+ }
69246
+ };
69247
+ function realFrontDoorPort(paths, spawnDaemon) {
69248
+ return {
69249
+ ensure: (inheritedExtraCaCerts) => {
69250
+ const up = ensureFrontDoor({
69251
+ paths,
69252
+ launcherPid: process.pid,
69253
+ ports: {
69254
+ fs: realFarmFs,
69255
+ isRunning: realIsProcessRunning,
69256
+ now: () => Date.now(),
69257
+ sleep: realSleepSync,
69258
+ spawnSupervisor: (layout) => spawnDaemon(layout, "__frontdoor-supervisor", layout.frontdoorLogPath),
69259
+ stopSupervisor: (pid) => {
69260
+ process.kill(pid, "SIGTERM");
69261
+ },
69262
+ // 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.
69263
+ verifyListener: (port) => probeFrontDoorSync(port, import_node_fs16.default.readFileSync(paths.frontdoorCaCertFile, "utf8"))
69264
+ }
69265
+ });
69266
+ const trust = resolveTrustBundle({ caCertFile: paths.frontdoorCaCertFile, bundlesDir: paths.frontdoorCaBundlesDir, inherited: inheritedExtraCaCerts, fs: realTrustBundleFs });
69267
+ return {
69268
+ port: up.port,
69269
+ connectPort: up.connectPort,
69270
+ trustBundlePath: trust.path,
69271
+ ...trust.warning === void 0 ? {} : { trustWarning: trust.warning },
69272
+ sessionToken: up.token
69273
+ };
69274
+ },
69275
+ release: () => {
69276
+ removeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, process.pid);
69277
+ }
69278
+ };
69279
+ }
69280
+
69272
69281
  // src/launcher.ts
69273
69282
  var import_node_crypto15 = require("node:crypto");
69274
69283
  var import_node_path37 = __toESM(require("node:path"), 1);
@@ -69517,7 +69526,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
69517
69526
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: resolution.message };
69518
69527
  }
69519
69528
  function pickFromPool(decided, params, parsedArgv) {
69520
- const { paths, fs: fs18, proc, log } = params;
69529
+ const { paths, fs: fs19, proc, log } = params;
69521
69530
  if (decided.pool === void 0) {
69522
69531
  return { identityDecision: decided };
69523
69532
  }
@@ -69531,7 +69540,7 @@ function pickFromPool(decided, params, parsedArgv) {
69531
69540
  selectedVia: decided.source,
69532
69541
  pools: params.pools,
69533
69542
  paths,
69534
- fs: fs18,
69543
+ fs: fs19,
69535
69544
  usageFs: farmRuntime.fs,
69536
69545
  cwd: farmRuntime.cwd,
69537
69546
  now: farmRuntime.now,
@@ -69546,8 +69555,8 @@ function pickFromPool(decided, params, parsedArgv) {
69546
69555
  }
69547
69556
  return { identityDecision: { ...decided, name: resolution.identity }, poolExplanation: resolution.explanation };
69548
69557
  }
69549
- function runLauncher(params) {
69550
- const { paths, fs: fs18, spawn: spawn3, proc, log } = params;
69558
+ function prepareLaunch(params) {
69559
+ const { paths, fs: fs19, proc, log } = params;
69551
69560
  const { env, argv } = proc;
69552
69561
  const parsedArgv = parseLauncherArgv(argv);
69553
69562
  const cliOverride = buildCliOverride({
@@ -69562,7 +69571,7 @@ function runLauncher(params) {
69562
69571
  argv0Identity: parsedArgv.identity,
69563
69572
  directoryPinnedIdentity: params.directoryPinnedIdentity,
69564
69573
  readActiveIdentityFile: () => {
69565
- const raw = fs18.readFileUtf8(paths.activeIdentityFile);
69574
+ const raw = fs19.readFileUtf8(paths.activeIdentityFile);
69566
69575
  if (raw === void 0) {
69567
69576
  return void 0;
69568
69577
  }
@@ -69597,7 +69606,7 @@ function runLauncher(params) {
69597
69606
  }
69598
69607
  let loadedIdentity;
69599
69608
  if (identityDecision.name !== void 0) {
69600
- loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs18);
69609
+ loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs19);
69601
69610
  if (loadedIdentity === void 0) {
69602
69611
  log.error(
69603
69612
  `agent-shim: no identity named "${identityDecision.name}" (selected via ${identityDecision.source}). Run \`agent-shim identity add ${identityDecision.name}\` first.`
@@ -69612,7 +69621,7 @@ function runLauncher(params) {
69612
69621
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
69613
69622
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
69614
69623
  });
69615
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs18.readConfigFile(import_node_path37.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
69624
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs19.readConfigFile(import_node_path37.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
69616
69625
  log.error(
69617
69626
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
69618
69627
  );
@@ -69621,7 +69630,7 @@ function runLauncher(params) {
69621
69630
  const farmContext = farm !== void 0 && farmIdentity !== void 0 ? { farm, identity: farmIdentity, cascade: farm.loadCascade(configProfileDecision.name, cliOverride) } : void 0;
69622
69631
  const provider = parsedArgv.provider === false ? void 0 : resolveProvider({
69623
69632
  paths,
69624
- port: fs18,
69633
+ port: fs19,
69625
69634
  env,
69626
69635
  ...params.credentials === void 0 ? {} : { credentials: params.credentials },
69627
69636
  ...parsedArgv.provider === void 0 ? {} : { cliProvider: parsedArgv.provider },
@@ -69773,32 +69782,25 @@ function runLauncher(params) {
69773
69782
  sessionId: (0, import_node_crypto15.randomUUID)()
69774
69783
  });
69775
69784
  const releases = [...headroom === void 0 || headroomPort === void 0 ? [] : [headroomPort.release], ...frontDoorRelease === void 0 ? [] : [frontDoorRelease]];
69776
- if (releases.length === 0) {
69777
- spawnClaude({ bin: discovered.path, args: finalArgv, env: finalEnv, spawn: spawn3, proc });
69778
- }
69779
- const releaseAll = () => {
69780
- for (const release of releases) {
69781
- release();
69785
+ const release = () => {
69786
+ for (const registered of releases) {
69787
+ registered();
69782
69788
  }
69783
69789
  };
69790
+ return { bin: discovered.path, args: finalArgv, env: finalEnv, release };
69791
+ }
69792
+ function runLauncher(params) {
69793
+ const plan = prepareLaunch(params);
69784
69794
  try {
69785
- spawnClaude({
69786
- bin: discovered.path,
69787
- args: finalArgv,
69788
- env: finalEnv,
69789
- spawn: spawn3,
69790
- proc,
69791
- beforeExit: releaseAll
69792
- });
69795
+ spawnClaude({ bin: plan.bin, args: plan.args, env: plan.env, spawn: params.spawn, proc: params.proc, beforeExit: plan.release });
69793
69796
  } finally {
69794
- releaseAll();
69797
+ plan.release();
69795
69798
  }
69796
69799
  }
69797
69800
 
69798
- // src/runClaude.ts
69799
- function buildFarmRuntime(paths) {
69801
+ // src/launchWiring.ts
69802
+ function buildFarmRuntime(paths, cwd) {
69800
69803
  const home = import_node_os8.default.homedir();
69801
- const cwd = process.cwd();
69802
69804
  const read = cosmiconfigReader();
69803
69805
  const classification = loadClassification(paths);
69804
69806
  const loaded = loadCascadeInput({ paths, home, cwd, read });
@@ -69832,9 +69834,30 @@ function buildFarmRuntime(paths) {
69832
69834
  ...loaded.globalConfig?.pools === void 0 ? {} : { pools: loaded.globalConfig.pools }
69833
69835
  };
69834
69836
  }
69837
+ function realPrepareLaunchParams(paths, options) {
69838
+ const { farm } = options;
69839
+ return {
69840
+ paths,
69841
+ fs: realFsPort,
69842
+ proc: options.proc,
69843
+ log: options.log,
69844
+ resolveClaudeBinary: realResolveClaudeBinary(resolveOwnInstallDirs(paths, realOwnExecutablePath())),
69845
+ farm: farm.runtime,
69846
+ headroom: realHeadroomPort(paths, { spawnDaemon: options.spawnDaemon, cwd: farm.runtime.cwd }),
69847
+ frontdoor: realFrontDoorPort(paths, options.spawnDaemon),
69848
+ credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
69849
+ ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
69850
+ ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
69851
+ ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
69852
+ ...farm.pools === void 0 ? {} : { pools: farm.pools },
69853
+ ...options.allowMissingConfigProfile === void 0 ? {} : { allowMissingConfigProfile: options.allowMissingConfigProfile }
69854
+ };
69855
+ }
69856
+
69857
+ // src/runClaude.ts
69835
69858
  async function runClaude(argvOverride) {
69836
69859
  const paths = resolveLayoutPaths();
69837
- const farm = buildFarmRuntime(paths);
69860
+ const farm = buildFarmRuntime(paths, process.cwd());
69838
69861
  let allowMissingConfigProfile = false;
69839
69862
  if (process.stdin.isTTY) {
69840
69863
  const procForDecision = argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride };
@@ -69884,21 +69907,14 @@ async function runClaude(argvOverride) {
69884
69907
  }
69885
69908
  }
69886
69909
  runLauncher({
69887
- paths,
69888
- fs: realFsPort,
69889
- spawn: realSpawnPort,
69890
- proc: argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride },
69891
- log: realLogPort,
69892
- resolveClaudeBinary: realResolveClaudeBinary(resolveOwnInstallDirs(paths, realOwnExecutablePath())),
69893
- farm: farm.runtime,
69894
- headroom: realHeadroomPort(paths),
69895
- frontdoor: realFrontDoorPort(paths),
69896
- credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
69897
- ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
69898
- ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
69899
- ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
69900
- ...farm.pools === void 0 ? {} : { pools: farm.pools },
69901
- allowMissingConfigProfile
69910
+ ...realPrepareLaunchParams(paths, {
69911
+ proc: argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride },
69912
+ log: realLogPort,
69913
+ spawnDaemon: spawnDetachedSupervisor,
69914
+ farm,
69915
+ allowMissingConfigProfile
69916
+ }),
69917
+ spawn: realSpawnPort
69902
69918
  });
69903
69919
  }
69904
69920