@cortexkit/anthropic-auth-core 2.5.2 → 2.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -348,16 +348,16 @@ async function select(terminal, items, options) {
348
348
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
349
349
  import { createHash, randomBytes, randomUUID as randomUUID4 } from "node:crypto";
350
350
  import { constants as fsConstants } from "node:fs";
351
- import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, realpath, rename as rename4, stat as stat2, unlink as unlink2 } from "node:fs/promises";
351
+ import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, realpath, rename as rename4, stat as stat3, unlink as unlink2 } from "node:fs/promises";
352
352
  import { basename, dirname as dirname4, extname, isAbsolute, join as join4, resolve as resolve4 } from "node:path";
353
353
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
354
354
 
355
355
  // ../../node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
356
- import { lstat } from "node:fs/promises";
356
+ import { lstat, stat } from "node:fs/promises";
357
357
  import { resolve } from "node:path";
358
- async function identity(path) {
358
+ async function identity(path, followSymlinks) {
359
359
  try {
360
- const metadata = await lstat(path);
360
+ const metadata = await (followSymlinks ? stat(path) : lstat(path));
361
361
  return metadata.isFile() ? metadata : undefined;
362
362
  } catch (error) {
363
363
  return error.code === "ENOENT" ? "absent" : undefined;
@@ -370,11 +370,15 @@ function sameIdentity(left, right) {
370
370
  }
371
371
 
372
372
  class FileReadCache {
373
+ #followSymlinks;
373
374
  #entries = new Map;
375
+ constructor(options = {}) {
376
+ this.#followSymlinks = options.followSymlinks ?? false;
377
+ }
374
378
  async read(paths, read, validateHit) {
375
379
  const resolvedPaths = paths.map((path) => resolve(path));
376
380
  const key = JSON.stringify(resolvedPaths);
377
- const probed = await Promise.all(resolvedPaths.map(identity));
381
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
378
382
  const identities = probed.every((entry) => entry !== undefined) ? probed : undefined;
379
383
  const cached = this.#entries.get(key);
380
384
  if (identities && cached && identities.every((entry, index) => {
@@ -798,7 +802,7 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
798
802
  });
799
803
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
800
804
  import { randomUUID as randomUUID3 } from "node:crypto";
801
- import { lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat } from "node:fs/promises";
805
+ import { lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
802
806
  import { dirname as dirname3, join as join3 } from "node:path";
803
807
 
804
808
  // ../../node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
@@ -1106,7 +1110,7 @@ async function acquireRefreshFileLockWithClock(options) {
1106
1110
  };
1107
1111
  }
1108
1112
  try {
1109
- const current = await stat(lockPath);
1113
+ const current = await stat2(lockPath);
1110
1114
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
1111
1115
  if (legacyExpiry > now())
1112
1116
  return { status: "live" };
@@ -1199,7 +1203,7 @@ async function acquireRefreshFileLockWithClock(options) {
1199
1203
  if (!ownedDirectory)
1200
1204
  return false;
1201
1205
  try {
1202
- await stat(evictOwnerPath);
1206
+ await stat2(evictOwnerPath);
1203
1207
  return false;
1204
1208
  } catch (error) {
1205
1209
  if (error.code !== "ENOENT")
@@ -1222,7 +1226,7 @@ async function acquireRefreshFileLockWithClock(options) {
1222
1226
  return false;
1223
1227
  stillOurs = true;
1224
1228
  try {
1225
- await stat(evictOwnerPath);
1229
+ await stat2(evictOwnerPath);
1226
1230
  return false;
1227
1231
  } catch (error) {
1228
1232
  return error.code === "ENOENT";
@@ -1270,7 +1274,7 @@ async function acquireRefreshFileLockWithClock(options) {
1270
1274
  async function recoverStaleEvictionMarker(deadline) {
1271
1275
  let evictStat;
1272
1276
  try {
1273
- evictStat = await stat(evictPath);
1277
+ evictStat = await stat2(evictPath);
1274
1278
  } catch (error) {
1275
1279
  if (error.code === "ENOENT")
1276
1280
  return "missing";
@@ -1288,7 +1292,7 @@ async function acquireRefreshFileLockWithClock(options) {
1288
1292
  if (evictStat.mtimeMs + EVICT_TTL > now()) {
1289
1293
  let hasOwner = true;
1290
1294
  try {
1291
- await stat(evictOwnerPath);
1295
+ await stat2(evictOwnerPath);
1292
1296
  } catch (error) {
1293
1297
  if (error.code === "ENOENT")
1294
1298
  hasOwner = false;
@@ -1895,7 +1899,7 @@ async function refuseWritableAncestor(parent, options = {}) {
1895
1899
  }
1896
1900
  let privateGroup;
1897
1901
  for (;; ) {
1898
- const metadata = await stat2(component).catch(() => {
1902
+ const metadata = await stat3(component).catch(() => {
1899
1903
  return;
1900
1904
  });
1901
1905
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
@@ -1926,7 +1930,7 @@ async function ensureClaustrumPrivateDirectory(directory, options = {}, what = "
1926
1930
  return;
1927
1931
  }
1928
1932
  await mkdir3(directory, { recursive: true, mode: 448 });
1929
- const metadata = await stat2(directory);
1933
+ const metadata = await stat3(directory);
1930
1934
  const uid = process.geteuid?.();
1931
1935
  if (uid !== undefined && metadata.uid !== uid) {
1932
1936
  throw new ClaustrumConsumerError("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -2628,7 +2632,7 @@ function setupPaths(io = {}) {
2628
2632
  }
2629
2633
 
2630
2634
  // ../../node_modules/@cortexkit/common-auth/dist/setup/detect.js
2631
- function stat3(path, kind) {
2635
+ function stat4(path, kind) {
2632
2636
  try {
2633
2637
  return statSync(path)[kind]();
2634
2638
  } catch {
@@ -2637,12 +2641,12 @@ function stat3(path, kind) {
2637
2641
  }
2638
2642
  var defaultSetupFileSystem = {
2639
2643
  exists: existsSync,
2640
- isFile: (path) => stat3(path, "isFile"),
2641
- isDirectory: (path) => stat3(path, "isDirectory"),
2644
+ isFile: (path) => stat4(path, "isFile"),
2645
+ isDirectory: (path) => stat4(path, "isDirectory"),
2642
2646
  isExecutable(path) {
2643
2647
  try {
2644
2648
  accessSync(path, constants.X_OK);
2645
- return stat3(path, "isFile");
2649
+ return stat4(path, "isFile");
2646
2650
  } catch {
2647
2651
  return false;
2648
2652
  }
@@ -3138,6 +3142,12 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
3138
3142
  await writeEnrollmentTokenFile2(path, file);
3139
3143
  }
3140
3144
  });
3145
+ await fence();
3146
+ const initial = await manager.status();
3147
+ if (initial.state === "approved") {
3148
+ printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
3149
+ return;
3150
+ }
3141
3151
  printLine(terminal, `Asking the vault to connect ${name}…`);
3142
3152
  const deadline = now() + ENROLLMENT_WAIT_MS;
3143
3153
  let printedRequest;
@@ -3145,7 +3155,6 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
3145
3155
  let reportedCode;
3146
3156
  let failedProposals = 0;
3147
3157
  for (;; ) {
3148
- await fence();
3149
3158
  const status = await manager.reconcile();
3150
3159
  if (status.state === "approved") {
3151
3160
  printLine(terminal, `Connected ${host} to Claustrum.`);
@@ -3191,6 +3200,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
3191
3200
  if (remaining <= 0)
3192
3201
  break;
3193
3202
  await wait(Math.min(pause, remaining));
3203
+ await fence();
3194
3204
  }
3195
3205
  if (printedRequest)
3196
3206
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -3355,7 +3365,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
3355
3365
 
3356
3366
  // ../../node_modules/@cortexkit/common-auth/dist/setup/config-write.js
3357
3367
  import { randomUUID as randomUUID5 } from "node:crypto";
3358
- import { mkdir as mkdir4, open as open4, rename as rename5, stat as stat4, unlink as unlink3 } from "node:fs/promises";
3368
+ import { mkdir as mkdir4, open as open4, rename as rename5, stat as stat5, unlink as unlink3 } from "node:fs/promises";
3359
3369
  import { basename as basename2, dirname as dirname5, join as join6 } from "node:path";
3360
3370
  import { setTimeout as delay2 } from "node:timers/promises";
3361
3371
  async function writeHostConfigAtomic(file, content, options = {}) {
@@ -3365,7 +3375,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
3365
3375
  let mode;
3366
3376
  if (!windows) {
3367
3377
  try {
3368
- mode = (await stat4(file)).mode & 4095;
3378
+ mode = (await stat5(file)).mode & 4095;
3369
3379
  } catch (error) {
3370
3380
  if (error.code !== "ENOENT")
3371
3381
  throw error;
@@ -3786,7 +3796,7 @@ ${write.content}`);
3786
3796
  }
3787
3797
  // src/accounts.ts
3788
3798
  import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
3789
- import { mkdir as mkdir5, readFile as readFile5, rename as rename6, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
3799
+ import { mkdir as mkdir5, readFile as readFile5, rename as rename6, rm as rm4, stat as stat6, writeFile } from "node:fs/promises";
3790
3800
  import { homedir as homedir2 } from "node:os";
3791
3801
  import { dirname as dirname6, join as join8 } from "node:path";
3792
3802
 
@@ -5018,7 +5028,7 @@ async function acquireRefreshFileLock2(options) {
5018
5028
  return Number(currentOwner?.expiresAt) > now();
5019
5029
  } catch {
5020
5030
  try {
5021
- const current = await stat5(lockPath);
5031
+ const current = await stat6(lockPath);
5022
5032
  return current.mtimeMs + options.ttlMs > now();
5023
5033
  } catch {
5024
5034
  return false;
@@ -5070,7 +5080,7 @@ async function acquireRefreshFileLock2(options) {
5070
5080
  throw evictError;
5071
5081
  let evictStat;
5072
5082
  try {
5073
- evictStat = await stat5(evictPath);
5083
+ evictStat = await stat6(evictPath);
5074
5084
  } catch (statError) {
5075
5085
  if (statError.code === "ENOENT") {
5076
5086
  await backoff();
@@ -8198,7 +8208,7 @@ function quotaFields(publication, witness = "") {
8198
8208
 
8199
8209
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
8200
8210
  import { createHash as createHash3 } from "node:crypto";
8201
- import { stat as stat6 } from "node:fs/promises";
8211
+ import { stat as stat7 } from "node:fs/promises";
8202
8212
  import { resolve as resolve7 } from "node:path";
8203
8213
 
8204
8214
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
@@ -8458,7 +8468,16 @@ function decodeRoster(value) {
8458
8468
  function decodedVaultRoster(roster) {
8459
8469
  return decodeRoster(JSON.parse(JSON.stringify(roster)));
8460
8470
  }
8471
+ var rosterReadCache = new FileReadCache({
8472
+ followSymlinks: true
8473
+ });
8461
8474
  async function readVaultRoster(path) {
8475
+ if (windowsPrivateFiles)
8476
+ return readFreshVaultRoster(path);
8477
+ const roster = await rosterReadCache.read([path], ([resolvedPath = path]) => readFreshVaultRoster(resolvedPath));
8478
+ return structuredClone(roster);
8479
+ }
8480
+ async function readFreshVaultRoster(path) {
8462
8481
  let text;
8463
8482
  try {
8464
8483
  text = await readPrivateText(path, windowsPrivateFiles);
@@ -8484,7 +8503,7 @@ var WRITE_LOCK = {
8484
8503
  var DISCOVERY_LEASE = { name: "claustrum-roster", ttlMs: 30000 };
8485
8504
  async function mutateVaultRoster(path, change, options = {}) {
8486
8505
  return withLock(path, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
8487
- const current = await readVaultRoster(path);
8506
+ const current = await readFreshVaultRoster(path);
8488
8507
  const { next, result } = await change(current, {
8489
8508
  assertOwned: () => lock.assertOwned()
8490
8509
  });
@@ -8646,7 +8665,7 @@ function isVaultRosterLockRefusal(path, error) {
8646
8665
  var UNLOCKED_READ_ATTEMPTS = 4;
8647
8666
  async function fileStamp(path) {
8648
8667
  try {
8649
- const { dev, ino, size, mtimeMs } = await stat6(path);
8668
+ const { dev, ino, size, mtimeMs } = await stat7(path);
8650
8669
  return { dev, ino, size, mtimeMs };
8651
8670
  } catch {
8652
8671
  return;
@@ -9647,7 +9666,7 @@ class ClaustrumConsumer {
9647
9666
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
9648
9667
  import { createHash as createHash4 } from "node:crypto";
9649
9668
  import { channel as channel2 } from "node:diagnostics_channel";
9650
- import { readdir, stat as stat7 } from "node:fs/promises";
9669
+ import { readdir, stat as stat8 } from "node:fs/promises";
9651
9670
  import { dirname as dirname8, join as join9, resolve as resolve9 } from "node:path";
9652
9671
  var sharedRosters = new Map;
9653
9672
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -10302,7 +10321,7 @@ class ClaustrumDiscoveryHub {
10302
10321
  let newest;
10303
10322
  for (const path of candidates) {
10304
10323
  try {
10305
- const modified = (await stat7(path)).mtimeMs;
10324
+ const modified = (await stat8(path)).mtimeMs;
10306
10325
  const roster = await readVaultRoster(path);
10307
10326
  if (roster && (!newest || modified > newest.modified))
10308
10327
  newest = { modified, roster };
@@ -10528,7 +10547,7 @@ import {
10528
10547
  open as open7,
10529
10548
  realpath as realpath2,
10530
10549
  rename as rename7,
10531
- stat as stat8,
10550
+ stat as stat9,
10532
10551
  unlink as unlink4
10533
10552
  } from "node:fs/promises";
10534
10553
  import { homedir as homedir4 } from "node:os";
@@ -11067,7 +11086,7 @@ async function readBoundedJson2(path, ownership = {}) {
11067
11086
  await descriptor.close();
11068
11087
  }
11069
11088
  }
11070
- async function refuseWritableAncestor2(parent, ownership = {}, metadataAt = (path) => stat8(path).catch(() => {
11089
+ async function refuseWritableAncestor2(parent, ownership = {}, metadataAt = (path) => stat9(path).catch(() => {
11071
11090
  return;
11072
11091
  })) {
11073
11092
  const safe = await isSafeWindowsParent(parent, ownership);
@@ -12446,8 +12465,8 @@ function rotateLogFile() {
12446
12465
  try {
12447
12466
  if (!fs2.existsSync(LOG_FILE))
12448
12467
  return;
12449
- const stat9 = fs2.statSync(LOG_FILE);
12450
- if (stat9.size < MAX_FILE_SIZE)
12468
+ const stat10 = fs2.statSync(LOG_FILE);
12469
+ if (stat10.size < MAX_FILE_SIZE)
12451
12470
  return;
12452
12471
  } catch {
12453
12472
  return;
@@ -15045,6 +15064,37 @@ async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
15045
15064
  const signedBodyText = await signRequestBody(JSON.stringify(orderClaudeCodeBody(warm)));
15046
15065
  return { ok: true, bodyText: signedBodyText };
15047
15066
  }
15067
+ function sessionMetadata(target) {
15068
+ return {
15069
+ id: target.id,
15070
+ cacheExpiresAt: target.cacheExpiresAt,
15071
+ nextPrewarmAt: target.nextPrewarmAt,
15072
+ ...target.ttlMs !== undefined && { ttlMs: target.ttlMs },
15073
+ ...target.lastTouchAt !== undefined && {
15074
+ lastTouchAt: target.lastTouchAt
15075
+ },
15076
+ ...target.lastTouchKind !== undefined && {
15077
+ lastTouchKind: target.lastTouchKind
15078
+ }
15079
+ };
15080
+ }
15081
+ function stopReason(reason) {
15082
+ switch (reason) {
15083
+ case "budget":
15084
+ case "count":
15085
+ return "evicted";
15086
+ case "schedule-period-ended":
15087
+ return "schedule";
15088
+ case "retry-window-ended":
15089
+ return "retries-exhausted";
15090
+ case "cachekeep-hybrid-inactive":
15091
+ return "disabled";
15092
+ case "source-warm-idle-cap":
15093
+ return "cost-cap";
15094
+ default:
15095
+ return "policy-refused";
15096
+ }
15097
+ }
15048
15098
  function isRecord9(value) {
15049
15099
  return typeof value === "object" && value !== null && !Array.isArray(value);
15050
15100
  }
@@ -15125,6 +15175,7 @@ function cacheKeepSentCredentials(headers) {
15125
15175
  class CacheKeepManager {
15126
15176
  options;
15127
15177
  targets = new Map;
15178
+ stoppedSessions = new Map;
15128
15179
  timer = null;
15129
15180
  tickPromise = null;
15130
15181
  nextPrewarmAttemptId = 0;
@@ -15164,6 +15215,16 @@ class CacheKeepManager {
15164
15215
  nextPrewarmAt: target.nextPrewarmAt
15165
15216
  })).sort((left, right) => left.id.localeCompare(right.id));
15166
15217
  }
15218
+ registrySessions() {
15219
+ const now = this.options.now?.() ?? Date.now();
15220
+ for (const [id, session] of this.stoppedSessions)
15221
+ if (session.cacheExpiresAt <= now)
15222
+ this.stoppedSessions.delete(id);
15223
+ return [
15224
+ ...this.stoppedSessions.values(),
15225
+ ...[...this.targets.values()].map(sessionMetadata)
15226
+ ].sort((left, right) => left.id.localeCompare(right.id));
15227
+ }
15167
15228
  trackedOAuthRoute(sessionId) {
15168
15229
  const target = this.targets.get(sessionId);
15169
15230
  return target ? { oauthAccountId: target.oauthAccountId } : undefined;
@@ -15186,9 +15247,11 @@ class CacheKeepManager {
15186
15247
  cacheExpiresAt: target.cacheExpiresAt
15187
15248
  };
15188
15249
  }
15189
- untrack(id) {
15190
- if (!this.targets.has(id))
15250
+ untrack(id, reason = "session-forgotten") {
15251
+ const target = this.targets.get(id);
15252
+ if (!target)
15191
15253
  return false;
15254
+ this.retainStopped(target, reason, this.options.now?.() ?? Date.now());
15192
15255
  this.targets.delete(id);
15193
15256
  this.options.onTargetRemoved?.(id);
15194
15257
  this.publishTrackedSessions();
@@ -15209,7 +15272,7 @@ class CacheKeepManager {
15209
15272
  if (!callback)
15210
15273
  return;
15211
15274
  try {
15212
- Promise.resolve(callback(this.trackedSessions())).catch(() => {
15275
+ Promise.resolve(callback(this.registrySessions())).catch(() => {
15213
15276
  logger2.warn("cachekeep", "failed to publish tracked sessions");
15214
15277
  });
15215
15278
  } catch {
@@ -15235,9 +15298,18 @@ class CacheKeepManager {
15235
15298
  nextPrewarmAt: target.nextPrewarmAt,
15236
15299
  ...details
15237
15300
  });
15301
+ this.retainStopped(target, stopReason(reason), now);
15238
15302
  this.targets.delete(target.id);
15239
15303
  this.options.onTargetRemoved?.(target.id);
15240
15304
  }
15305
+ retainStopped(target, reason, now) {
15306
+ if (now >= target.cacheExpiresAt)
15307
+ return;
15308
+ this.stoppedSessions.set(target.id, {
15309
+ ...sessionMetadata(target),
15310
+ warmStopped: { at: now, reason }
15311
+ });
15312
+ }
15241
15313
  evictOldestTarget(now, reason) {
15242
15314
  const oldest = this.targets.values().next().value;
15243
15315
  if (!oldest)
@@ -15320,6 +15392,7 @@ class CacheKeepManager {
15320
15392
  this.pruneTargets(now, today);
15321
15393
  if (this.targets.has(input.sessionId))
15322
15394
  this.targets.delete(input.sessionId);
15395
+ this.stoppedSessions.delete(input.sessionId);
15323
15396
  const headers = {};
15324
15397
  input.headers.forEach((value, key) => {
15325
15398
  headers[key] = value;
@@ -15330,8 +15403,17 @@ class CacheKeepManager {
15330
15403
  headers,
15331
15404
  bodyText: input.bodyText,
15332
15405
  bodyBytes,
15333
- cacheExpiresAt: input.retained?.cacheExpiresAt ?? now + CACHE_KEEP_TTL_MS,
15334
- nextPrewarmAt: input.retained?.nextPrewarmAt ?? now + CACHE_KEEP_TTL_MS - CACHE_KEEP_PREWARM_LEAD_MS,
15406
+ ...input.retained ? {
15407
+ ttlMs: input.retained.ttlMs,
15408
+ lastTouchAt: input.retained.lastTouchAt,
15409
+ lastTouchKind: input.retained.lastTouchKind
15410
+ } : input.sourceWarm ? {} : {
15411
+ ttlMs: input.ttlMs ?? CACHE_KEEP_TTL_MS,
15412
+ lastTouchAt: now,
15413
+ lastTouchKind: "response"
15414
+ },
15415
+ cacheExpiresAt: input.retained?.cacheExpiresAt ?? now + (input.ttlMs ?? CACHE_KEEP_TTL_MS),
15416
+ nextPrewarmAt: input.retained?.nextPrewarmAt ?? now + (input.ttlMs ?? CACHE_KEEP_TTL_MS) - CACHE_KEEP_PREWARM_LEAD_MS,
15335
15417
  consecutiveFailures: 0,
15336
15418
  dayKey: today,
15337
15419
  oauthAccountId: input.oauthAccountId,
@@ -15394,18 +15476,19 @@ class CacheKeepManager {
15394
15476
  this.pruneTargets(now, today);
15395
15477
  if (!this.targets.size) {
15396
15478
  this.publishTrackedSessions();
15397
- this.stop();
15479
+ if (!this.stoppedSessions.size)
15480
+ this.stop();
15398
15481
  return;
15399
15482
  }
15400
15483
  if (!isCacheKeepHybridActive(storage)) {
15401
- for (const target of this.targets.values()) {
15402
- if (target.sourceWarm)
15403
- this.removeTarget(target, "cachekeep-hybrid-inactive", now);
15404
- }
15484
+ for (const target of this.targets.values())
15485
+ this.removeTarget(target, "cachekeep-hybrid-inactive", now);
15405
15486
  this.publishTrackedSessions();
15406
15487
  return;
15407
15488
  }
15408
15489
  if (!isCacheKeepActiveNow(storage, new Date(now))) {
15490
+ for (const target of this.targets.values())
15491
+ this.removeTarget(target, "schedule-period-ended", now);
15409
15492
  this.publishTrackedSessions();
15410
15493
  return;
15411
15494
  }
@@ -15450,7 +15533,7 @@ class CacheKeepManager {
15450
15533
  const delay3 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
15451
15534
  target.nextPrewarmAt = Math.min(now + delay3, deadline);
15452
15535
  }
15453
- async sendPrewarm(target) {
15536
+ async sendPrewarm(target, onAccepted) {
15454
15537
  const attempt = {
15455
15538
  id: ++this.nextPrewarmAttemptId,
15456
15539
  signal: AbortSignal.timeout(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS)
@@ -15602,6 +15685,7 @@ class CacheKeepManager {
15602
15685
  }
15603
15686
  const objectData = data && typeof data === "object" && !Array.isArray(data) ? data : null;
15604
15687
  const usage = objectData?.usage;
15688
+ onAccepted?.(receivedAt);
15605
15689
  return { ok: true, ...usage && { usage } };
15606
15690
  } catch (error) {
15607
15691
  const failure = classifyCacheKeepFailure(error, stage, responseStatus);
@@ -15628,7 +15712,10 @@ class CacheKeepManager {
15628
15712
  }
15629
15713
  }
15630
15714
  async prewarm(target, now) {
15631
- const result = await this.sendPrewarm(target);
15715
+ let acceptedAt;
15716
+ const result = await this.sendPrewarm(target, (receivedAt) => {
15717
+ acceptedAt = receivedAt;
15718
+ });
15632
15719
  if (!result.ok) {
15633
15720
  if (result.refused === true) {
15634
15721
  this.removeTarget(target, result.reason, now, {
@@ -15658,7 +15745,13 @@ class CacheKeepManager {
15658
15745
  }
15659
15746
  return;
15660
15747
  }
15661
- target.cacheExpiresAt = now + CACHE_KEEP_TTL_MS;
15748
+ if (this.targets.get(target.id) !== target)
15749
+ return;
15750
+ acceptedAt ??= this.options.now?.() ?? Date.now();
15751
+ target.ttlMs = CACHE_KEEP_TTL_MS;
15752
+ target.lastTouchAt = acceptedAt;
15753
+ target.lastTouchKind = "warm";
15754
+ target.cacheExpiresAt = acceptedAt + CACHE_KEEP_TTL_MS;
15662
15755
  target.nextPrewarmAt = target.cacheExpiresAt - CACHE_KEEP_PREWARM_LEAD_MS;
15663
15756
  target.consecutiveFailures = 0;
15664
15757
  logger2.debug("cachekeep", "prewarm succeeded", {
@@ -15671,6 +15764,7 @@ class CacheKeepManager {
15671
15764
  import { randomUUID as randomUUID15 } from "node:crypto";
15672
15765
  import {
15673
15766
  link,
15767
+ lstat as lstat13,
15674
15768
  mkdir as mkdir11,
15675
15769
  readdir as readdir3,
15676
15770
  readFile as readFile12,
@@ -15679,7 +15773,8 @@ import {
15679
15773
  writeFile as writeFile4
15680
15774
  } from "node:fs/promises";
15681
15775
  import { tmpdir as tmpdir6 } from "node:os";
15682
- import { join as join21 } from "node:path";
15776
+ import * as nodePath3 from "node:path";
15777
+ import { dirname as dirname18, join as join21 } from "node:path";
15683
15778
 
15684
15779
  // src/holder-registry.ts
15685
15780
  import { execFile } from "node:child_process";
@@ -15739,7 +15834,7 @@ import { basename as basename7, dirname as dirname14, join as join16, resolve as
15739
15834
 
15740
15835
  // src/sticky-routing.ts
15741
15836
  import { createHash as createHash16, randomUUID as randomUUID12 } from "node:crypto";
15742
- import { mkdir as mkdir9, readFile as readFile8, rename as rename11, rm as rm6, stat as stat9, writeFile as writeFile3 } from "node:fs/promises";
15837
+ import { mkdir as mkdir9, readFile as readFile8, rename as rename11, rm as rm6, stat as stat10, writeFile as writeFile3 } from "node:fs/promises";
15743
15838
  import { basename as basename6, dirname as dirname13, join as join15 } from "node:path";
15744
15839
 
15745
15840
  // src/native-vault-seed.ts
@@ -19571,6 +19666,9 @@ function toNativeQuotaMap(snapshot) {
19571
19666
  const json = JSON.parse(JSON.stringify(snapshot));
19572
19667
  if (!isNativeOAuthQuotaSnapshot(json))
19573
19668
  throw new NativeQuotaCodecError;
19669
+ return encodeNativeQuotaMap(json);
19670
+ }
19671
+ function encodeNativeQuotaMap(json) {
19574
19672
  const { five_hour, seven_day, scoped, ...metadata } = json;
19575
19673
  const limits = [];
19576
19674
  const remainingPercent = {};
@@ -19630,11 +19728,18 @@ function reading(value) {
19630
19728
  return record3(value) && keys(value, ["scope", "label", "kind", "checkedAt", "usedPercent"], ["resetsAt"]) && text(value.scope) && text(value.label) && value.kind === "reading" && time(value.checkedAt) && finite(value.usedPercent) && optional2(value, "resetsAt", (entry) => typeof entry === "string");
19631
19729
  }
19632
19730
  function equalJson(a, b) {
19633
- if (Array.isArray(a) && Array.isArray(b))
19634
- return a.length === b.length && a.every((value, i) => equalJson(value, b[i]));
19731
+ if (Array.isArray(a) && Array.isArray(b)) {
19732
+ if (a.length !== b.length)
19733
+ return false;
19734
+ for (let i = 0;i < a.length; i++) {
19735
+ if (!equalJson(a[i], b[i]))
19736
+ return false;
19737
+ }
19738
+ return true;
19739
+ }
19635
19740
  if (record3(a) && record3(b))
19636
19741
  return Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => Object.hasOwn(b, key) && equalJson(a[key], b[key]));
19637
- return a === b;
19742
+ return a !== undefined && a === b;
19638
19743
  }
19639
19744
  function fromNativeQuotaMap(value) {
19640
19745
  if (!record3(value) || !keys(value, ["limits", "anthropic"], ["budget"]) || !isQuotaMap(value) || !value.limits.every(reading) || !nativeMetadata(value.anthropic))
@@ -19676,7 +19781,7 @@ function fromNativeQuotaMap(value) {
19676
19781
  };
19677
19782
  });
19678
19783
  }
19679
- if (!equalJson(toNativeQuotaMap(snapshot), value))
19784
+ if (!isNativeOAuthQuotaSnapshot(snapshot) || !equalJson(encodeNativeQuotaMap(snapshot), value))
19680
19785
  throw new NativeQuotaCodecError;
19681
19786
  return snapshot;
19682
19787
  }
@@ -20143,20 +20248,36 @@ function checkPath(path2) {
20143
20248
  if (!isAbsolute4(path2))
20144
20249
  throw new NativeRuntimeError("unsafe-runtime");
20145
20250
  }
20251
+ var runtimeCacheLimit = 4;
20252
+ var runtimeCache = new Map;
20253
+ function runtimeFileIdentity(info) {
20254
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
20255
+ }
20256
+ function freezeRuntime(value) {
20257
+ if (value === null || typeof value !== "object")
20258
+ return;
20259
+ for (const child of Object.values(value))
20260
+ freezeRuntime(child);
20261
+ Object.freeze(value);
20262
+ }
20146
20263
  async function readNativeRuntime(path2, storageId, ownership = {}) {
20147
- checkPath(path2);
20148
- if (!digest(storageId))
20149
- throw new NativeRuntimeError("invalid-runtime");
20150
20264
  const noFollow = constants2.O_NOFOLLOW ?? 0;
20151
20265
  try {
20266
+ checkPath(path2);
20267
+ if (!digest(storageId))
20268
+ throw new NativeRuntimeError("invalid-runtime");
20152
20269
  for (let attempt = 0;attempt < 2; attempt++) {
20153
- const info = await lstat6(path2);
20154
- if (!info.isFile() || !await isOwnerOnly(path2, () => (info.mode & 511) === 384 && (typeof process.geteuid !== "function" || info.uid === process.geteuid()), ownership))
20270
+ const info = await lstat6(path2, { bigint: true });
20271
+ if (!info.isFile() || !await isOwnerOnly(path2, () => (info.mode & 0o777n) === 0o600n && (typeof process.geteuid !== "function" || info.uid === BigInt(process.geteuid())), ownership))
20155
20272
  throw new NativeRuntimeError("unsafe-runtime");
20273
+ const identity2 = runtimeFileIdentity(info);
20274
+ const cached = runtimeCache.get(path2);
20275
+ if (cached?.storageId === storageId && cached.identity === identity2)
20276
+ return { status: "ready", state: cached.state };
20156
20277
  const file = await open8(path2, constants2.O_RDONLY | noFollow);
20157
20278
  try {
20158
- const opened = await file.stat();
20159
- if (!opened.isFile() || !await isOwnerOnly(path2, () => (opened.mode & 511) === 384 && (typeof process.geteuid !== "function" || opened.uid === process.geteuid()), ownership))
20279
+ const opened = await file.stat({ bigint: true });
20280
+ if (!opened.isFile() || !await isOwnerOnly(path2, () => (opened.mode & 0o777n) === 0o600n && (typeof process.geteuid !== "function" || opened.uid === BigInt(process.geteuid())), ownership))
20160
20281
  throw new NativeRuntimeError("unsafe-runtime");
20161
20282
  if (!noFollow && (opened.dev !== info.dev || opened.ino !== info.ino)) {
20162
20283
  if (attempt === 0)
@@ -20171,16 +20292,25 @@ async function readNativeRuntime(path2, storageId, ownership = {}) {
20171
20292
  throw new NativeRuntimeError("invalid-runtime");
20172
20293
  throw error;
20173
20294
  }
20174
- return {
20175
- status: "ready",
20176
- state: decodeNativeRuntime(parseJsonRedacted(contents), storageId)
20177
- };
20295
+ const state = decodeNativeRuntime(parseJsonRedacted(contents), storageId);
20296
+ freezeRuntime(state);
20297
+ if (runtimeFileIdentity(opened) === identity2) {
20298
+ runtimeCache.delete(path2);
20299
+ runtimeCache.set(path2, { storageId, identity: identity2, state });
20300
+ if (runtimeCache.size > runtimeCacheLimit) {
20301
+ const oldest = runtimeCache.keys().next().value;
20302
+ if (oldest !== undefined)
20303
+ runtimeCache.delete(oldest);
20304
+ }
20305
+ }
20306
+ return { status: "ready", state };
20178
20307
  } finally {
20179
20308
  await file.close();
20180
20309
  }
20181
20310
  }
20182
20311
  throw new NativeRuntimeError("unsafe-runtime");
20183
20312
  } catch (error) {
20313
+ runtimeCache.delete(path2);
20184
20314
  if (missing(error))
20185
20315
  return { status: "missing" };
20186
20316
  if (error instanceof NativeRuntimeError)
@@ -21915,7 +22045,7 @@ class StickySessionRouter {
21915
22045
  }
21916
22046
  async readStateMtimeNs() {
21917
22047
  try {
21918
- return (await stat9(this.options.path, { bigint: true })).mtimeNs;
22048
+ return (await stat10(this.options.path, { bigint: true })).mtimeNs;
21919
22049
  } catch (error) {
21920
22050
  if (error.code === "ENOENT")
21921
22051
  return 0n;
@@ -23307,8 +23437,8 @@ async function linuxIncarnation(pid) {
23307
23437
  if (!boot)
23308
23438
  return null;
23309
23439
  try {
23310
- const stat10 = await readFile11(`/proc/${pid}/stat`, "utf8");
23311
- const fields2 = stat10.slice(stat10.lastIndexOf(")") + 2).split(" ");
23440
+ const stat11 = await readFile11(`/proc/${pid}/stat`, "utf8");
23441
+ const fields2 = stat11.slice(stat11.lastIndexOf(")") + 2).split(" ");
23312
23442
  const start = fields2[19];
23313
23443
  return start && /^\d+$/.test(start) ? `${boot}:${start}` : null;
23314
23444
  } catch {
@@ -23637,8 +23767,28 @@ function resetNativeHolderRegistryForTests() {
23637
23767
  ownIncarnation = undefined;
23638
23768
  }
23639
23769
 
23770
+ // src/host-paths.ts
23771
+ import { homedir as homedir5 } from "node:os";
23772
+ import * as nodePath2 from "node:path";
23773
+ function getHostHome(env = process.env, platform = process.platform) {
23774
+ return (platform === "win32" ? env.USERPROFILE || env.HOME : env.HOME) || homedir5();
23775
+ }
23776
+ function getHostDataHome(env = process.env, platform = process.platform, pathApi = nodePath2) {
23777
+ const xdg = env.XDG_DATA_HOME?.trim();
23778
+ return xdg ? pathApi.resolve(xdg) : pathApi.join(getHostHome(env, platform), ".local", "share");
23779
+ }
23780
+
23640
23781
  // src/cachekeep-registry.ts
23641
23782
  var CACHE_KEEP_REGISTRY_LEASE_MS = 3 * 60000;
23783
+ var CACHE_KEEP_STOP_REASONS = [
23784
+ "cost-cap",
23785
+ "schedule",
23786
+ "evicted",
23787
+ "policy-refused",
23788
+ "retries-exhausted",
23789
+ "session-forgotten",
23790
+ "disabled"
23791
+ ];
23642
23792
  function normalizeSession(value) {
23643
23793
  if (!value || typeof value !== "object" || Array.isArray(value))
23644
23794
  return;
@@ -23649,7 +23799,28 @@ function normalizeSession(value) {
23649
23799
  return {
23650
23800
  id: record8.id,
23651
23801
  cacheExpiresAt: record8.cacheExpiresAt,
23652
- nextPrewarmAt: record8.nextPrewarmAt
23802
+ nextPrewarmAt: record8.nextPrewarmAt,
23803
+ ...typeof record8.ttlMs === "number" && Number.isFinite(record8.ttlMs) && record8.ttlMs > 0 && { ttlMs: record8.ttlMs },
23804
+ ...typeof record8.lastTouchAt === "number" && Number.isFinite(record8.lastTouchAt) && {
23805
+ lastTouchAt: record8.lastTouchAt
23806
+ },
23807
+ ...(record8.lastTouchKind === "response" || record8.lastTouchKind === "warm") && {
23808
+ lastTouchKind: record8.lastTouchKind
23809
+ },
23810
+ ...normalizeStopped(record8.warmStopped)
23811
+ };
23812
+ }
23813
+ function normalizeStopped(value) {
23814
+ if (!value || typeof value !== "object")
23815
+ return {};
23816
+ const stopped = value;
23817
+ if (typeof stopped.at !== "number" || !Number.isFinite(stopped.at) || !CACHE_KEEP_STOP_REASONS.includes(stopped.reason))
23818
+ return {};
23819
+ return {
23820
+ warmStopped: {
23821
+ at: stopped.at,
23822
+ reason: stopped.reason
23823
+ }
23653
23824
  };
23654
23825
  }
23655
23826
  function normalizeRecord(value) {
@@ -23671,41 +23842,69 @@ function normalizeRecord(value) {
23671
23842
  function isExpiredRecord(record8, now, leaseMs) {
23672
23843
  return record8.updatedAt <= now && now - record8.updatedAt > leaseMs;
23673
23844
  }
23674
- function getDefaultCacheKeepRegistryDirectory(scope) {
23845
+ function getLegacyCacheKeepRegistryDirectory(scope) {
23675
23846
  return join21(tmpdir6(), "opencode-anthropic-auth", "cachekeep-sessions", scope);
23676
23847
  }
23848
+ function getDefaultCacheKeepRegistryDirectory(scope, env = process.env, platform = process.platform, pathApi = nodePath3) {
23849
+ return pathApi.join(getHostDataHome(env, platform, pathApi), "cortexkit", "anthropic-auth", "cachekeep-sessions", scope);
23850
+ }
23851
+ function getCacheKeepRegistryDirectories(scope, override, env = process.env) {
23852
+ const directory = override || env[scope === "pi" ? "PI_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR" : "OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR"];
23853
+ return {
23854
+ directory: directory || getDefaultCacheKeepRegistryDirectory(scope, env),
23855
+ legacyDirectory: directory ? undefined : getLegacyCacheKeepRegistryDirectory(scope)
23856
+ };
23857
+ }
23677
23858
 
23678
23859
  class CacheKeepSessionRegistry {
23679
23860
  options;
23680
- filePath;
23861
+ directories;
23862
+ filePaths;
23681
23863
  writeChain = Promise.resolve();
23682
23864
  lastSweepAt;
23683
23865
  constructor(options) {
23684
23866
  this.options = options;
23685
23867
  const instanceId = options.instanceId ?? `${process.pid}-${randomUUID15()}`;
23686
- this.filePath = join21(options.directory, `${instanceId}.json`);
23868
+ this.directories = [
23869
+ ...new Set([options.directory, options.legacyDirectory].filter((dir) => !!dir))
23870
+ ];
23871
+ this.filePaths = this.directories.map((dir) => join21(dir, `${instanceId}.json`));
23687
23872
  }
23688
23873
  publish(sessions) {
23689
23874
  const snapshot = sessions.map((session) => ({ ...session }));
23690
23875
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
23691
23876
  const now = this.options.now?.() ?? Date.now();
23692
23877
  const leaseMs = this.options.leaseMs ?? CACHE_KEEP_REGISTRY_LEASE_MS;
23693
- if (snapshot.length === 0) {
23694
- await rm7(this.filePath, { force: true });
23695
- } else {
23696
- await mkdir11(this.options.directory, { recursive: true, mode: 448 });
23697
- const tempPath = `${this.filePath}.${randomUUID15()}.tmp`;
23698
- const record8 = {
23699
- version: 1,
23700
- updatedAt: now,
23701
- sessions: snapshot,
23702
- writer: writerStamp()
23703
- };
23704
- await writeFile4(tempPath, `${JSON.stringify(record8)}
23705
- `, {
23706
- mode: 384
23707
- });
23708
- await rename12(tempPath, this.filePath);
23878
+ const record8 = {
23879
+ version: 1,
23880
+ updatedAt: now,
23881
+ sessions: snapshot,
23882
+ writer: writerStamp()
23883
+ };
23884
+ for (const filePath of this.filePaths) {
23885
+ if (snapshot.length === 0) {
23886
+ await rm7(filePath, { force: true });
23887
+ continue;
23888
+ }
23889
+ const directory = dirname18(filePath);
23890
+ if (!await ensureWindowsOwnerOnlyDirectory(directory, this.options.ownerOnly)) {
23891
+ await mkdir11(directory, { recursive: true, mode: 448 });
23892
+ }
23893
+ const stat11 = await lstat13(directory);
23894
+ if (!stat11.isDirectory() || stat11.isSymbolicLink() || !await isOwnerOnly(directory, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 448, this.options.ownerOnly))
23895
+ throw new Error("Unsafe CacheKeep registry directory");
23896
+ const tempPath = `${filePath}.${randomUUID15()}.tmp`;
23897
+ try {
23898
+ const bytes = `${JSON.stringify(record8)}
23899
+ `;
23900
+ if (!await createWindowsOwnerOnly(tempPath, bytes, this.options.ownerOnly))
23901
+ await writeFile4(tempPath, bytes, { flag: "wx", mode: 384 });
23902
+ await renameWithWindowsSharingRetry(tempPath, filePath, {
23903
+ platform: this.options.ownerOnly?.platform
23904
+ });
23905
+ } finally {
23906
+ await rm7(tempPath, { force: true });
23907
+ }
23709
23908
  }
23710
23909
  await this.sweepExpiredRecords(now, leaseMs);
23711
23910
  });
@@ -23716,15 +23915,9 @@ class CacheKeepSessionRegistry {
23716
23915
  const now = this.options.now?.() ?? Date.now();
23717
23916
  const leaseMs = this.options.leaseMs ?? CACHE_KEEP_REGISTRY_LEASE_MS;
23718
23917
  await this.sweepExpiredRecords(now, leaseMs);
23719
- let names;
23720
- try {
23721
- names = (await readdir3(this.options.directory)).filter((name) => name.endsWith(".json"));
23722
- } catch {
23723
- names = [];
23724
- }
23725
- const records = await Promise.all(names.map(async (name) => {
23918
+ const records = await Promise.all((await this.recordPaths()).map(async (path2) => {
23726
23919
  try {
23727
- const raw = await readFile12(join21(this.options.directory, name), "utf8");
23920
+ const raw = await readFile12(path2, "utf8");
23728
23921
  return normalizeRecord(JSON.parse(raw));
23729
23922
  } catch {
23730
23923
  return;
@@ -23752,22 +23945,32 @@ class CacheKeepSessionRegistry {
23752
23945
  }
23753
23946
  async dispose() {
23754
23947
  await this.writeChain.catch(() => {});
23755
- await rm7(this.filePath, { force: true });
23948
+ await Promise.all(this.filePaths.map((path2) => rm7(path2, { force: true })));
23949
+ }
23950
+ async recordPaths() {
23951
+ return (await Promise.all(this.directories.map(async (directory) => {
23952
+ try {
23953
+ return (await readdir3(directory)).filter((name) => name.endsWith(".json")).map((name) => join21(directory, name));
23954
+ } catch {
23955
+ return [];
23956
+ }
23957
+ }))).flat();
23958
+ }
23959
+ async mayRemove(recordPath, record8, now, leaseMs) {
23960
+ if (!isExpiredRecord(record8, now, leaseMs))
23961
+ return false;
23962
+ const pid = Number(/(?:^|[/\\])(\d+)-[^/\\]+\.json(?:\..+\.sweep)?$/.exec(recordPath)?.[1]);
23963
+ if (!Number.isSafeInteger(pid) || pid <= 0)
23964
+ return false;
23965
+ return !await holderEntryIsLive({ pid, incarnation: null, registeredAt: record8.updatedAt }, this.options.liveness);
23756
23966
  }
23757
23967
  async sweepExpiredRecords(now, leaseMs) {
23758
23968
  if (this.lastSweepAt !== undefined && now - this.lastSweepAt < leaseMs) {
23759
23969
  return;
23760
23970
  }
23761
23971
  this.lastSweepAt = now;
23762
- let names;
23763
- try {
23764
- names = (await readdir3(this.options.directory)).filter((name) => name.endsWith(".json"));
23765
- } catch {
23766
- return;
23767
- }
23768
- await Promise.all(names.map(async (name) => {
23769
- const recordPath = join21(this.options.directory, name);
23770
- if (recordPath === this.filePath)
23972
+ await Promise.all((await this.recordPaths()).map(async (recordPath) => {
23973
+ if (this.filePaths.includes(recordPath))
23771
23974
  return;
23772
23975
  let initialRecord;
23773
23976
  try {
@@ -23775,7 +23978,7 @@ class CacheKeepSessionRegistry {
23775
23978
  } catch {
23776
23979
  return;
23777
23980
  }
23778
- if (!initialRecord || !isExpiredRecord(initialRecord, now, leaseMs)) {
23981
+ if (!initialRecord || !await this.mayRemove(recordPath, initialRecord, now, leaseMs)) {
23779
23982
  return;
23780
23983
  }
23781
23984
  const sweptPath = `${recordPath}.${randomUUID15()}.sweep`;
@@ -23790,7 +23993,7 @@ class CacheKeepSessionRegistry {
23790
23993
  raw = await readFile12(sweptPath, "utf8");
23791
23994
  record8 = normalizeRecord(JSON.parse(raw));
23792
23995
  } catch {}
23793
- if (record8 && isExpiredRecord(record8, now, leaseMs)) {
23996
+ if (record8 && await this.mayRemove(recordPath, record8, now, leaseMs)) {
23794
23997
  try {
23795
23998
  await rm7(sweptPath, { force: true });
23796
23999
  } catch {}
@@ -23813,11 +24016,12 @@ class CacheKeepSessionRegistry {
23813
24016
  if (raw === undefined)
23814
24017
  return;
23815
24018
  try {
23816
- await writeFile4(recordPath, raw, {
23817
- encoding: "utf8",
23818
- flag: "wx",
23819
- mode: 384
23820
- });
24019
+ if (!await createWindowsOwnerOnly(recordPath, raw, this.options.ownerOnly))
24020
+ await writeFile4(recordPath, raw, {
24021
+ encoding: "utf8",
24022
+ flag: "wx",
24023
+ mode: 384
24024
+ });
23821
24025
  } catch (writeError) {
23822
24026
  const writeCode = writeError && typeof writeError === "object" && "code" in writeError ? writeError.code : undefined;
23823
24027
  if (writeCode !== "EEXIST")
@@ -27183,7 +27387,7 @@ import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node
27183
27387
  // src/migration-source.ts
27184
27388
  import { createHash as createHash22 } from "node:crypto";
27185
27389
  import { constants as constants3 } from "node:fs";
27186
- import { lstat as lstat13, open as open10 } from "node:fs/promises";
27390
+ import { lstat as lstat14, open as open10 } from "node:fs/promises";
27187
27391
  class NativeMigrationSourceError extends Error {
27188
27392
  role;
27189
27393
  code;
@@ -27226,7 +27430,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27226
27430
  });
27227
27431
  let initial;
27228
27432
  try {
27229
- initial = await lstat13(path2, { bigint: true });
27433
+ initial = await lstat14(path2, { bigint: true });
27230
27434
  } catch (error) {
27231
27435
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
27232
27436
  return missing2;
@@ -27264,7 +27468,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27264
27468
  chunks.push(chunk.subarray(0, read.bytesRead));
27265
27469
  }
27266
27470
  const after = await handle.stat({ bigint: true });
27267
- const current = await lstat13(path2, { bigint: true });
27471
+ const current = await lstat14(path2, { bigint: true });
27268
27472
  if (before.uid !== after.uid || before.gid !== after.gid || before.mode !== after.mode || current.uid !== before.uid || current.gid !== before.gid || current.mode !== before.mode || before.dev !== after.dev || before.ino !== after.ino || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || before.size !== after.size || current.dev !== before.dev || current.ino !== before.ino || current.isSymbolicLink() || current.mtimeNs !== before.mtimeNs || current.ctimeNs !== before.ctimeNs || current.size !== before.size || BigInt(bytes) !== before.size) {
27269
27473
  throw new NativeMigrationSourceError(role, "source-changed");
27270
27474
  }
@@ -33234,8 +33438,8 @@ function relayGeneration(input) {
33234
33438
  }
33235
33439
  // src/native-host-auth-write.ts
33236
33440
  import { randomUUID as randomUUID18 } from "node:crypto";
33237
- import { lstat as lstat14, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33238
- import { dirname as dirname18, isAbsolute as isAbsolute6, join as join22 } from "node:path";
33441
+ import { lstat as lstat15, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33442
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join22 } from "node:path";
33239
33443
  class NativeHostAuthWriteError extends Error {
33240
33444
  code;
33241
33445
  effect;
@@ -33296,7 +33500,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33296
33500
  const removingFile = host === "pi" && Object.keys(next).length === 0;
33297
33501
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
33298
33502
  if (!removingFile) {
33299
- stage = join22(dirname18(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33503
+ stage = join22(dirname19(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33300
33504
  const bytes = `${JSON.stringify(next, null, 2)}
33301
33505
  `;
33302
33506
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
@@ -33346,7 +33550,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33346
33550
  } finally {
33347
33551
  if (stage && ownedStage) {
33348
33552
  try {
33349
- const current = await lstat14(stage);
33553
+ const current = await lstat15(stage);
33350
33554
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
33351
33555
  await unlink7(stage);
33352
33556
  } catch {}
@@ -33356,8 +33560,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
33356
33560
 
33357
33561
  // src/native-migration.ts
33358
33562
  import { createHash as createHash24 } from "node:crypto";
33359
- import { lstat as lstat15, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
33360
- import { dirname as dirname19, isAbsolute as isAbsolute7 } from "node:path";
33563
+ import { lstat as lstat16, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
33564
+ import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
33361
33565
  class NativeMigrationError extends Error {
33362
33566
  code;
33363
33567
  constructor(code) {
@@ -33406,7 +33610,7 @@ function owned(snapshot) {
33406
33610
  }
33407
33611
  async function absent(path2) {
33408
33612
  try {
33409
- await lstat15(path2);
33613
+ await lstat16(path2);
33410
33614
  return false;
33411
33615
  } catch (error) {
33412
33616
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -34110,7 +34314,7 @@ async function runNativeMigration(input, hooks = {}) {
34110
34314
  refuse3();
34111
34315
  await step("before:host");
34112
34316
  await recheck();
34113
- await mkdir12(dirname19(operation.hostAuthPath), {
34317
+ await mkdir12(dirname20(operation.hostAuthPath), {
34114
34318
  recursive: true,
34115
34319
  mode: 448
34116
34320
  });
@@ -36590,7 +36794,7 @@ function waitForRequest(pending, signal) {
36590
36794
  });
36591
36795
  }
36592
36796
  // src/native-vault-connection.ts
36593
- import { dirname as dirname21, join as join23, resolve as resolve16 } from "node:path";
36797
+ import { dirname as dirname22, join as join23, resolve as resolve16 } from "node:path";
36594
36798
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
36595
36799
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
36596
36800
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -36600,13 +36804,13 @@ function placeholderSecret(integrationID) {
36600
36804
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
36601
36805
  import { createHash as createHash25 } from "node:crypto";
36602
36806
  import { constants as constants4 } from "node:fs";
36603
- import { lstat as lstat16, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
36604
- import { dirname as dirname20, resolve as resolve15 } from "node:path";
36807
+ import { lstat as lstat17, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
36808
+ import { dirname as dirname21, resolve as resolve15 } from "node:path";
36605
36809
  import { setTimeout as sleep } from "node:timers/promises";
36606
36810
 
36607
36811
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
36608
36812
  import { rmdirSync, statSync as statSync5, utimesSync } from "node:fs";
36609
- import { mkdir as mkdir13, rmdir, stat as stat10, utimes } from "node:fs/promises";
36813
+ import { mkdir as mkdir13, rmdir, stat as stat11, utimes } from "node:fs/promises";
36610
36814
  var STALE = 30000;
36611
36815
  var RENEWAL_STALE = 1e4;
36612
36816
  var UPDATE = 3000;
@@ -36650,7 +36854,7 @@ async function acquire(path2, stale) {
36650
36854
  throw held();
36651
36855
  let mtime;
36652
36856
  try {
36653
- mtime = (await stat10(path2)).mtime.getTime();
36857
+ mtime = (await stat11(path2)).mtime.getTime();
36654
36858
  } catch (error2) {
36655
36859
  if (errorCode4(error2) === "ENOENT")
36656
36860
  return acquire(path2, 0);
@@ -36663,7 +36867,7 @@ async function acquire(path2, stale) {
36663
36867
  }
36664
36868
  let created;
36665
36869
  try {
36666
- const st = await stat10(path2);
36870
+ const st = await stat11(path2);
36667
36871
  created = { dev: st.dev, ino: st.ino };
36668
36872
  } catch {
36669
36873
  created = undefined;
@@ -36673,14 +36877,14 @@ async function acquire(path2, stale) {
36673
36877
  const probe2 = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
36674
36878
  await utimes(path2, probe2, probe2);
36675
36879
  }
36676
- const observed = await stat10(path2);
36880
+ const observed = await stat11(path2);
36677
36881
  const mtime = observed.mtime.getTime();
36678
36882
  precision ??= mtime % 1000 === 0 ? "s" : "ms";
36679
36883
  return { dev: observed.dev, ino: observed.ino, mtime };
36680
36884
  } catch (error) {
36681
36885
  try {
36682
36886
  if (created) {
36683
- const current = await stat10(path2).catch(() => {
36887
+ const current = await stat11(path2).catch(() => {
36684
36888
  return;
36685
36889
  });
36686
36890
  if (current && current.dev === created.dev && current.ino === created.ino)
@@ -36780,7 +36984,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
36780
36984
  }
36781
36985
  let observed;
36782
36986
  try {
36783
- observed = await stat10(path2);
36987
+ observed = await stat11(path2);
36784
36988
  } catch (error) {
36785
36989
  if (errorCode4(error) !== "ENOENT")
36786
36990
  throw error;
@@ -36900,13 +37104,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
36900
37104
  let file;
36901
37105
  try {
36902
37106
  file = await open12(path2, constants4.O_RDONLY | constants4.O_NOFOLLOW);
36903
- const stat11 = await file.stat();
36904
- if (!stat11.isFile() || privateFile && (stat11.mode & 511) !== 384) {
37107
+ const stat12 = await file.stat();
37108
+ if (!stat12.isFile() || privateFile && (stat12.mode & 511) !== 384) {
36905
37109
  throw new PiSlotError("unsafe-path");
36906
37110
  }
36907
37111
  await afterReadCheck?.(path2);
36908
- const current = await lstat16(path2);
36909
- if (!current.isFile() || current.dev !== stat11.dev || current.ino !== stat11.ino) {
37112
+ const current = await lstat17(path2);
37113
+ if (!current.isFile() || current.dev !== stat12.dev || current.ino !== stat12.ino) {
36910
37114
  throw new PiSlotError("unsafe-path");
36911
37115
  }
36912
37116
  const bytes = await file.readFile();
@@ -37038,9 +37242,9 @@ function createPiSlot(options, onStep, hooks) {
37038
37242
  };
37039
37243
  try {
37040
37244
  if (windowsPrivateFiles)
37041
- await ensurePrivateDirectory(dirname20(authPath));
37245
+ await ensurePrivateDirectory(dirname21(authPath));
37042
37246
  else
37043
- await mkdir14(dirname20(authPath), { recursive: true, mode: 448 });
37247
+ await mkdir14(dirname21(authPath), { recursive: true, mode: 448 });
37044
37248
  const deadline = Date.now() + timeout;
37045
37249
  let retry = 0;
37046
37250
  while (!release2) {
@@ -37080,7 +37284,7 @@ function createPiSlot(options, onStep, hooks) {
37080
37284
  async function deleteStash(assertLock) {
37081
37285
  assertLock();
37082
37286
  await unlink9(stashPath);
37083
- await syncDir(dirname20(stashPath));
37287
+ await syncDir(dirname21(stashPath));
37084
37288
  onStep?.("stash-deleted");
37085
37289
  }
37086
37290
  return {
@@ -37100,10 +37304,10 @@ function createPiSlot(options, onStep, hooks) {
37100
37304
  throw new PiSlotError("conflict");
37101
37305
  if (!stash) {
37102
37306
  if (windowsPrivateFiles)
37103
- await ensurePrivateDirectory(dirname20(stashPath));
37307
+ await ensurePrivateDirectory(dirname21(stashPath));
37104
37308
  else {
37105
- await mkdir14(dirname20(stashPath), { recursive: true, mode: 448 });
37106
- const dir = await lstat16(dirname20(stashPath));
37309
+ await mkdir14(dirname21(stashPath), { recursive: true, mode: 448 });
37310
+ const dir = await lstat17(dirname21(stashPath));
37107
37311
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
37108
37312
  throw new PiSlotError("unsafe-path");
37109
37313
  }
@@ -37144,7 +37348,7 @@ function createPiSlot(options, onStep, hooks) {
37144
37348
  function nativePiAuthSlotPaths(options) {
37145
37349
  return {
37146
37350
  authPath: resolve16(options.authPath),
37147
- stashPath: join23(dirname21(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37351
+ stashPath: join23(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37148
37352
  provider: "anthropic",
37149
37353
  placeholderKey: placeholderSecret("anthropic")
37150
37354
  };
@@ -37276,7 +37480,7 @@ function createAnthropicOAuthFetch(options = {}) {
37276
37480
  // src/prime.ts
37277
37481
  import { createHash as createHash26 } from "node:crypto";
37278
37482
  import { realpathSync as realpathSync3 } from "node:fs";
37279
- import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat11, writeFile as writeFile5 } from "node:fs/promises";
37483
+ import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat12, writeFile as writeFile5 } from "node:fs/promises";
37280
37484
  import { tmpdir as tmpdir7 } from "node:os";
37281
37485
  import { join as join24, resolve as resolve17 } from "node:path";
37282
37486
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
@@ -37695,7 +37899,7 @@ class PrimeManager {
37695
37899
  const bootstrapMarkerPath = primeBootstrapMarkerPath(markerDir, evaluation.id);
37696
37900
  const expectedMarkerPath = storedResetEpoch === undefined ? bootstrapMarkerPath : primeMarkerPath(markerDir, evaluation.id, storedResetEpoch);
37697
37901
  try {
37698
- await stat11(expectedMarkerPath);
37902
+ await stat12(expectedMarkerPath);
37699
37903
  return;
37700
37904
  } catch (error) {
37701
37905
  if (error.code !== "ENOENT")
@@ -37936,7 +38140,7 @@ class PrimeManager {
37936
38140
  for (const entry2 of entries) {
37937
38141
  try {
37938
38142
  const path2 = join24(dir, entry2);
37939
- const s = await stat11(path2);
38143
+ const s = await stat12(path2);
37940
38144
  if (s.isDirectory()) {
37941
38145
  swept += await this.sweepMarkerDirectory(path2, now);
37942
38146
  continue;
@@ -37960,13 +38164,13 @@ class PrimeManager {
37960
38164
  import { randomUUID as randomUUID19 } from "node:crypto";
37961
38165
  import {
37962
38166
  chmod as chmod3,
37963
- lstat as lstat17,
38167
+ lstat as lstat18,
37964
38168
  mkdir as mkdir16,
37965
38169
  readdir as readdir5,
37966
38170
  readFile as readFile13,
37967
38171
  rename as rename14,
37968
38172
  rm as rm9,
37969
- stat as stat12,
38173
+ stat as stat13,
37970
38174
  writeFile as writeFile6
37971
38175
  } from "node:fs/promises";
37972
38176
  import { tmpdir as tmpdir8 } from "node:os";
@@ -38198,11 +38402,11 @@ class QuotaHeaderFeedRegistry {
38198
38402
  if (path2 === this.filePath)
38199
38403
  return;
38200
38404
  try {
38201
- const file = await stat12(path2);
38405
+ const file = await stat13(path2);
38202
38406
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
38203
38407
  return;
38204
38408
  await this.options.beforeRemoveFile?.(path2);
38205
- const current = await lstat17(path2);
38409
+ const current = await lstat18(path2);
38206
38410
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
38207
38411
  return;
38208
38412
  await (this.options.removeFile ?? ((target2) => rm9(target2)))(path2);
@@ -38404,7 +38608,7 @@ function buildClaudeQuotaSummary(input) {
38404
38608
  }
38405
38609
  // src/request-gzip.ts
38406
38610
  import { mkdir as mkdir17, readFile as readFile14, rename as rename15, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
38407
- import { basename as basename10, dirname as dirname22, join as join26 } from "node:path";
38611
+ import { basename as basename10, dirname as dirname23, join as join26 } from "node:path";
38408
38612
  import { promisify } from "node:util";
38409
38613
  import { gzip } from "node:zlib";
38410
38614
  var gzipAsync = promisify(gzip);
@@ -38528,7 +38732,7 @@ class RequestGzipLatch {
38528
38732
  return;
38529
38733
  const temporary = `${this.path}.${process.pid}.tmp`;
38530
38734
  try {
38531
- await mkdir17(dirname22(this.path), { recursive: true });
38735
+ await mkdir17(dirname23(this.path), { recursive: true });
38532
38736
  await writeFile7(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
38533
38737
  `, { mode: 384 });
38534
38738
  await rename15(temporary, this.path);
@@ -38550,7 +38754,7 @@ function getRequestGzipLatch(path2) {
38550
38754
  function getRequestGzipLatchPath(accountStoragePath) {
38551
38755
  const name = basename10(accountStoragePath);
38552
38756
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
38553
- return join26(dirname22(accountStoragePath), `${stem}-request-gzip.json`);
38757
+ return join26(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
38554
38758
  }
38555
38759
  async function decideRequestGzip(options) {
38556
38760
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -38779,12 +38983,12 @@ function executeLaneStartCommand(input) {
38779
38983
  }
38780
38984
  // src/state-layout-decision.ts
38781
38985
  import { mkdir as mkdir18, readdir as readdir8 } from "node:fs/promises";
38782
- import { homedir as homedir7 } from "node:os";
38783
- import { basename as basename13, dirname as dirname24, join as join30 } from "node:path";
38986
+ import { homedir as homedir8 } from "node:os";
38987
+ import { basename as basename13, dirname as dirname25, join as join30 } from "node:path";
38784
38988
 
38785
38989
  // src/layout-fence.ts
38786
38990
  import { open as open13, readdir as readdir6 } from "node:fs/promises";
38787
- import { homedir as homedir5 } from "node:os";
38991
+ import { homedir as homedir6 } from "node:os";
38788
38992
  import { basename as basename11, join as join27, resolve as resolve18 } from "node:path";
38789
38993
  var STATE_PATH_OVERRIDE_VARIABLES = [
38790
38994
  "OPENCODE_ANTHROPIC_AUTH_FILE",
@@ -38863,7 +39067,7 @@ async function holderFenceBlockers(input) {
38863
39067
  }
38864
39068
  return blockers;
38865
39069
  }
38866
- function defaultPreNArtifactLocations(env = process.env, home = homedir5()) {
39070
+ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
38867
39071
  const root = anthropicAuthStateRoot({
38868
39072
  xdgStateHome: env.XDG_STATE_HOME,
38869
39073
  home,
@@ -38875,8 +39079,10 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir5()) {
38875
39079
  rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
38876
39080
  cacheKeepDirs: [
38877
39081
  ...new Set([
38878
- getDefaultCacheKeepRegistryDirectory("opencode"),
38879
- getDefaultCacheKeepRegistryDirectory("pi"),
39082
+ getDefaultCacheKeepRegistryDirectory("opencode", env),
39083
+ getDefaultCacheKeepRegistryDirectory("pi", env),
39084
+ getLegacyCacheKeepRegistryDirectory("opencode"),
39085
+ getLegacyCacheKeepRegistryDirectory("pi"),
38880
39086
  env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR?.trim(),
38881
39087
  env.PI_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR?.trim()
38882
39088
  ].filter((dir) => Boolean(dir)))
@@ -38982,8 +39188,8 @@ function describeFenceBlocker(blocker) {
38982
39188
 
38983
39189
  // src/state-layout-move.ts
38984
39190
  import { randomUUID as randomUUID20 } from "node:crypto";
38985
- import { lstat as lstat18, readdir as readdir7, readFile as readFile15, stat as stat13, unlink as unlink10 } from "node:fs/promises";
38986
- import { basename as basename12, dirname as dirname23, join as join28, sep as sep2 } from "node:path";
39191
+ import { lstat as lstat19, readdir as readdir7, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39192
+ import { basename as basename12, dirname as dirname24, join as join28, sep as sep2 } from "node:path";
38987
39193
  var ACCOUNT_FILE = "anthropic-auth.json";
38988
39194
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
38989
39195
  var LAYOUT_LOCK_NAME = "runtime-layout";
@@ -39063,7 +39269,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
39063
39269
  } catch (error) {
39064
39270
  if (error instanceof LockContentionError)
39065
39271
  throw error;
39066
- throw new HolderRegistrationError("unavailable", dirname23(holderFile), error);
39272
+ throw new HolderRegistrationError("unavailable", dirname24(holderFile), error);
39067
39273
  }
39068
39274
  }
39069
39275
  async function acquireHolderLocks(dataset, ctx) {
@@ -39273,7 +39479,7 @@ function restoringPath(path2, attempt) {
39273
39479
  }
39274
39480
  async function exists3(path2) {
39275
39481
  try {
39276
- await lstat18(path2);
39482
+ await lstat19(path2);
39277
39483
  return true;
39278
39484
  } catch (error) {
39279
39485
  if (errorCode6(error) === "ENOENT")
@@ -39283,7 +39489,7 @@ async function exists3(path2) {
39283
39489
  }
39284
39490
  async function removeOwnStaging(path2) {
39285
39491
  try {
39286
- const info = await lstat18(path2);
39492
+ const info = await lstat19(path2);
39287
39493
  if (info.isFile())
39288
39494
  await unlink10(path2);
39289
39495
  } catch (error) {
@@ -39309,10 +39515,10 @@ function recordFilesProblem(record9, dataset) {
39309
39515
  return;
39310
39516
  }
39311
39517
  async function movePreconditionFailure(dataset, platform) {
39312
- const oldInfo = await stat13(dataset.oldDir);
39518
+ const oldInfo = await stat14(dataset.oldDir);
39313
39519
  let subInfo;
39314
39520
  try {
39315
- subInfo = await stat13(dataset.sub);
39521
+ subInfo = await stat14(dataset.sub);
39316
39522
  } catch (error) {
39317
39523
  if (errorCode6(error) !== "ENOENT")
39318
39524
  throw error;
@@ -39326,7 +39532,7 @@ async function movePreconditionFailure(dataset, platform) {
39326
39532
  for (const path2 of new Set([slot.configured, slot.from])) {
39327
39533
  let info;
39328
39534
  try {
39329
- info = await lstat18(path2);
39535
+ info = await lstat19(path2);
39330
39536
  } catch (error) {
39331
39537
  if (errorCode6(error) === "ENOENT")
39332
39538
  continue;
@@ -39337,13 +39543,13 @@ async function movePreconditionFailure(dataset, platform) {
39337
39543
  if (platform !== "win32" && typeof process.getuid === "function" && info.uid !== process.getuid())
39338
39544
  return `${path2} belongs to another user`;
39339
39545
  }
39340
- if (dirname23(slot.from) !== dataset.oldDir || basename12(slot.from) !== basename12(slot.configured))
39546
+ if (dirname24(slot.from) !== dataset.oldDir || basename12(slot.from) !== basename12(slot.configured))
39341
39547
  return `${slot.configured} resolves to ${slot.from}, not to a file of its own in the config folder`;
39342
39548
  const fromExists = await exists3(slot.from);
39343
39549
  anyOld ||= fromExists;
39344
39550
  if (await exists3(slot.to)) {
39345
39551
  if (fromExists) {
39346
- const [a, b] = await Promise.all([lstat18(slot.from), lstat18(slot.to)]);
39552
+ const [a, b] = await Promise.all([lstat19(slot.from), lstat19(slot.to)]);
39347
39553
  if (a.dev === b.dev && a.ino === b.ino)
39348
39554
  return `${slot.from} and ${slot.to} are the same file`;
39349
39555
  }
@@ -39761,7 +39967,7 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
39761
39967
  // src/state-layout-restore.ts
39762
39968
  import { randomUUID as randomUUID21 } from "node:crypto";
39763
39969
  import { readFile as readFile16 } from "node:fs/promises";
39764
- import { homedir as homedir6 } from "node:os";
39970
+ import { homedir as homedir7 } from "node:os";
39765
39971
  import { join as join29 } from "node:path";
39766
39972
  var DATA_ROLES = [
39767
39973
  "localPoolState",
@@ -40039,7 +40245,7 @@ async function newRestoreProblems(record9, dataset, options) {
40039
40245
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
40040
40246
  }
40041
40247
  problems.push(...await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join29(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
40042
- const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir6());
40248
+ const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40043
40249
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
40044
40250
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
40045
40251
  for (const slot of dataset.slots) {
@@ -40151,7 +40357,7 @@ function finished(record9) {
40151
40357
  }
40152
40358
  async function restoreLegacyLayout(options = {}) {
40153
40359
  const env = options.env ?? process.env;
40154
- const home = options.home ?? homedir6();
40360
+ const home = options.home ?? homedir7();
40155
40361
  const overrides = statePathOverrides(env);
40156
40362
  if (overrides.length)
40157
40363
  throw refused2(`${RESTORE_LEGACY_COMMAND} works only on OpenCode's own config folder. Unset ${overrides.join(", ")} and run it again.`);
@@ -40325,7 +40531,7 @@ async function registerHeld(holderFile, paths, kind, identity3, options, ctx) {
40325
40531
  assertOwned: () => ctx.stack.assertAll()
40326
40532
  });
40327
40533
  } catch (error) {
40328
- throw error instanceof HolderRegistrationError ? error : new HolderRegistrationError("unavailable", dirname24(holderFile), error);
40534
+ throw error instanceof HolderRegistrationError ? error : new HolderRegistrationError("unavailable", dirname25(holderFile), error);
40329
40535
  }
40330
40536
  }
40331
40537
  function deferLegacyRegistration(paths, dir, options, error) {
@@ -40447,7 +40653,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
40447
40653
  }
40448
40654
  let names2;
40449
40655
  try {
40450
- names2 = await readdir8(dirname24(journal));
40656
+ names2 = await readdir8(dirname25(journal));
40451
40657
  } catch (error) {
40452
40658
  if (error?.code === "ENOENT")
40453
40659
  return false;
@@ -40466,7 +40672,7 @@ async function recordedMovingJournal(journal, identity3, options) {
40466
40672
  try {
40467
40673
  const target2 = stateHomeTargetFor(identity3, {
40468
40674
  env: options.env ?? process.env,
40469
- home: options.home ?? homedir7()
40675
+ home: options.home ?? homedir8()
40470
40676
  });
40471
40677
  const record9 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40472
40678
  if (record9?.barriers.journal !== "present")
@@ -40507,7 +40713,7 @@ function stateFolderUnreadable(dir, cause) {
40507
40713
  }
40508
40714
  async function decideOpenCodeStateLayout(options) {
40509
40715
  const env = options.env ?? process.env;
40510
- const home = options.home ?? homedir7();
40716
+ const home = options.home ?? homedir8();
40511
40717
  const fs3 = options.fs ?? defaultStateLayoutFs();
40512
40718
  const configDir = getOpenCodeConfigDir(env, home);
40513
40719
  const newContext = () => ({
@@ -40521,7 +40727,7 @@ async function decideOpenCodeStateLayout(options) {
40521
40727
  });
40522
40728
  if (isExplicit(env)) {
40523
40729
  const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join30(configDir, ACCOUNT_FILE2);
40524
- const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname24(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
40730
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
40525
40731
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
40526
40732
  const registration = await registerNativePoolHolder({
40527
40733
  paths,
@@ -40681,9 +40887,9 @@ async function ensureSubfolder(sub, fs3) {
40681
40887
  const created = await mkdir18(sub, { recursive: true, mode: 448 });
40682
40888
  if (created === undefined)
40683
40889
  return;
40684
- for (let dir = dirname24(sub);; dir = dirname24(dir)) {
40890
+ for (let dir = dirname25(sub);; dir = dirname25(dir)) {
40685
40891
  await fs3.syncDirectory(dir);
40686
- if (dir === dirname24(created) || dir === dirname24(dir))
40892
+ if (dir === dirname25(created) || dir === dirname25(dir))
40687
40893
  break;
40688
40894
  }
40689
40895
  } catch (error) {
@@ -40761,7 +40967,7 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40761
40967
  return stay([RELOCATION_MOVE_DISABLED_REASON], false);
40762
40968
  const holdersMark = ctx.stack.size;
40763
40969
  const files = [...dataset.slots.flatMap((slot) => [slot.from, slot.to])];
40764
- const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40970
+ const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir8());
40765
40971
  const checkArtifacts = async () => {
40766
40972
  const found = await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness);
40767
40973
  return found.length ? found.map(describeFenceBlocker).join("; ") : undefined;
@@ -40828,7 +41034,7 @@ async function stateLayoutFenceStep(ctx) {
40828
41034
  var processDecisions = new Map;
40829
41035
  function decisionKey(options) {
40830
41036
  const env = options.env ?? process.env;
40831
- const home = options.home ?? homedir7();
41037
+ const home = options.home ?? homedir8();
40832
41038
  return JSON.stringify([
40833
41039
  getOpenCodeConfigDir(env, home),
40834
41040
  home,
@@ -41238,8 +41444,11 @@ export {
41238
41444
  getMaxSameAccountWait,
41239
41445
  getLogLevel,
41240
41446
  getLogFilePath,
41447
+ getLegacyCacheKeepRegistryDirectory,
41241
41448
  getKillswitchThresholdsForAccount,
41242
41449
  getKillswitchConfig,
41450
+ getHostHome,
41451
+ getHostDataHome,
41243
41452
  getHostClaustrumEnrollmentPaths,
41244
41453
  getFallbackReauthLabels,
41245
41454
  getDumpDirectory,
@@ -41254,6 +41463,7 @@ export {
41254
41463
  getClaudeCodeIdentityForVerifiedAccount,
41255
41464
  getClaudeCodeIdentity,
41256
41465
  getCacheKeepWindow,
41466
+ getCacheKeepRegistryDirectories,
41257
41467
  getCache1hPersistentMode,
41258
41468
  getCache1hMode,
41259
41469
  getAccountStoragePath,
@@ -41566,6 +41776,7 @@ export {
41566
41776
  CACHE_KEEP_TRANSIENT_RETRY_STEP_MS,
41567
41777
  CACHE_KEEP_TRANSIENT_RETRY_MAX_MS,
41568
41778
  CACHE_KEEP_TICK_MS,
41779
+ CACHE_KEEP_STOP_REASONS,
41569
41780
  CACHE_KEEP_RETRY_MAX_MS,
41570
41781
  CACHE_KEEP_RETRY_JITTER_MAX_MS,
41571
41782
  CACHE_KEEP_RETRY_BASE_MS,