claude-use 7.12.1 → 7.13.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.
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
@@ -59063,6 +59065,43 @@ function planFarm(params) {
59063
59065
  return { entries, materialised, links };
59064
59066
  }
59065
59067
 
59068
+ // src/resolve/walkPolicy.ts
59069
+ var ENTER_EVERYTHING = () => true;
59070
+ function readsSubtreeAggregates(rule) {
59071
+ const when = rule.when;
59072
+ return when !== void 0 && (when.newerThan !== void 0 || when.olderThan !== void 0 || when.maxSizeBytes !== void 0);
59073
+ }
59074
+ function hasUnboundedDepth(pattern) {
59075
+ return pattern.includes("**") || /[{(]/.test(pattern);
59076
+ }
59077
+ function couldMatchBeneath(rule, dirRel) {
59078
+ if (rule.matches(dirRel)) {
59079
+ return rule.when !== void 0;
59080
+ }
59081
+ if (rule.isExact) {
59082
+ return rule.canonicalPattern.startsWith(`${dirRel}/`);
59083
+ }
59084
+ const depth = dirRel.split("/").length;
59085
+ if (!hasUnboundedDepth(rule.canonicalPattern) && rule.segmentCount <= depth) {
59086
+ return false;
59087
+ }
59088
+ const prefix = rule.literalPrefix;
59089
+ return prefix === "" || prefix.startsWith(`${dirRel}/`) || dirRel.startsWith(prefix);
59090
+ }
59091
+ function descendPolicy(rules) {
59092
+ const all = [...rules];
59093
+ if (all.some(readsSubtreeAggregates)) {
59094
+ return ENTER_EVERYTHING;
59095
+ }
59096
+ return (dirRel) => all.some((rule) => couldMatchBeneath(rule, dirRel));
59097
+ }
59098
+ function enterRulesAnd(policy, target) {
59099
+ if (target === void 0 || target === "") {
59100
+ return policy;
59101
+ }
59102
+ return (dirRel) => dirRel === target || target.startsWith(`${dirRel}/`) || policy(dirRel);
59103
+ }
59104
+
59066
59105
  // src/resolve/pipeline.ts
59067
59106
  function topLevelNames(facts) {
59068
59107
  const names = /* @__PURE__ */ new Set();
@@ -59074,6 +59113,9 @@ function topLevelNames(facts) {
59074
59113
  }
59075
59114
  return [...names].sort();
59076
59115
  }
59116
+ function descendPolicyFor(cascade, home) {
59117
+ return descendPolicy(flattenLayers(assembleCascade(cascade).layers, { home }).rules.values());
59118
+ }
59077
59119
  function resolveDecisions(input2) {
59078
59120
  const assembled = assembleCascade(input2.cascade);
59079
59121
  const flattened = flattenLayers(assembled.layers, { home: input2.facts.home });
@@ -59109,8 +59151,8 @@ var FarmManifestSchema = external_exports.strictObject({
59109
59151
  materialised: external_exports.array(external_exports.string()),
59110
59152
  links: external_exports.array(external_exports.strictObject({ rel: external_exports.string(), target: external_exports.string() }))
59111
59153
  });
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));
59154
+ function readFarmManifest(fs19, farmRoot) {
59155
+ 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
59156
  if (raw === void 0) {
59115
59157
  return void 0;
59116
59158
  }
@@ -59134,7 +59176,7 @@ function buildEntryFacts(params) {
59134
59176
  const isDirectory = stat.kind === "dir";
59135
59177
  let latestMtimeMs = stat.mtimeMs;
59136
59178
  let totalSizeBytes = stat.sizeBytes;
59137
- if (isDirectory) {
59179
+ if (isDirectory && params.descend(rel)) {
59138
59180
  for (const name of [...params.fs.readdir(absolute)].sort()) {
59139
59181
  const child = visit2(`${rel}/${name}`);
59140
59182
  if (child !== void 0) {
@@ -59168,9 +59210,9 @@ function buildEntryFacts(params) {
59168
59210
  entries
59169
59211
  };
59170
59212
  }
59171
- function listSubtree(fs18, root, rel) {
59213
+ function listSubtree(fs19, root, rel) {
59172
59214
  const absolute = import_node_path16.default.join(root, rel);
59173
- const stat = fs18.lstat(absolute);
59215
+ const stat = fs19.lstat(absolute);
59174
59216
  if (stat === void 0) {
59175
59217
  return [];
59176
59218
  }
@@ -59178,10 +59220,10 @@ function listSubtree(fs18, root, rel) {
59178
59220
  return [{ rel, kind: "symlink" }];
59179
59221
  }
59180
59222
  if (stat.kind === "dir") {
59181
- const children = [...fs18.readdir(absolute)].sort().flatMap((name) => listSubtree(fs18, root, `${rel}/${name}`));
59223
+ const children = [...fs19.readdir(absolute)].sort().flatMap((name) => listSubtree(fs19, root, `${rel}/${name}`));
59182
59224
  return [{ rel, kind: "dir" }, ...children];
59183
59225
  }
59184
- const contentHash = fs18.hashFile(absolute);
59226
+ const contentHash = fs19.hashFile(absolute);
59185
59227
  return [{ rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } }];
59186
59228
  }
59187
59229
  function topLevelScopeRoots(roots) {
@@ -59195,25 +59237,25 @@ function topLevelScopeRoots(roots) {
59195
59237
  }
59196
59238
  return kept;
59197
59239
  }
59198
- function reconciliationScope(fs18, farmRoot, manifest) {
59240
+ function reconciliationScope(fs19, farmRoot, manifest) {
59199
59241
  if (manifest !== void 0) {
59200
59242
  return topLevelScopeRoots(manifest.materialised);
59201
59243
  }
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();
59244
+ 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
59245
  }
59204
- function collectFarmListing(fs18, farmRoot, scopeRoots) {
59205
- return scopeRoots.flatMap((root) => listSubtree(fs18, farmRoot, root));
59246
+ function collectFarmListing(fs19, farmRoot, scopeRoots) {
59247
+ return scopeRoots.flatMap((root) => listSubtree(fs19, farmRoot, root));
59206
59248
  }
59207
- function collectCanonicalCounterparts(fs18, claudeHome, farmListing) {
59249
+ function collectCanonicalCounterparts(fs19, claudeHome, farmListing) {
59208
59250
  const out = [];
59209
59251
  for (const entry of farmListing) {
59210
59252
  const absolute = import_node_path16.default.join(claudeHome, entry.rel);
59211
- const stat = fs18.lstat(absolute);
59253
+ const stat = fs19.lstat(absolute);
59212
59254
  if (stat === void 0) {
59213
59255
  continue;
59214
59256
  }
59215
59257
  if (stat.kind === "file") {
59216
- const contentHash = fs18.hashFile(absolute);
59258
+ const contentHash = fs19.hashFile(absolute);
59217
59259
  out.push({ rel: entry.rel, kind: "file", ...contentHash === void 0 ? {} : { contentHash } });
59218
59260
  continue;
59219
59261
  }
@@ -59481,7 +59523,8 @@ function resyncFarm(params) {
59481
59523
  nowMs,
59482
59524
  env: params.env,
59483
59525
  ...params.branch === void 0 ? {} : { branch: params.branch },
59484
- ...params.branchDetached === void 0 ? {} : { branchDetached: params.branchDetached }
59526
+ ...params.branchDetached === void 0 ? {} : { branchDetached: params.branchDetached },
59527
+ descend: descendPolicyFor(params.cascade, params.home)
59485
59528
  });
59486
59529
  const resolved = resolveDecisions({ facts, cascade: params.cascade, classification: params.classification });
59487
59530
  const manifest = {
@@ -59863,7 +59906,9 @@ function buildConfigureContext(deps, params) {
59863
59906
  nowMs: Date.now(),
59864
59907
  env: process.env,
59865
59908
  ...git.branch === void 0 ? {} : { branch: git.branch },
59866
- ...git.branchDetached === void 0 ? {} : { branchDetached: git.branchDetached }
59909
+ ...git.branchDetached === void 0 ? {} : { branchDetached: git.branchDetached },
59910
+ // The picker lists the direct children of the path it was asked about, so the walk also enters that path and the directories on the way to it.
59911
+ descend: enterRulesAnd(descendPolicyFor(cascade, params.home), params.path)
59867
59912
  });
59868
59913
  const resolved = resolveDecisions({ facts, cascade, classification });
59869
59914
  const levels = buildWriteTargetLevels(params.cwd, params.home, globalConfig2?.walkUpLimit);
@@ -60455,7 +60500,7 @@ async function resolveFarmConflicts(params) {
60455
60500
  return { resolved, autoResolved, removed, retained };
60456
60501
  }
60457
60502
 
60458
- // src/cli/parsers.ts
60503
+ // src/cli/pairs.ts
60459
60504
  function splitCommas(input2) {
60460
60505
  if (input2 === "") {
60461
60506
  return [];
@@ -60489,6 +60534,8 @@ function parseBoolPairList(input2) {
60489
60534
  }
60490
60535
  return result;
60491
60536
  }
60537
+
60538
+ // src/cli/parsers.ts
60492
60539
  function asInvalidArgument(parse3) {
60493
60540
  try {
60494
60541
  return parse3();
@@ -60985,7 +61032,7 @@ function registerIdentityCommand(program2, deps) {
60985
61032
  // package.json
60986
61033
  var package_default = {
60987
61034
  name: "claude-use",
60988
- version: "7.12.1",
61035
+ version: "7.13.1",
60989
61036
  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
61037
  license: "MIT",
60991
61038
  author: "Joseph Mearman <joseph@mearman.co.uk>",
@@ -61307,12 +61354,12 @@ function isIdentityName(name) {
61307
61354
  function claudeJsonPath(identitiesDir, identity) {
61308
61355
  return import_node_path21.default.join(identitiesDir, identity, CLAUDE_JSON);
61309
61356
  }
61310
- function readAccountMetadata(fs18, identitiesDir, identity) {
61357
+ function readAccountMetadata(fs19, identitiesDir, identity) {
61311
61358
  if (!isIdentityName(identity)) {
61312
61359
  throw new Error(`"${identity}" is not a valid identity name.`);
61313
61360
  }
61314
61361
  const file2 = claudeJsonPath(identitiesDir, identity);
61315
- const raw = fs18.readFileUtf8(file2);
61362
+ const raw = fs19.readFileUtf8(file2);
61316
61363
  if (raw === void 0) {
61317
61364
  return void 0;
61318
61365
  }
@@ -61342,19 +61389,19 @@ function readAccountMetadata(fs18, identitiesDir, identity) {
61342
61389
  }
61343
61390
  return account.data;
61344
61391
  }
61345
- function createAccountReader(fs18, identitiesDir) {
61392
+ function createAccountReader(fs19, identitiesDir) {
61346
61393
  const cache = /* @__PURE__ */ new Map();
61347
61394
  return (identity) => {
61348
61395
  if (!isIdentityName(identity)) {
61349
61396
  throw new Error(`"${identity}" is not a valid identity name.`);
61350
61397
  }
61351
- const stat = fs18.lstat(claudeJsonPath(identitiesDir, identity));
61398
+ const stat = fs19.lstat(claudeJsonPath(identitiesDir, identity));
61352
61399
  const stamp = stat === void 0 ? "absent" : `${String(stat.mtimeMs)}:${String(stat.sizeBytes)}`;
61353
61400
  const cached2 = cache.get(identity);
61354
61401
  if (cached2?.stamp === stamp) {
61355
61402
  return cached2.account;
61356
61403
  }
61357
- const account = readAccountMetadata(fs18, identitiesDir, identity);
61404
+ const account = readAccountMetadata(fs19, identitiesDir, identity);
61358
61405
  cache.set(identity, { stamp, account });
61359
61406
  return account;
61360
61407
  };
@@ -62122,8 +62169,8 @@ function segmentDay(epochMs) {
62122
62169
  function segmentName(day, pid) {
62123
62170
  return `${day}.${String(pid)}.jsonl`;
62124
62171
  }
62125
- function listLogSegments(fs18, logDir) {
62126
- return fs18.readdir(logDir).flatMap((name) => {
62172
+ function listLogSegments(fs19, logDir) {
62173
+ return fs19.readdir(logDir).flatMap((name) => {
62127
62174
  const match = SEGMENT_RE.exec(name);
62128
62175
  const day = match?.[1];
62129
62176
  if (day === void 0) {
@@ -62132,15 +62179,15 @@ function listLogSegments(fs18, logDir) {
62132
62179
  return [{ name, day, endsAt: Date.parse(`${day}T00:00:00.000Z`) + DAY_MS }];
62133
62180
  }).sort((left, right) => left.day.localeCompare(right.day) || left.name.localeCompare(right.name));
62134
62181
  }
62135
- function readUsageLog(fs18, logDir, options = {}) {
62182
+ function readUsageLog(fs19, logDir, options = {}) {
62136
62183
  const { sinceMs } = options;
62137
62184
  const records = [];
62138
62185
  let invalidLines = 0;
62139
- for (const segment of listLogSegments(fs18, logDir)) {
62186
+ for (const segment of listLogSegments(fs19, logDir)) {
62140
62187
  if (sinceMs !== void 0 && segment.endsAt <= sinceMs) {
62141
62188
  continue;
62142
62189
  }
62143
- const contents = fs18.readFileUtf8(import_node_path22.default.join(logDir, segment.name));
62190
+ const contents = fs19.readFileUtf8(import_node_path22.default.join(logDir, segment.name));
62144
62191
  if (contents === void 0) {
62145
62192
  continue;
62146
62193
  }
@@ -62184,9 +62231,9 @@ function snapshotPath(snapshotsDir, identity) {
62184
62231
  }
62185
62232
  return import_node_path22.default.join(snapshotsDir, `${identity}.json`);
62186
62233
  }
62187
- function readUsageSnapshot(fs18, snapshotsDir, identity) {
62234
+ function readUsageSnapshot(fs19, snapshotsDir, identity) {
62188
62235
  const file2 = snapshotPath(snapshotsDir, identity);
62189
- const raw = fs18.readFileUtf8(file2);
62236
+ const raw = fs19.readFileUtf8(file2);
62190
62237
  if (raw === void 0) {
62191
62238
  return void 0;
62192
62239
  }
@@ -62202,8 +62249,8 @@ function readUsageSnapshot(fs18, snapshotsDir, identity) {
62202
62249
  }
62203
62250
  return snapshot.data;
62204
62251
  }
62205
- function listUsageSnapshots(fs18, snapshotsDir) {
62206
- return fs18.readdir(snapshotsDir).flatMap((name) => {
62252
+ function listUsageSnapshots(fs19, snapshotsDir) {
62253
+ return fs19.readdir(snapshotsDir).flatMap((name) => {
62207
62254
  if (!name.endsWith(".json")) {
62208
62255
  return [];
62209
62256
  }
@@ -62211,7 +62258,7 @@ function listUsageSnapshots(fs18, snapshotsDir) {
62211
62258
  if (!isIdentityName(identity)) {
62212
62259
  return [];
62213
62260
  }
62214
- const snapshot = readUsageSnapshot(fs18, snapshotsDir, identity);
62261
+ const snapshot = readUsageSnapshot(fs19, snapshotsDir, identity);
62215
62262
  return snapshot === void 0 ? [] : [snapshot];
62216
62263
  }).sort((left, right) => left.identity.localeCompare(right.identity));
62217
62264
  }
@@ -62270,11 +62317,11 @@ var import_node_path23 = __toESM(require("node:path"), 1);
62270
62317
  var DAY_MS2 = 864e5;
62271
62318
  var DAYS_IN_WEEK = 7;
62272
62319
  var USAGE_RETENTION_MS = DAYS_IN_WEEK * DAY_MS2;
62273
- function pruneUsageLog(fs18, logDir, nowMs) {
62320
+ function pruneUsageLog(fs19, logDir, nowMs) {
62274
62321
  const cutoff = nowMs - USAGE_RETENTION_MS;
62275
- for (const segment of listLogSegments(fs18, logDir)) {
62322
+ for (const segment of listLogSegments(fs19, logDir)) {
62276
62323
  if (segment.endsAt <= cutoff) {
62277
- fs18.removeRecursive(import_node_path23.default.join(logDir, segment.name));
62324
+ fs19.removeRecursive(import_node_path23.default.join(logDir, segment.name));
62278
62325
  }
62279
62326
  }
62280
62327
  }
@@ -62303,7 +62350,7 @@ function foldProviderState(current, record2) {
62303
62350
  };
62304
62351
  }
62305
62352
  function createUsageStore(deps) {
62306
- const { fs: fs18, paths } = deps;
62353
+ const { fs: fs19, paths } = deps;
62307
62354
  let prunedDay;
62308
62355
  const rewriteSnapshot = (identity, fold) => {
62309
62356
  if (!isIdentityName(identity)) {
@@ -62312,7 +62359,7 @@ function createUsageStore(deps) {
62312
62359
  }
62313
62360
  let current;
62314
62361
  try {
62315
- current = readUsageSnapshot(fs18, paths.usageSnapshotsDir, identity);
62362
+ current = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
62316
62363
  } catch (error62) {
62317
62364
  if (!(error62 instanceof UsageSnapshotError)) {
62318
62365
  throw error62;
@@ -62339,8 +62386,8 @@ function createUsageStore(deps) {
62339
62386
  ...account === void 0 ? {} : { account },
62340
62387
  providers
62341
62388
  });
62342
- fs18.mkdirPrivate(paths.usageSnapshotsDir);
62343
- fs18.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
62389
+ fs19.mkdirPrivate(paths.usageSnapshotsDir);
62390
+ fs19.writeFilePrivate(snapshotPath(paths.usageSnapshotsDir, identity), `${JSON.stringify(snapshot, null, 2)}
62344
62391
  `);
62345
62392
  return true;
62346
62393
  };
@@ -62348,14 +62395,14 @@ function createUsageStore(deps) {
62348
62395
  record: (input2) => {
62349
62396
  const record2 = UsageRecordSchema.parse(input2);
62350
62397
  const nowMs = deps.now();
62351
- fs18.mkdirPrivate(paths.usageDir);
62352
- fs18.mkdirPrivate(paths.usageLogDir);
62398
+ fs19.mkdirPrivate(paths.usageDir);
62399
+ fs19.mkdirPrivate(paths.usageLogDir);
62353
62400
  const day = segmentDay(nowMs);
62354
62401
  if (prunedDay !== day) {
62355
- pruneUsageLog(fs18, paths.usageLogDir, nowMs);
62402
+ pruneUsageLog(fs19, paths.usageLogDir, nowMs);
62356
62403
  prunedDay = day;
62357
62404
  }
62358
- fs18.appendFilePrivate(import_node_path23.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
62405
+ fs19.appendFilePrivate(import_node_path23.default.join(paths.usageLogDir, segmentName(day, deps.pid)), `${JSON.stringify(record2)}
62359
62406
  `);
62360
62407
  if (record2.identity !== void 0) {
62361
62408
  rewriteSnapshot(record2.identity, (current) => ({ ...current?.providers, [record2.provider]: foldProviderState(current?.providers[record2.provider], record2) }));
@@ -62382,14 +62429,14 @@ var PicksFileSchema = external_exports.strictObject({
62382
62429
  function errorMessage(error62) {
62383
62430
  return error62 instanceof Error ? error62.message : String(error62);
62384
62431
  }
62385
- function loadPoolMembers(fs18, paths, identities, nowMs) {
62432
+ function loadPoolMembers(fs19, paths, identities, nowMs) {
62386
62433
  const windowStartMs = nowMs - FIVE_HOUR_WINDOW_MS;
62387
- const log = readUsageLog(fs18, paths.usageLogDir, { sinceMs: windowStartMs });
62434
+ const log = readUsageLog(fs19, paths.usageLogDir, { sinceMs: windowStartMs });
62388
62435
  return identities.map((identity) => {
62389
62436
  const records = log.records.filter((record2) => record2.identity === identity && record2.provider === ANTHROPIC_PROVIDER && Date.parse(record2.at) >= windowStartMs);
62390
62437
  try {
62391
- const snapshot = readUsageSnapshot(fs18, paths.usageSnapshotsDir, identity);
62392
- const account = readAccountMetadata(fs18, paths.identitiesDir, identity) ?? snapshot?.account;
62438
+ const snapshot = readUsageSnapshot(fs19, paths.usageSnapshotsDir, identity);
62439
+ const account = readAccountMetadata(fs19, paths.identitiesDir, identity) ?? snapshot?.account;
62393
62440
  return { identity, records, ...snapshot === void 0 ? {} : { snapshot }, ...account === void 0 ? {} : { account } };
62394
62441
  } catch (error62) {
62395
62442
  if (error62 instanceof UsageSnapshotError || error62 instanceof AccountMetadataError) {
@@ -62407,9 +62454,9 @@ function rankPoolFromStore(params) {
62407
62454
  ...params.sticky === void 0 ? {} : { sticky: params.sticky }
62408
62455
  });
62409
62456
  }
62410
- function readPicksFile(fs18, file2) {
62457
+ function readPicksFile(fs19, file2) {
62411
62458
  const empty = { schemaVersion: SCHEMA_VERSION, picks: {} };
62412
- const raw = fs18.readFileUtf8(file2);
62459
+ const raw = fs19.readFileUtf8(file2);
62413
62460
  if (raw === void 0) {
62414
62461
  return { file: empty };
62415
62462
  }
@@ -62422,17 +62469,17 @@ function readPicksFile(fs18, file2) {
62422
62469
  const result = PicksFileSchema.safeParse(parsed);
62423
62470
  return result.success ? { file: result.data } : { file: empty, problem: `${file2} is not a picks file this agent-shim can read` };
62424
62471
  }
62425
- function readStickyPick(fs18, picksFile, directory) {
62426
- const read = readPicksFile(fs18, picksFile);
62472
+ function readStickyPick(fs19, picksFile, directory) {
62473
+ const read = readPicksFile(fs19, picksFile);
62427
62474
  const entry = read.file.picks[directory];
62428
62475
  return { ...entry === void 0 ? {} : { sticky: entry }, ...read.problem === void 0 ? {} : { problem: read.problem } };
62429
62476
  }
62430
- function recordStickyPick(fs18, picksFile, directory, identity, nowMs) {
62431
- const current = readPicksFile(fs18, picksFile).file.picks;
62477
+ function recordStickyPick(fs19, picksFile, directory, identity, nowMs) {
62478
+ const current = readPicksFile(fs19, picksFile).file.picks;
62432
62479
  const kept = Object.entries(current).filter(([, entry]) => nowMs - Date.parse(entry.at) <= USAGE_RETENTION_MS);
62433
62480
  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)}
62481
+ fs19.mkdirPrivate(import_node_path24.default.dirname(picksFile));
62482
+ fs19.writeFilePrivate(picksFile, `${JSON.stringify(next, null, 2)}
62436
62483
  `);
62437
62484
  }
62438
62485
 
@@ -62440,8 +62487,8 @@ function recordStickyPick(fs18, picksFile, directory, identity, nowMs) {
62440
62487
  var RESUME_FLAGS = /* @__PURE__ */ new Set(["--continue", "-c", "--resume", "-r"]);
62441
62488
  var TERMINATOR = "--";
62442
62489
  var REASONS_LOGGED = 3;
62443
- function splitMembers(pool, paths, fs18) {
62444
- const exists = (name) => loadIdentity(paths.identitiesDir, name, fs18) !== void 0;
62490
+ function splitMembers(pool, paths, fs19) {
62491
+ const exists = (name) => loadIdentity(paths.identitiesDir, name, fs19) !== void 0;
62445
62492
  return { present: pool.identities.filter(exists), missing: pool.identities.filter((name) => !exists(name)) };
62446
62493
  }
62447
62494
  function isResuming(passthrough) {
@@ -63013,7 +63060,8 @@ function runCheck(params) {
63013
63060
  nowMs: params.nowMs,
63014
63061
  env: params.env,
63015
63062
  ...params.branch === void 0 ? {} : { branch: params.branch },
63016
- ...params.branchDetached === void 0 ? {} : { branchDetached: params.branchDetached }
63063
+ ...params.branchDetached === void 0 ? {} : { branchDetached: params.branchDetached },
63064
+ descend: descendPolicyFor(params.cascade, params.home)
63017
63065
  });
63018
63066
  const resolved = resolveDecisions({ facts, cascade: params.cascade, classification: params.classification });
63019
63067
  const decisionLines = [...resolved.decisions.values()].slice().sort((a2, b) => a2.relPath < b.relPath ? -1 : a2.relPath > b.relPath ? 1 : 0).map(formatDecision);
@@ -63284,10 +63332,10 @@ var FrontDoorStateSchema = external_exports.strictObject({
63284
63332
  /** The last fatal error, kept across shutdowns so `frontdoor status` can explain a front door that is not running. */
63285
63333
  lastError: external_exports.string().optional()
63286
63334
  });
63287
- function readFrontDoorState(fs18, stateFile) {
63335
+ function readFrontDoorState(fs19, stateFile) {
63288
63336
  let raw;
63289
63337
  try {
63290
- raw = fs18.readFileUtf8(stateFile);
63338
+ raw = fs19.readFileUtf8(stateFile);
63291
63339
  } catch {
63292
63340
  return void 0;
63293
63341
  }
@@ -63301,28 +63349,28 @@ function readFrontDoorState(fs18, stateFile) {
63301
63349
  return void 0;
63302
63350
  }
63303
63351
  }
63304
- function writeFrontDoorState(fs18, stateFile, state) {
63305
- fs18.mkdirp(import_node_path28.default.dirname(stateFile));
63306
- fs18.writeFileUtf8(stateFile, `${JSON.stringify(state, null, 2)}
63352
+ function writeFrontDoorState(fs19, stateFile, state) {
63353
+ fs19.mkdirp(import_node_path28.default.dirname(stateFile));
63354
+ fs19.writeFileUtf8(stateFile, `${JSON.stringify(state, null, 2)}
63307
63355
  `);
63308
63356
  }
63309
63357
  function frontDoorOrigin(state) {
63310
63358
  const port = state?.directPort ?? state?.lastDirectPort;
63311
63359
  return port === void 0 ? void 0 : `http://127.0.0.1:${String(port)}`;
63312
63360
  }
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)}
63361
+ function writeFrontDoorSession(fs19, sessionsDir, session) {
63362
+ fs19.mkdirPrivate(sessionsDir);
63363
+ fs19.writeFilePrivate(import_node_path28.default.join(sessionsDir, `${String(session.pid)}.json`), `${JSON.stringify(session, null, 2)}
63316
63364
  `);
63317
63365
  }
63318
- function listFrontDoorSessions(fs18, sessionsDir) {
63366
+ function listFrontDoorSessions(fs19, sessionsDir) {
63319
63367
  const sessions = [];
63320
- for (const name of fs18.readdir(sessionsDir)) {
63368
+ for (const name of fs19.readdir(sessionsDir)) {
63321
63369
  if (!name.endsWith(".json")) {
63322
63370
  continue;
63323
63371
  }
63324
63372
  try {
63325
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs18.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63373
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63326
63374
  if (parsed.success) {
63327
63375
  sessions.push({ pid: parsed.data.pid, startedAt: parsed.data.startedAt });
63328
63376
  }
@@ -63332,27 +63380,27 @@ function listFrontDoorSessions(fs18, sessionsDir) {
63332
63380
  }
63333
63381
  return sessions.sort((a2, b) => a2.pid - b.pid);
63334
63382
  }
63335
- function removeFrontDoorSession(fs18, sessionsDir, pid) {
63336
- fs18.removeRecursive(import_node_path28.default.join(sessionsDir, `${String(pid)}.json`));
63383
+ function removeFrontDoorSession(fs19, sessionsDir, pid) {
63384
+ fs19.removeRecursive(import_node_path28.default.join(sessionsDir, `${String(pid)}.json`));
63337
63385
  }
63338
- function pruneDeadFrontDoorSessions(fs18, sessionsDir, isRunning) {
63386
+ function pruneDeadFrontDoorSessions(fs19, sessionsDir, isRunning) {
63339
63387
  const removed = [];
63340
- for (const session of listFrontDoorSessions(fs18, sessionsDir)) {
63388
+ for (const session of listFrontDoorSessions(fs19, sessionsDir)) {
63341
63389
  if (!isRunning(session.pid)) {
63342
- removeFrontDoorSession(fs18, sessionsDir, session.pid);
63390
+ removeFrontDoorSession(fs19, sessionsDir, session.pid);
63343
63391
  removed.push(session.pid);
63344
63392
  }
63345
63393
  }
63346
63394
  return removed;
63347
63395
  }
63348
- function liveSessionTokens(fs18, sessionsDir) {
63396
+ function liveSessionTokens(fs19, sessionsDir) {
63349
63397
  const tokens = /* @__PURE__ */ new Set();
63350
- for (const name of fs18.readdir(sessionsDir)) {
63398
+ for (const name of fs19.readdir(sessionsDir)) {
63351
63399
  if (!name.endsWith(".json")) {
63352
63400
  continue;
63353
63401
  }
63354
63402
  try {
63355
- const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs18.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63403
+ const parsed = FrontDoorSessionSchema.safeParse(JSON.parse(fs19.readFileUtf8(import_node_path28.default.join(sessionsDir, name)) ?? ""));
63356
63404
  if (parsed.success) {
63357
63405
  tokens.add(parsed.data.token);
63358
63406
  }
@@ -63717,8 +63765,8 @@ function registerCodexCommand(program2, deps) {
63717
63765
  }
63718
63766
 
63719
63767
  // src/frontdoor/commands.ts
63720
- var import_node_crypto13 = require("node:crypto");
63721
- var import_node_path31 = __toESM(require("node:path"), 1);
63768
+ var import_node_crypto11 = require("node:crypto");
63769
+ var import_node_path30 = __toESM(require("node:path"), 1);
63722
63770
  var import_node_fs11 = __toESM(require("node:fs"), 1);
63723
63771
 
63724
63772
  // src/frontdoor/custody.ts
@@ -64324,8 +64372,8 @@ var FRONTDOOR_SUPERVISOR_STILL_RUNNING = -1;
64324
64372
  var FRONTDOOR_POLL_MS = 1e3;
64325
64373
  var MS_PER_MINUTE = 6e4;
64326
64374
  async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {}) {
64327
- const { fs: fs18, paths } = ports;
64328
- const previous = readFrontDoorState(fs18, paths.frontdoorStateFile);
64375
+ const { fs: fs19, paths } = ports;
64376
+ const previous = readFrontDoorState(fs19, paths.frontdoorStateFile);
64329
64377
  let lastPort = previous?.lastPort;
64330
64378
  let lastConnectPort = previous?.lastConnectPort;
64331
64379
  let lastDirectPort = previous?.lastDirectPort;
@@ -64335,12 +64383,12 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64335
64383
  ...lastDirectPort === void 0 ? {} : { lastDirectPort }
64336
64384
  });
64337
64385
  const fail = (message) => {
64338
- writeFrontDoorState(fs18, paths.frontdoorStateFile, { lastError: message, ...sticky() });
64339
- fs18.removeRecursive(paths.frontdoorLockFile);
64386
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { lastError: message, ...sticky() });
64387
+ fs19.removeRecursive(paths.frontdoorLockFile);
64340
64388
  ports.log(`agent-shim frontdoor supervisor: ${message}`);
64341
64389
  return 1;
64342
64390
  };
64343
- writeFrontDoorState(fs18, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
64391
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { supervisorPid: ports.ownPid, ...sticky() });
64344
64392
  const previousSticky = lastPort;
64345
64393
  let http5;
64346
64394
  try {
@@ -64377,8 +64425,8 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64377
64425
  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
64426
  }
64379
64427
  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);
64428
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, { protocol: FRONT_DOOR_PROTOCOL, supervisorPid: ports.ownPid, port: http5.port, connectPort: connect3.port, directPort: direct.port, ...sticky() });
64429
+ fs19.removeRecursive(paths.frontdoorLockFile);
64382
64430
  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
64431
  let idleSince;
64384
64432
  let ticks = 0;
@@ -64387,15 +64435,15 @@ async function runFrontDoorSupervisor(idleShutdownMinutes, ports, options = {})
64387
64435
  return FRONTDOOR_SUPERVISOR_STILL_RUNNING;
64388
64436
  }
64389
64437
  ticks += 1;
64390
- pruneDeadFrontDoorSessions(fs18, paths.frontdoorSessionsDir, ports.isRunning);
64391
- if (listFrontDoorSessions(fs18, paths.frontdoorSessionsDir).length === 0) {
64438
+ pruneDeadFrontDoorSessions(fs19, paths.frontdoorSessionsDir, ports.isRunning);
64439
+ if (listFrontDoorSessions(fs19, paths.frontdoorSessionsDir).length === 0) {
64392
64440
  idleSince ??= ports.now();
64393
64441
  if (ports.now() - idleSince >= idleShutdownMinutes * MS_PER_MINUTE) {
64394
64442
  ports.log(`agent-shim frontdoor supervisor: no sessions for ${String(idleShutdownMinutes)} minute(s); closing the front door and exiting`);
64395
64443
  await direct.close();
64396
64444
  await connect3.close();
64397
64445
  await http5.close();
64398
- writeFrontDoorState(fs18, paths.frontdoorStateFile, sticky());
64446
+ writeFrontDoorState(fs19, paths.frontdoorStateFile, sticky());
64399
64447
  return 0;
64400
64448
  }
64401
64449
  } else {
@@ -64945,80 +64993,6 @@ function realConnectEffects() {
64945
64993
  };
64946
64994
  }
64947
64995
 
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
64996
  // src/frontdoor/headroomHop.ts
65023
64997
  var http3 = __toESM(require("node:http"), 1);
65024
64998
 
@@ -65411,72 +65385,8 @@ async function serveRouted(request6, deps) {
65411
65385
  }
65412
65386
  }
65413
65387
 
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
65388
  // src/codex/translate.ts
65479
- var import_node_crypto11 = require("node:crypto");
65389
+ var import_node_crypto10 = require("node:crypto");
65480
65390
 
65481
65391
  // src/codex/anthropic.ts
65482
65392
  var TextBlockSchema = external_exports.looseObject({ type: external_exports.literal("text"), text: external_exports.string() });
@@ -65588,7 +65498,7 @@ function shortToolName(name, names) {
65588
65498
  if (name.length <= CODEX_TOOL_NAME_LIMIT) {
65589
65499
  return name;
65590
65500
  }
65591
- const hash2 = (0, import_node_crypto11.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
65501
+ const hash2 = (0, import_node_crypto10.createHash)("sha256").update(name).digest("hex").slice(0, TOOL_NAME_HASH_CHARS);
65592
65502
  const shortened = `${name.slice(0, CODEX_TOOL_NAME_LIMIT - TOOL_NAME_HASH_CHARS - 1)}_${hash2}`;
65593
65503
  names.set(shortened, name);
65594
65504
  return shortened;
@@ -66429,38 +66339,6 @@ function createProviderRouteResolver(deps) {
66429
66339
  return async (request6) => await Promise.resolve(resolve(request6));
66430
66340
  }
66431
66341
 
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
66342
  // src/usage/providerQuota.ts
66465
66343
  var ProviderQuotaError = class extends Error {
66466
66344
  constructor(source, detail) {
@@ -66783,8 +66661,8 @@ function realFrontDoorSupervisorPorts(paths) {
66783
66661
  now: () => Date.now(),
66784
66662
  headroomPort: () => liveHeadroomPort(paths),
66785
66663
  // 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)()),
66664
+ hopSecret: (0, import_node_crypto11.randomUUID)(),
66665
+ custody: createCredentialCustody(() => (0, import_node_crypto11.randomUUID)()),
66788
66666
  log
66789
66667
  });
66790
66668
  let ca;
@@ -66821,14 +66699,14 @@ function realFrontDoorSupervisorPorts(paths) {
66821
66699
  },
66822
66700
  startConnectListener: async (preferredPort) => {
66823
66701
  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)();
66702
+ const transparentCapability = transparentPort === void 0 || Number.isNaN(transparentPort) ? void 0 : (0, import_node_crypto11.randomUUID)();
66825
66703
  if (transparentCapability !== void 0) {
66826
66704
  writeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, { pid: process.pid, startedAt: Date.now(), token: transparentCapability });
66827
66705
  }
66828
66706
  const leafFor = createLeafCache(loadCa(), () => /* @__PURE__ */ new Date());
66829
66707
  const capture = captureFromEnv(process.env, paths.logsDir);
66830
66708
  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")}`);
66709
+ log(`capture enabled, recording CONNECT targets and piped exchanges to ${import_node_path30.default.join(paths.logsDir, "frontdoor-capture.jsonl")}`);
66832
66710
  }
66833
66711
  const server = await startConnectServer(
66834
66712
  {
@@ -66884,49 +66762,6 @@ function realFrontDoorSupervisorPorts(paths) {
66884
66762
  }
66885
66763
  };
66886
66764
  }
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
66765
  function collectFrontDoorStatus(fsPort, paths, isRunning) {
66931
66766
  const state = readFrontDoorState(fsPort, paths.frontdoorStateFile) ?? {};
66932
66767
  return {
@@ -67279,15 +67114,15 @@ var import_node_child_process4 = require("node:child_process");
67279
67114
 
67280
67115
  // src/identityToken.ts
67281
67116
  var import_node_fs12 = __toESM(require("node:fs"), 1);
67282
- var import_node_path32 = __toESM(require("node:path"), 1);
67117
+ var import_node_path31 = __toESM(require("node:path"), 1);
67283
67118
  var TOKEN_FILE_MODE = 384;
67284
67119
  var TOKEN_DIR_MODE = 448;
67285
67120
  var OAUTH_TOKEN_RE = /^sk-ant-oat\d+-[A-Za-z0-9_-]+$/;
67286
67121
  function identityTokenDir(paths) {
67287
- return import_node_path32.default.join(paths.root, "credentials");
67122
+ return import_node_path31.default.join(paths.root, "credentials");
67288
67123
  }
67289
67124
  function identityTokenPath(paths, identityName) {
67290
- return import_node_path32.default.join(identityTokenDir(paths), `${identityName}.token`);
67125
+ return import_node_path31.default.join(identityTokenDir(paths), `${identityName}.token`);
67291
67126
  }
67292
67127
  function storeIdentityToken(paths, identityName, raw) {
67293
67128
  const token = raw.trim();
@@ -67298,7 +67133,7 @@ function storeIdentityToken(paths, identityName, raw) {
67298
67133
  import_node_fs12.default.mkdirSync(dir, { recursive: true, mode: TOKEN_DIR_MODE });
67299
67134
  import_node_fs12.default.chmodSync(dir, TOKEN_DIR_MODE);
67300
67135
  const target = identityTokenPath(paths, identityName);
67301
- const temp = import_node_path32.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
67136
+ const temp = import_node_path31.default.join(dir, `.${identityName}.${String(process.pid)}.tmp`);
67302
67137
  import_node_fs12.default.writeFileSync(temp, `${token}
67303
67138
  `, { mode: TOKEN_FILE_MODE });
67304
67139
  import_node_fs12.default.renameSync(temp, target);
@@ -67308,7 +67143,7 @@ function storeIdentityToken(paths, identityName, raw) {
67308
67143
  // src/realCredentialCache.ts
67309
67144
  var import_node_child_process3 = require("node:child_process");
67310
67145
  var import_node_fs13 = __toESM(require("node:fs"), 1);
67311
- var import_node_path33 = __toESM(require("node:path"), 1);
67146
+ var import_node_path32 = __toESM(require("node:path"), 1);
67312
67147
  var KEYCHAIN_CACHE_SERVICE = "agent-shim-credential-cache";
67313
67148
  var CACHE_DIR_MODE = 448;
67314
67149
  var CACHE_FILE_MODE = 384;
@@ -67335,8 +67170,8 @@ function security(args, stdin2) {
67335
67170
  return { status: result.status, stdout: result.stdout };
67336
67171
  }
67337
67172
  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));
67173
+ const dir = import_node_path32.default.join(root, "credential-cache");
67174
+ const filePath = (owner) => import_node_path32.default.join(dir, cacheFileNameFor(owner));
67340
67175
  return {
67341
67176
  read(store, owner) {
67342
67177
  if (store === "file") {
@@ -67515,7 +67350,7 @@ function subjectName(positional, provider) {
67515
67350
 
67516
67351
  // src/doctorReport.ts
67517
67352
  var import_node_fs14 = __toESM(require("node:fs"), 1);
67518
- var import_node_path34 = __toESM(require("node:path"), 1);
67353
+ var import_node_path33 = __toESM(require("node:path"), 1);
67519
67354
 
67520
67355
  // src/headroom/source.ts
67521
67356
  var GIT_SPEC_RE = /git\+[^@\s]+(?:@([^\s#]+))?/;
@@ -67566,7 +67401,7 @@ function validateJson(schema, input2) {
67566
67401
  return { ok: true, data: result.data };
67567
67402
  }
67568
67403
  function pushPathResolution(push, resolution) {
67569
- const ownDir = import_node_path34.default.dirname(resolution.ownExecutablePath);
67404
+ const ownDir = import_node_path33.default.dirname(resolution.ownExecutablePath);
67570
67405
  switch (resolution.agentShim.status) {
67571
67406
  case "ok":
67572
67407
  push("path-resolution", "pass", `\`agent-shim\` on PATH resolves to this running executable, ${resolution.ownExecutablePath}.`, "agent-shim");
@@ -67634,14 +67469,14 @@ function pushProvider(push, entry) {
67634
67469
  }
67635
67470
  function pushLegacyName(push, params) {
67636
67471
  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) {
67472
+ if (legacyVariables.length === 0 && import_node_path33.default.basename(params.rootPath) !== LEGACY_HOME_DIRNAME) {
67638
67473
  push("legacy-name", "pass", "Nothing here still uses the former `claude-use` name.");
67639
67474
  return;
67640
67475
  }
67641
67476
  for (const name of legacyVariables) {
67642
67477
  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
67478
  }
67644
- if (import_node_path34.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
67479
+ if (import_node_path33.default.basename(params.rootPath) === LEGACY_HOME_DIRNAME) {
67645
67480
  push(
67646
67481
  "legacy-name",
67647
67482
  "warn",
@@ -67949,18 +67784,18 @@ function collectDoctorReport(params) {
67949
67784
  const { paths } = params;
67950
67785
  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
67786
  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");
67787
+ const farmRoot = import_node_path33.default.join(paths.identitiesDir, name);
67788
+ const identityPath = import_node_path33.default.join(farmRoot, "identity.json");
67954
67789
  return { name, path: identityPath, raw: realFsPort.readFileUtf8(identityPath), farmRoot };
67955
67790
  });
67956
67791
  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
67792
  const configProfiles = profileNames.map((name) => {
67958
- const profilePath = import_node_path34.default.join(paths.configProfilesDir, `${name}.json`);
67793
+ const profilePath = import_node_path33.default.join(paths.configProfilesDir, `${name}.json`);
67959
67794
  return { name, path: profilePath, raw: realFsPort.readFileUtf8(profilePath) };
67960
67795
  });
67961
67796
  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
67797
  const providers = providerNames.map((name) => {
67963
- const providerPath = import_node_path34.default.join(paths.providersDir, `${name}.json`);
67798
+ const providerPath = import_node_path33.default.join(paths.providersDir, `${name}.json`);
67964
67799
  return { name, path: providerPath, raw: realFsPort.readFileUtf8(providerPath) };
67965
67800
  });
67966
67801
  const ownExecutablePath = realOwnExecutablePath();
@@ -67972,12 +67807,12 @@ function collectDoctorReport(params) {
67972
67807
  binaryDiscovery = { ok: false, message: error62 instanceof Error ? error62.message : String(error62) };
67973
67808
  }
67974
67809
  const shimState = readJson(paths.claudeShimFile, ClaudeShimStateSchema);
67975
- const pathDirs = (params.env.PATH ?? "").split(import_node_path34.default.delimiter).filter((dir) => dir !== "");
67810
+ const pathDirs = (params.env.PATH ?? "").split(import_node_path33.default.delimiter).filter((dir) => dir !== "");
67976
67811
  const claudeShimShadow = shimState === void 0 ? void 0 : refinePathShadow(
67977
67812
  findPathShadow({
67978
67813
  pathDirs,
67979
- targetDir: import_node_path34.default.dirname(shimState.targetPath),
67980
- targetFilename: import_node_path34.default.basename(shimState.targetPath),
67814
+ targetDir: import_node_path33.default.dirname(shimState.targetPath),
67815
+ targetFilename: import_node_path33.default.basename(shimState.targetPath),
67981
67816
  findExecutableInDir
67982
67817
  }),
67983
67818
  shimState.targetPath,
@@ -68000,7 +67835,7 @@ function collectDoctorReport(params) {
68000
67835
  agentShim: refinePathShadow(
68001
67836
  findPathShadow({
68002
67837
  pathDirs,
68003
- targetDir: import_node_path34.default.dirname(ownExecutablePath),
67838
+ targetDir: import_node_path33.default.dirname(ownExecutablePath),
68004
67839
  targetFilename: commandFilename(ownExecutablePath, "agent-shim"),
68005
67840
  findExecutableInDir
68006
67841
  }),
@@ -68043,11 +67878,11 @@ function registerDoctorCommand(program2, deps) {
68043
67878
  // src/headroom/commands.ts
68044
67879
  var import_node_fs15 = __toESM(require("node:fs"), 1);
68045
67880
  var import_node_net3 = __toESM(require("node:net"), 1);
68046
- var import_node_path35 = __toESM(require("node:path"), 1);
67881
+ var import_node_path34 = __toESM(require("node:path"), 1);
68047
67882
  var import_node_child_process5 = require("node:child_process");
68048
67883
 
68049
67884
  // src/headroom/settings.ts
68050
- var import_node_crypto14 = require("node:crypto");
67885
+ var import_node_crypto12 = require("node:crypto");
68051
67886
  function settingsOf(config2) {
68052
67887
  return {
68053
67888
  ...config2.mode === void 0 ? {} : { mode: config2.mode },
@@ -68072,7 +67907,7 @@ function settingsEnv(settings2) {
68072
67907
  return settings2.rolloutChannel === void 0 ? {} : { HEADROOM_ROLLOUT_CHANNEL: settings2.rolloutChannel };
68073
67908
  }
68074
67909
  function hashSettings(settings2) {
68075
- return (0, import_node_crypto14.createHash)("sha256").update(JSON.stringify([...settingsArgs(settings2), JSON.stringify(settingsEnv(settings2))])).digest("hex");
67910
+ return (0, import_node_crypto12.createHash)("sha256").update(JSON.stringify([...settingsArgs(settings2), JSON.stringify(settingsEnv(settings2))])).digest("hex");
68076
67911
  }
68077
67912
 
68078
67913
  // src/headroom/supervisor.ts
@@ -68174,9 +68009,9 @@ function compareVersions2(a2, b) {
68174
68009
  }
68175
68010
  var HEADROOM_SUPERVISOR_STILL_RUNNING = -1;
68176
68011
  async function runSupervisor(initialConfig, ports, options = {}) {
68177
- const { fs: fs18, paths } = ports;
68012
+ const { fs: fs19, paths } = ports;
68178
68013
  let config2 = initialConfig;
68179
- const previousState = readHeadroomState(fs18, paths.headroomStateFile);
68014
+ const previousState = readHeadroomState(fs19, paths.headroomStateFile);
68180
68015
  if (previousState?.supervisorPid !== void 0 && previousState.supervisorPid !== ports.ownPid && ports.isRunning(previousState.supervisorPid)) {
68181
68016
  ports.log(`agent-shim headroom supervisor ${String(ports.ownPid)}: supervisor ${String(previousState.supervisorPid)} already owns the daemon; exiting`);
68182
68017
  return 0;
@@ -68185,19 +68020,19 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68185
68020
  let lastPort = previousState?.lastPort;
68186
68021
  const sticky = () => lastPort === void 0 ? {} : { lastPort };
68187
68022
  const ownsState = () => {
68188
- const owner = readHeadroomState(fs18, paths.headroomStateFile)?.supervisorPid;
68023
+ const owner = readHeadroomState(fs19, paths.headroomStateFile)?.supervisorPid;
68189
68024
  return owner === void 0 || owner === ports.ownPid || !ports.isRunning(owner);
68190
68025
  };
68191
68026
  const writeOwnState = (state) => {
68192
68027
  if (!ownsState()) {
68193
68028
  return false;
68194
68029
  }
68195
- writeHeadroomState(fs18, paths.headroomStateFile, state);
68030
+ writeHeadroomState(fs19, paths.headroomStateFile, state);
68196
68031
  return true;
68197
68032
  };
68198
68033
  const fail = (message) => {
68199
68034
  if (writeOwnState({ lastError: message, ...sticky() })) {
68200
- fs18.removeRecursive(paths.headroomLockFile);
68035
+ fs19.removeRecursive(paths.headroomLockFile);
68201
68036
  }
68202
68037
  ports.log(`agent-shim headroom supervisor: ${message}`);
68203
68038
  return 1;
@@ -68246,7 +68081,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68246
68081
  const settingsHash = hashSettings(config2.settings);
68247
68082
  const allowlist = allowlistOf(ports);
68248
68083
  const allowlistHash = hashAllowlist(allowlist);
68249
- pruneDeadSessions(fs18, paths.headroomSessionsDir, ports.isRunning);
68084
+ pruneDeadSessions(fs19, paths.headroomSessionsDir, ports.isRunning);
68250
68085
  const ownsNow = ownsState();
68251
68086
  if (!ownsNow && !superseded) {
68252
68087
  ports.log("agent-shim headroom supervisor: another supervisor now owns state.json; serving this daemon's own sessions until they end");
@@ -68298,7 +68133,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68298
68133
  ...sticky()
68299
68134
  });
68300
68135
  if (recorded) {
68301
- fs18.removeRecursive(paths.headroomLockFile);
68136
+ fs19.removeRecursive(paths.headroomLockFile);
68302
68137
  }
68303
68138
  idleSince = void 0;
68304
68139
  ports.log(`agent-shim headroom supervisor: headroom pid ${String(pid)} ready on 127.0.0.1:${String(port)}`);
@@ -68313,7 +68148,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68313
68148
  }
68314
68149
  } else {
68315
68150
  if (runningHash !== allowlistHash || runningSettingsHash !== settingsHash || installedSource !== config2.source) {
68316
- if (sessionsForSupervisor(fs18, paths.headroomSessionsDir, ports.ownPid).length === 0) {
68151
+ if (sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid).length === 0) {
68317
68152
  ports.log("agent-shim headroom supervisor: configuration drifted and no sessions are live; restarting headroom");
68318
68153
  ports.stopProcess(headroomPid);
68319
68154
  headroomPid = void 0;
@@ -68322,7 +68157,7 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68322
68157
  continue;
68323
68158
  }
68324
68159
  }
68325
- const sessions = sessionsForSupervisor(fs18, paths.headroomSessionsDir, ports.ownPid);
68160
+ const sessions = sessionsForSupervisor(fs19, paths.headroomSessionsDir, ports.ownPid);
68326
68161
  if (sessions.length === 0) {
68327
68162
  idleSince ??= ports.now();
68328
68163
  const idleMs = ports.now() - idleSince;
@@ -68344,9 +68179,9 @@ async function runSupervisor(initialConfig, ports, options = {}) {
68344
68179
  await ports.sleep(HEADROOM_POLL_MS);
68345
68180
  }
68346
68181
  }
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))));
68182
+ function currentHeadroomAllowlist(fs19, paths) {
68183
+ const providers = readAllProviders(fs19, paths.providersDir).map((entry) => entry.provider);
68184
+ return headroomAllowlist(headroomUpstreams(providers, frontDoorOrigin(readFrontDoorState(fs19, paths.frontdoorStateFile))));
68350
68185
  }
68351
68186
  function allowlistOf(ports) {
68352
68187
  return currentHeadroomAllowlist(ports.fs, ports.paths);
@@ -68458,12 +68293,12 @@ function readInstalledHeadroomCommit() {
68458
68293
  if (toolDir.status !== 0) {
68459
68294
  return void 0;
68460
68295
  }
68461
- const libDir = import_node_path35.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
68296
+ const libDir = import_node_path34.default.join(toolDir.stdout.trim(), HEADROOM_TOOL_NAME, "lib");
68462
68297
  for (const python of realFarmFs.readdir(libDir)) {
68463
- const sitePackages = import_node_path35.default.join(libDir, python, "site-packages");
68298
+ const sitePackages = import_node_path34.default.join(libDir, python, "site-packages");
68464
68299
  for (const entry of realFarmFs.readdir(sitePackages)) {
68465
68300
  if (entry.startsWith("headroom_ai-") && entry.endsWith(".dist-info")) {
68466
- const directUrl = realFarmFs.readFileUtf8(import_node_path35.default.join(sitePackages, entry, "direct_url.json"));
68301
+ const directUrl = realFarmFs.readFileUtf8(import_node_path34.default.join(sitePackages, entry, "direct_url.json"));
68467
68302
  return directUrl === void 0 ? void 0 : parseInstalledCommit(directUrl);
68468
68303
  }
68469
68304
  }
@@ -68993,14 +68828,14 @@ function requireIdentity(paths, name) {
68993
68828
  throw new IdentityNotFoundError(name);
68994
68829
  }
68995
68830
  }
68996
- function collectUsageReport(fs18, paths, filters) {
68831
+ function collectUsageReport(fs19, paths, filters) {
68997
68832
  const { identity, provider, sinceMs } = filters;
68998
68833
  if (identity !== void 0) {
68999
68834
  requireIdentity(paths, identity);
69000
68835
  }
69001
- const log = readUsageLog(fs18, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
68836
+ const log = readUsageLog(fs19, paths.usageLogDir, sinceMs === void 0 ? {} : { sinceMs });
69002
68837
  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);
68838
+ 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
68839
  return {
69005
68840
  since: sinceMs === void 0 ? void 0 : new Date(sinceMs).toISOString(),
69006
68841
  logDir: paths.usageLogDir,
@@ -69096,15 +68931,15 @@ function formatUsageReport(report) {
69096
68931
  }
69097
68932
  return lines;
69098
68933
  }
69099
- function collectAccounts(fs18, paths, identity) {
68934
+ function collectAccounts(fs19, paths, identity) {
69100
68935
  if (identity !== void 0) {
69101
68936
  requireIdentity(paths, identity);
69102
68937
  }
69103
68938
  const names = identity === void 0 ? listIdentities(paths).map((entry) => entry.name) : [identity];
69104
68939
  return names.map((name) => ({
69105
68940
  identity: name,
69106
- account: readAccountMetadata(fs18, paths.identitiesDir, name),
69107
- usage: readUsageSnapshot(fs18, paths.usageSnapshotsDir, name)
68941
+ account: readAccountMetadata(fs19, paths.identitiesDir, name),
68942
+ usage: readUsageSnapshot(fs19, paths.usageSnapshotsDir, name)
69108
68943
  }));
69109
68944
  }
69110
68945
  function formatAccounts(views) {
@@ -69265,10 +69100,228 @@ function buildProgram(deps) {
69265
69100
  return program2;
69266
69101
  }
69267
69102
 
69268
- // src/runClaude.ts
69103
+ // src/launchWiring.ts
69269
69104
  var import_node_os8 = __toESM(require("node:os"), 1);
69270
69105
  var import_node_crypto16 = require("node:crypto");
69271
69106
 
69107
+ // src/frontdoor/realFrontDoorPort.ts
69108
+ var import_node_fs16 = __toESM(require("node:fs"), 1);
69109
+
69110
+ // src/frontdoor/ensure.ts
69111
+ var import_node_crypto13 = require("node:crypto");
69112
+ var FRONTDOOR_START_TIMEOUT_MS = 3e4;
69113
+ var FRONTDOOR_LAUNCHER_POLL_MS = 100;
69114
+ var FrontDoorStartError = class extends CliError {
69115
+ constructor(message) {
69116
+ super(message);
69117
+ this.name = "FrontDoorStartError";
69118
+ }
69119
+ };
69120
+ function ensureFrontDoor(params) {
69121
+ const { paths, ports } = params;
69122
+ const deadline = ports.now() + FRONTDOOR_START_TIMEOUT_MS;
69123
+ let spawned = false;
69124
+ let replaced = false;
69125
+ const distrusted = /* @__PURE__ */ new Set();
69126
+ let lastRejection;
69127
+ for (; ; ) {
69128
+ const state = readFrontDoorState(ports.fs, paths.frontdoorStateFile);
69129
+ const supervisorPid = state?.supervisorPid;
69130
+ if (supervisorPid !== void 0 && !distrusted.has(supervisorPid) && ports.isRunning(supervisorPid)) {
69131
+ if (state?.port !== void 0 && state.connectPort !== void 0) {
69132
+ const verdict = ports.verifyListener(state.port);
69133
+ if (verdict.ok && (state.protocol ?? 0) < FRONT_DOOR_PROTOCOL && !replaced) {
69134
+ ports.stopSupervisor(supervisorPid);
69135
+ while (ports.isRunning(supervisorPid)) {
69136
+ if (ports.now() >= deadline) {
69137
+ 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}`);
69138
+ }
69139
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
69140
+ }
69141
+ replaced = true;
69142
+ continue;
69143
+ }
69144
+ if (verdict.ok) {
69145
+ const token = (0, import_node_crypto13.randomUUID)();
69146
+ writeFrontDoorSession(ports.fs, paths.frontdoorSessionsDir, { pid: params.launcherPid, startedAt: ports.now(), token });
69147
+ return { port: state.port, connectPort: state.connectPort, token };
69148
+ }
69149
+ lastRejection = `the listener on 127.0.0.1:${String(state.port)} (recorded for pid ${String(supervisorPid)}) failed authentication: ${verdict.reason}`;
69150
+ if (spawned) {
69151
+ throw new FrontDoorStartError(`agent-shim: ${lastRejection}; refusing to send this session's credentials to it. Daemon log: ${paths.frontdoorLogPath}`);
69152
+ }
69153
+ distrusted.add(supervisorPid);
69154
+ continue;
69155
+ }
69156
+ if (state?.lastError !== void 0) {
69157
+ throw new FrontDoorStartError(`agent-shim: the front door reported a fatal error and is not serving: ${state.lastError} (daemon log: ${paths.frontdoorLogPath})`);
69158
+ }
69159
+ } else if (!spawned) {
69160
+ ports.fs.mkdirp(paths.frontdoorDir);
69161
+ const created = ports.fs.writeFileExclusive(paths.frontdoorLockFile, `${JSON.stringify({ pid: params.launcherPid, at: ports.now() })}
69162
+ `);
69163
+ if (created) {
69164
+ ports.spawnSupervisor(paths);
69165
+ spawned = true;
69166
+ } else {
69167
+ const lock = readStartLock(ports.fs, paths.frontdoorLockFile);
69168
+ if (lock === void 0 || !ports.isRunning(lock.pid)) {
69169
+ ports.fs.removeRecursive(paths.frontdoorLockFile);
69170
+ continue;
69171
+ }
69172
+ }
69173
+ }
69174
+ if (ports.now() >= deadline) {
69175
+ const lastError = state?.lastError;
69176
+ throw new FrontDoorStartError(
69177
+ `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}`
69178
+ );
69179
+ }
69180
+ ports.sleep(FRONTDOOR_LAUNCHER_POLL_MS);
69181
+ }
69182
+ }
69183
+
69184
+ // src/frontdoor/probe.ts
69185
+ var import_node_worker_threads = require("node:worker_threads");
69186
+ var PROBE_TIMEOUT_MS = 2e3;
69187
+ var PROBE_WAIT_MARGIN_MS = 1e3;
69188
+ var REASON_BYTES = 1024;
69189
+ var HEADER_SLOTS = 2;
69190
+ var INT32_BYTES = 4;
69191
+ var VERDICT_PENDING = 0;
69192
+ var VERDICT_OK = 1;
69193
+ var VERDICT_FAILED = 2;
69194
+ var PROBE_SOURCE = `
69195
+ const { workerData } = require("node:worker_threads");
69196
+ const https = require("node:https");
69197
+ const { port, ca, timeoutMs, shared, ok, failed, headerSlots } = workerData;
69198
+ const header = new Int32Array(shared, 0, headerSlots);
69199
+ const reason = new Uint8Array(shared, headerSlots * 4);
69200
+ let done = false;
69201
+ const finish = (verdict, message) => {
69202
+ if (done) return;
69203
+ done = true;
69204
+ const bytes = Buffer.from(String(message), "utf8").subarray(0, reason.length);
69205
+ reason.set(bytes);
69206
+ Atomics.store(header, 1, bytes.length);
69207
+ Atomics.store(header, 0, verdict);
69208
+ Atomics.notify(header, 0);
69209
+ };
69210
+ const request = https.get({ host: "127.0.0.1", port, path: "/healthz", ca: [ca], agent: false }, (response) => {
69211
+ let body = "";
69212
+ response.setEncoding("utf8");
69213
+ response.on("data", (chunk) => { body += chunk; });
69214
+ response.on("end", () => {
69215
+ if (response.statusCode === 200 && body === "ok") finish(ok, "");
69216
+ else finish(failed, "the listener answered its health probe with HTTP " + String(response.statusCode));
69217
+ });
69218
+ response.on("error", (error) => finish(failed, error.message));
69219
+ });
69220
+ // A hard deadline over the whole exchange, handshake included: a listener that accepts the connection and then says nothing must still fail the probe.
69221
+ setTimeout(() => { request.destroy(new Error("no answer within " + String(timeoutMs) + "ms")); }, timeoutMs);
69222
+ request.on("error", (error) => finish(failed, (error.code ? error.code + ": " : "") + error.message));
69223
+ `;
69224
+ function probeFrontDoorSync(port, caPem) {
69225
+ const shared = new SharedArrayBuffer(HEADER_SLOTS * INT32_BYTES + REASON_BYTES);
69226
+ const header = new Int32Array(shared, 0, HEADER_SLOTS);
69227
+ const worker = new import_node_worker_threads.Worker(PROBE_SOURCE, {
69228
+ eval: true,
69229
+ workerData: { port, ca: caPem, timeoutMs: PROBE_TIMEOUT_MS, shared, ok: VERDICT_OK, failed: VERDICT_FAILED, headerSlots: HEADER_SLOTS }
69230
+ });
69231
+ worker.unref();
69232
+ try {
69233
+ const waited = Atomics.wait(header, 0, VERDICT_PENDING, PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS);
69234
+ const verdict = Atomics.load(header, 0);
69235
+ if (waited === "timed-out" || verdict === VERDICT_PENDING) {
69236
+ return { ok: false, reason: `the probe did not finish within ${String(PROBE_TIMEOUT_MS + PROBE_WAIT_MARGIN_MS)}ms` };
69237
+ }
69238
+ if (verdict === VERDICT_OK) {
69239
+ return { ok: true };
69240
+ }
69241
+ const length = Atomics.load(header, 1);
69242
+ return { ok: false, reason: Buffer.from(new Uint8Array(shared, HEADER_SLOTS * INT32_BYTES, length)).toString("utf8") };
69243
+ } finally {
69244
+ void worker.terminate();
69245
+ }
69246
+ }
69247
+
69248
+ // src/frontdoor/trust.ts
69249
+ var import_node_crypto14 = require("node:crypto");
69250
+ var import_node_path35 = __toESM(require("node:path"), 1);
69251
+ var BUNDLE_NAME_HEX_DIGITS = 16;
69252
+ function resolveTrustBundle(params) {
69253
+ const { caCertFile, bundlesDir, inherited, fs: fs19 } = params;
69254
+ if (inherited === void 0 || inherited === "" || import_node_path35.default.resolve(inherited) === import_node_path35.default.resolve(caCertFile)) {
69255
+ return { path: caCertFile };
69256
+ }
69257
+ const caPem = fs19.readFileUtf8(caCertFile);
69258
+ let inheritedPem;
69259
+ try {
69260
+ inheritedPem = fs19.readFileUtf8(inherited);
69261
+ } catch (error62) {
69262
+ return {
69263
+ path: caCertFile,
69264
+ 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`
69265
+ };
69266
+ }
69267
+ if (inheritedPem.includes(caPem.trim())) {
69268
+ return { path: inherited };
69269
+ }
69270
+ const combined = `${inheritedPem.trimEnd()}
69271
+ ${caPem}`;
69272
+ 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`);
69273
+ if (!fs19.exists(bundle)) {
69274
+ fs19.mkdirp(bundlesDir);
69275
+ fs19.writeFileAtomic(bundle, combined);
69276
+ }
69277
+ return { path: bundle };
69278
+ }
69279
+
69280
+ // src/frontdoor/realFrontDoorPort.ts
69281
+ var realTrustBundleFs = {
69282
+ readFileUtf8: (file2) => import_node_fs16.default.readFileSync(file2, "utf8"),
69283
+ exists: (file2) => import_node_fs16.default.existsSync(file2),
69284
+ mkdirp: (dir) => {
69285
+ import_node_fs16.default.mkdirSync(dir, { recursive: true });
69286
+ },
69287
+ writeFileAtomic: (file2, contents) => {
69288
+ realFarmFs.writeFilePrivate(file2, contents);
69289
+ }
69290
+ };
69291
+ function realFrontDoorPort(paths, spawnDaemon) {
69292
+ return {
69293
+ ensure: (inheritedExtraCaCerts) => {
69294
+ const up = ensureFrontDoor({
69295
+ paths,
69296
+ launcherPid: process.pid,
69297
+ ports: {
69298
+ fs: realFarmFs,
69299
+ isRunning: realIsProcessRunning,
69300
+ now: () => Date.now(),
69301
+ sleep: realSleepSync,
69302
+ spawnSupervisor: (layout) => spawnDaemon(layout, "__frontdoor-supervisor", layout.frontdoorLogPath),
69303
+ stopSupervisor: (pid) => {
69304
+ process.kill(pid, "SIGTERM");
69305
+ },
69306
+ // 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.
69307
+ verifyListener: (port) => probeFrontDoorSync(port, import_node_fs16.default.readFileSync(paths.frontdoorCaCertFile, "utf8"))
69308
+ }
69309
+ });
69310
+ const trust = resolveTrustBundle({ caCertFile: paths.frontdoorCaCertFile, bundlesDir: paths.frontdoorCaBundlesDir, inherited: inheritedExtraCaCerts, fs: realTrustBundleFs });
69311
+ return {
69312
+ port: up.port,
69313
+ connectPort: up.connectPort,
69314
+ trustBundlePath: trust.path,
69315
+ ...trust.warning === void 0 ? {} : { trustWarning: trust.warning },
69316
+ sessionToken: up.token
69317
+ };
69318
+ },
69319
+ release: () => {
69320
+ removeFrontDoorSession(realFarmFs, paths.frontdoorSessionsDir, process.pid);
69321
+ }
69322
+ };
69323
+ }
69324
+
69272
69325
  // src/launcher.ts
69273
69326
  var import_node_crypto15 = require("node:crypto");
69274
69327
  var import_node_path37 = __toESM(require("node:path"), 1);
@@ -69517,7 +69570,7 @@ function resolveIdentityCredential(identity, credential, env, port) {
69517
69570
  return resolution.ok ? resolution : { ok: false, status: CREDENTIAL_UNAVAILABLE_EXIT, message: resolution.message };
69518
69571
  }
69519
69572
  function pickFromPool(decided, params, parsedArgv) {
69520
- const { paths, fs: fs18, proc, log } = params;
69573
+ const { paths, fs: fs19, proc, log } = params;
69521
69574
  if (decided.pool === void 0) {
69522
69575
  return { identityDecision: decided };
69523
69576
  }
@@ -69531,7 +69584,7 @@ function pickFromPool(decided, params, parsedArgv) {
69531
69584
  selectedVia: decided.source,
69532
69585
  pools: params.pools,
69533
69586
  paths,
69534
- fs: fs18,
69587
+ fs: fs19,
69535
69588
  usageFs: farmRuntime.fs,
69536
69589
  cwd: farmRuntime.cwd,
69537
69590
  now: farmRuntime.now,
@@ -69546,8 +69599,8 @@ function pickFromPool(decided, params, parsedArgv) {
69546
69599
  }
69547
69600
  return { identityDecision: { ...decided, name: resolution.identity }, poolExplanation: resolution.explanation };
69548
69601
  }
69549
- function runLauncher(params) {
69550
- const { paths, fs: fs18, spawn: spawn3, proc, log } = params;
69602
+ function prepareLaunch(params) {
69603
+ const { paths, fs: fs19, proc, log } = params;
69551
69604
  const { env, argv } = proc;
69552
69605
  const parsedArgv = parseLauncherArgv(argv);
69553
69606
  const cliOverride = buildCliOverride({
@@ -69562,7 +69615,7 @@ function runLauncher(params) {
69562
69615
  argv0Identity: parsedArgv.identity,
69563
69616
  directoryPinnedIdentity: params.directoryPinnedIdentity,
69564
69617
  readActiveIdentityFile: () => {
69565
- const raw = fs18.readFileUtf8(paths.activeIdentityFile);
69618
+ const raw = fs19.readFileUtf8(paths.activeIdentityFile);
69566
69619
  if (raw === void 0) {
69567
69620
  return void 0;
69568
69621
  }
@@ -69597,7 +69650,7 @@ function runLauncher(params) {
69597
69650
  }
69598
69651
  let loadedIdentity;
69599
69652
  if (identityDecision.name !== void 0) {
69600
- loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs18);
69653
+ loadedIdentity = loadIdentity(paths.identitiesDir, identityDecision.name, fs19);
69601
69654
  if (loadedIdentity === void 0) {
69602
69655
  log.error(
69603
69656
  `agent-shim: no identity named "${identityDecision.name}" (selected via ${identityDecision.source}). Run \`agent-shim identity add ${identityDecision.name}\` first.`
@@ -69612,7 +69665,7 @@ function runLauncher(params) {
69612
69665
  identityDefaultConfigProfile: loadedIdentity?.config.defaultConfigProfile,
69613
69666
  globalDefaultConfigProfile: params.globalDefaultConfigProfile
69614
69667
  });
69615
- if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs18.readConfigFile(import_node_path37.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
69668
+ if (configProfileDecision.name !== void 0 && params.allowMissingConfigProfile !== true && fs19.readConfigFile(import_node_path37.default.join(paths.configProfilesDir, `${configProfileDecision.name}.json`)) === void 0) {
69616
69669
  log.error(
69617
69670
  `agent-shim: no configuration profile named "${configProfileDecision.name}" (selected via ${configProfileDecision.source}). Run \`agent-shim profile add ${configProfileDecision.name}\` first.`
69618
69671
  );
@@ -69621,7 +69674,7 @@ function runLauncher(params) {
69621
69674
  const farmContext = farm !== void 0 && farmIdentity !== void 0 ? { farm, identity: farmIdentity, cascade: farm.loadCascade(configProfileDecision.name, cliOverride) } : void 0;
69622
69675
  const provider = parsedArgv.provider === false ? void 0 : resolveProvider({
69623
69676
  paths,
69624
- port: fs18,
69677
+ port: fs19,
69625
69678
  env,
69626
69679
  ...params.credentials === void 0 ? {} : { credentials: params.credentials },
69627
69680
  ...parsedArgv.provider === void 0 ? {} : { cliProvider: parsedArgv.provider },
@@ -69773,32 +69826,25 @@ function runLauncher(params) {
69773
69826
  sessionId: (0, import_node_crypto15.randomUUID)()
69774
69827
  });
69775
69828
  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();
69829
+ const release = () => {
69830
+ for (const registered of releases) {
69831
+ registered();
69782
69832
  }
69783
69833
  };
69834
+ return { bin: discovered.path, args: finalArgv, env: finalEnv, release };
69835
+ }
69836
+ function runLauncher(params) {
69837
+ const plan = prepareLaunch(params);
69784
69838
  try {
69785
- spawnClaude({
69786
- bin: discovered.path,
69787
- args: finalArgv,
69788
- env: finalEnv,
69789
- spawn: spawn3,
69790
- proc,
69791
- beforeExit: releaseAll
69792
- });
69839
+ spawnClaude({ bin: plan.bin, args: plan.args, env: plan.env, spawn: params.spawn, proc: params.proc, beforeExit: plan.release });
69793
69840
  } finally {
69794
- releaseAll();
69841
+ plan.release();
69795
69842
  }
69796
69843
  }
69797
69844
 
69798
- // src/runClaude.ts
69799
- function buildFarmRuntime(paths) {
69845
+ // src/launchWiring.ts
69846
+ function buildFarmRuntime(paths, cwd) {
69800
69847
  const home = import_node_os8.default.homedir();
69801
- const cwd = process.cwd();
69802
69848
  const read = cosmiconfigReader();
69803
69849
  const classification = loadClassification(paths);
69804
69850
  const loaded = loadCascadeInput({ paths, home, cwd, read });
@@ -69832,9 +69878,30 @@ function buildFarmRuntime(paths) {
69832
69878
  ...loaded.globalConfig?.pools === void 0 ? {} : { pools: loaded.globalConfig.pools }
69833
69879
  };
69834
69880
  }
69881
+ function realPrepareLaunchParams(paths, options) {
69882
+ const { farm } = options;
69883
+ return {
69884
+ paths,
69885
+ fs: realFsPort,
69886
+ proc: options.proc,
69887
+ log: options.log,
69888
+ resolveClaudeBinary: realResolveClaudeBinary(resolveOwnInstallDirs(paths, realOwnExecutablePath())),
69889
+ farm: farm.runtime,
69890
+ headroom: realHeadroomPort(paths, { spawnDaemon: options.spawnDaemon, cwd: farm.runtime.cwd }),
69891
+ frontdoor: realFrontDoorPort(paths, options.spawnDaemon),
69892
+ credentials: { ...realCredentialPort, cache: realCredentialCacheEnv(paths) },
69893
+ ...farm.directoryIdentity === void 0 ? {} : { directoryPinnedIdentity: farm.directoryIdentity },
69894
+ ...farm.directoryConfigProfile === void 0 ? {} : { directoryRuleConfigProfile: farm.directoryConfigProfile },
69895
+ ...farm.globalDefaultConfigProfile === void 0 ? {} : { globalDefaultConfigProfile: farm.globalDefaultConfigProfile },
69896
+ ...farm.pools === void 0 ? {} : { pools: farm.pools },
69897
+ ...options.allowMissingConfigProfile === void 0 ? {} : { allowMissingConfigProfile: options.allowMissingConfigProfile }
69898
+ };
69899
+ }
69900
+
69901
+ // src/runClaude.ts
69835
69902
  async function runClaude(argvOverride) {
69836
69903
  const paths = resolveLayoutPaths();
69837
- const farm = buildFarmRuntime(paths);
69904
+ const farm = buildFarmRuntime(paths, process.cwd());
69838
69905
  let allowMissingConfigProfile = false;
69839
69906
  if (process.stdin.isTTY) {
69840
69907
  const procForDecision = argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride };
@@ -69884,21 +69951,14 @@ async function runClaude(argvOverride) {
69884
69951
  }
69885
69952
  }
69886
69953
  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
69954
+ ...realPrepareLaunchParams(paths, {
69955
+ proc: argvOverride === void 0 ? realProcPort : { ...realProcPort, argv: argvOverride },
69956
+ log: realLogPort,
69957
+ spawnDaemon: spawnDetachedSupervisor,
69958
+ farm,
69959
+ allowMissingConfigProfile
69960
+ }),
69961
+ spawn: realSpawnPort
69902
69962
  });
69903
69963
  }
69904
69964