@cortexkit/anthropic-auth-core 2.5.3 → 2.5.5

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,19 +8503,26 @@ 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
  });
8491
8510
  if (next) {
8492
8511
  await lock.assertOwned();
8493
- await writeJsonAtomic(path, next, {
8494
- beforeRename: async () => {
8495
- await options.beforePublish?.();
8496
- options.signal?.throwIfAborted();
8497
- await lock.assertOwned();
8498
- }
8499
- });
8512
+ try {
8513
+ await writeJsonAtomic(path, next, {
8514
+ beforeRename: async () => {
8515
+ await options.beforePublish?.();
8516
+ options.signal?.throwIfAborted();
8517
+ await lock.assertOwned();
8518
+ }
8519
+ });
8520
+ } catch (error) {
8521
+ if (error && typeof error === "object" && "published" in error && error.published === true)
8522
+ options.onPublished?.();
8523
+ throw error;
8524
+ }
8525
+ options.onPublished?.();
8500
8526
  }
8501
8527
  return result;
8502
8528
  });
@@ -8646,7 +8672,7 @@ function isVaultRosterLockRefusal(path, error) {
8646
8672
  var UNLOCKED_READ_ATTEMPTS = 4;
8647
8673
  async function fileStamp(path) {
8648
8674
  try {
8649
- const { dev, ino, size, mtimeMs } = await stat6(path);
8675
+ const { dev, ino, size, mtimeMs } = await stat7(path);
8650
8676
  return { dev, ino, size, mtimeMs };
8651
8677
  } catch {
8652
8678
  return;
@@ -9647,7 +9673,7 @@ class ClaustrumConsumer {
9647
9673
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
9648
9674
  import { createHash as createHash4 } from "node:crypto";
9649
9675
  import { channel as channel2 } from "node:diagnostics_channel";
9650
- import { readdir, stat as stat7 } from "node:fs/promises";
9676
+ import { readdir, stat as stat8 } from "node:fs/promises";
9651
9677
  import { dirname as dirname8, join as join9, resolve as resolve9 } from "node:path";
9652
9678
  var sharedRosters = new Map;
9653
9679
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -10302,7 +10328,7 @@ class ClaustrumDiscoveryHub {
10302
10328
  let newest;
10303
10329
  for (const path of candidates) {
10304
10330
  try {
10305
- const modified = (await stat7(path)).mtimeMs;
10331
+ const modified = (await stat8(path)).mtimeMs;
10306
10332
  const roster = await readVaultRoster(path);
10307
10333
  if (roster && (!newest || modified > newest.modified))
10308
10334
  newest = { modified, roster };
@@ -10528,7 +10554,7 @@ import {
10528
10554
  open as open7,
10529
10555
  realpath as realpath2,
10530
10556
  rename as rename7,
10531
- stat as stat8,
10557
+ stat as stat9,
10532
10558
  unlink as unlink4
10533
10559
  } from "node:fs/promises";
10534
10560
  import { homedir as homedir4 } from "node:os";
@@ -11067,7 +11093,7 @@ async function readBoundedJson2(path, ownership = {}) {
11067
11093
  await descriptor.close();
11068
11094
  }
11069
11095
  }
11070
- async function refuseWritableAncestor2(parent, ownership = {}, metadataAt = (path) => stat8(path).catch(() => {
11096
+ async function refuseWritableAncestor2(parent, ownership = {}, metadataAt = (path) => stat9(path).catch(() => {
11071
11097
  return;
11072
11098
  })) {
11073
11099
  const safe = await isSafeWindowsParent(parent, ownership);
@@ -12446,8 +12472,8 @@ function rotateLogFile() {
12446
12472
  try {
12447
12473
  if (!fs2.existsSync(LOG_FILE))
12448
12474
  return;
12449
- const stat9 = fs2.statSync(LOG_FILE);
12450
- if (stat9.size < MAX_FILE_SIZE)
12475
+ const stat10 = fs2.statSync(LOG_FILE);
12476
+ if (stat10.size < MAX_FILE_SIZE)
12451
12477
  return;
12452
12478
  } catch {
12453
12479
  return;
@@ -15045,6 +15071,37 @@ async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
15045
15071
  const signedBodyText = await signRequestBody(JSON.stringify(orderClaudeCodeBody(warm)));
15046
15072
  return { ok: true, bodyText: signedBodyText };
15047
15073
  }
15074
+ function sessionMetadata(target) {
15075
+ return {
15076
+ id: target.id,
15077
+ cacheExpiresAt: target.cacheExpiresAt,
15078
+ nextPrewarmAt: target.nextPrewarmAt,
15079
+ ...target.ttlMs !== undefined && { ttlMs: target.ttlMs },
15080
+ ...target.lastTouchAt !== undefined && {
15081
+ lastTouchAt: target.lastTouchAt
15082
+ },
15083
+ ...target.lastTouchKind !== undefined && {
15084
+ lastTouchKind: target.lastTouchKind
15085
+ }
15086
+ };
15087
+ }
15088
+ function stopReason(reason) {
15089
+ switch (reason) {
15090
+ case "budget":
15091
+ case "count":
15092
+ return "evicted";
15093
+ case "schedule-period-ended":
15094
+ return "schedule";
15095
+ case "retry-window-ended":
15096
+ return "retries-exhausted";
15097
+ case "cachekeep-hybrid-inactive":
15098
+ return "disabled";
15099
+ case "source-warm-idle-cap":
15100
+ return "cost-cap";
15101
+ default:
15102
+ return "policy-refused";
15103
+ }
15104
+ }
15048
15105
  function isRecord9(value) {
15049
15106
  return typeof value === "object" && value !== null && !Array.isArray(value);
15050
15107
  }
@@ -15125,6 +15182,7 @@ function cacheKeepSentCredentials(headers) {
15125
15182
  class CacheKeepManager {
15126
15183
  options;
15127
15184
  targets = new Map;
15185
+ stoppedSessions = new Map;
15128
15186
  timer = null;
15129
15187
  tickPromise = null;
15130
15188
  nextPrewarmAttemptId = 0;
@@ -15164,6 +15222,16 @@ class CacheKeepManager {
15164
15222
  nextPrewarmAt: target.nextPrewarmAt
15165
15223
  })).sort((left, right) => left.id.localeCompare(right.id));
15166
15224
  }
15225
+ registrySessions() {
15226
+ const now = this.options.now?.() ?? Date.now();
15227
+ for (const [id, session] of this.stoppedSessions)
15228
+ if (session.cacheExpiresAt <= now)
15229
+ this.stoppedSessions.delete(id);
15230
+ return [
15231
+ ...this.stoppedSessions.values(),
15232
+ ...[...this.targets.values()].map(sessionMetadata)
15233
+ ].sort((left, right) => left.id.localeCompare(right.id));
15234
+ }
15167
15235
  trackedOAuthRoute(sessionId) {
15168
15236
  const target = this.targets.get(sessionId);
15169
15237
  return target ? { oauthAccountId: target.oauthAccountId } : undefined;
@@ -15186,9 +15254,11 @@ class CacheKeepManager {
15186
15254
  cacheExpiresAt: target.cacheExpiresAt
15187
15255
  };
15188
15256
  }
15189
- untrack(id) {
15190
- if (!this.targets.has(id))
15257
+ untrack(id, reason = "session-forgotten") {
15258
+ const target = this.targets.get(id);
15259
+ if (!target)
15191
15260
  return false;
15261
+ this.retainStopped(target, reason, this.options.now?.() ?? Date.now());
15192
15262
  this.targets.delete(id);
15193
15263
  this.options.onTargetRemoved?.(id);
15194
15264
  this.publishTrackedSessions();
@@ -15209,7 +15279,7 @@ class CacheKeepManager {
15209
15279
  if (!callback)
15210
15280
  return;
15211
15281
  try {
15212
- Promise.resolve(callback(this.trackedSessions())).catch(() => {
15282
+ Promise.resolve(callback(this.registrySessions())).catch(() => {
15213
15283
  logger2.warn("cachekeep", "failed to publish tracked sessions");
15214
15284
  });
15215
15285
  } catch {
@@ -15235,9 +15305,18 @@ class CacheKeepManager {
15235
15305
  nextPrewarmAt: target.nextPrewarmAt,
15236
15306
  ...details
15237
15307
  });
15308
+ this.retainStopped(target, stopReason(reason), now);
15238
15309
  this.targets.delete(target.id);
15239
15310
  this.options.onTargetRemoved?.(target.id);
15240
15311
  }
15312
+ retainStopped(target, reason, now) {
15313
+ if (now >= target.cacheExpiresAt)
15314
+ return;
15315
+ this.stoppedSessions.set(target.id, {
15316
+ ...sessionMetadata(target),
15317
+ warmStopped: { at: now, reason }
15318
+ });
15319
+ }
15241
15320
  evictOldestTarget(now, reason) {
15242
15321
  const oldest = this.targets.values().next().value;
15243
15322
  if (!oldest)
@@ -15320,6 +15399,7 @@ class CacheKeepManager {
15320
15399
  this.pruneTargets(now, today);
15321
15400
  if (this.targets.has(input.sessionId))
15322
15401
  this.targets.delete(input.sessionId);
15402
+ this.stoppedSessions.delete(input.sessionId);
15323
15403
  const headers = {};
15324
15404
  input.headers.forEach((value, key) => {
15325
15405
  headers[key] = value;
@@ -15330,8 +15410,17 @@ class CacheKeepManager {
15330
15410
  headers,
15331
15411
  bodyText: input.bodyText,
15332
15412
  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,
15413
+ ...input.retained ? {
15414
+ ttlMs: input.retained.ttlMs,
15415
+ lastTouchAt: input.retained.lastTouchAt,
15416
+ lastTouchKind: input.retained.lastTouchKind
15417
+ } : input.sourceWarm ? {} : {
15418
+ ttlMs: input.ttlMs ?? CACHE_KEEP_TTL_MS,
15419
+ lastTouchAt: now,
15420
+ lastTouchKind: "response"
15421
+ },
15422
+ cacheExpiresAt: input.retained?.cacheExpiresAt ?? now + (input.ttlMs ?? CACHE_KEEP_TTL_MS),
15423
+ nextPrewarmAt: input.retained?.nextPrewarmAt ?? now + (input.ttlMs ?? CACHE_KEEP_TTL_MS) - CACHE_KEEP_PREWARM_LEAD_MS,
15335
15424
  consecutiveFailures: 0,
15336
15425
  dayKey: today,
15337
15426
  oauthAccountId: input.oauthAccountId,
@@ -15394,18 +15483,19 @@ class CacheKeepManager {
15394
15483
  this.pruneTargets(now, today);
15395
15484
  if (!this.targets.size) {
15396
15485
  this.publishTrackedSessions();
15397
- this.stop();
15486
+ if (!this.stoppedSessions.size)
15487
+ this.stop();
15398
15488
  return;
15399
15489
  }
15400
15490
  if (!isCacheKeepHybridActive(storage)) {
15401
- for (const target of this.targets.values()) {
15402
- if (target.sourceWarm)
15403
- this.removeTarget(target, "cachekeep-hybrid-inactive", now);
15404
- }
15491
+ for (const target of this.targets.values())
15492
+ this.removeTarget(target, "cachekeep-hybrid-inactive", now);
15405
15493
  this.publishTrackedSessions();
15406
15494
  return;
15407
15495
  }
15408
15496
  if (!isCacheKeepActiveNow(storage, new Date(now))) {
15497
+ for (const target of this.targets.values())
15498
+ this.removeTarget(target, "schedule-period-ended", now);
15409
15499
  this.publishTrackedSessions();
15410
15500
  return;
15411
15501
  }
@@ -15450,7 +15540,7 @@ class CacheKeepManager {
15450
15540
  const delay3 = transient ? Math.min(backoff, CACHE_KEEP_TRANSIENT_RETRY_STEP_MS * target.consecutiveFailures, CACHE_KEEP_TRANSIENT_RETRY_MAX_MS) : backoff;
15451
15541
  target.nextPrewarmAt = Math.min(now + delay3, deadline);
15452
15542
  }
15453
- async sendPrewarm(target) {
15543
+ async sendPrewarm(target, onAccepted) {
15454
15544
  const attempt = {
15455
15545
  id: ++this.nextPrewarmAttemptId,
15456
15546
  signal: AbortSignal.timeout(this.options.prewarmTimeoutMs ?? CACHE_KEEP_PREWARM_TIMEOUT_MS)
@@ -15602,6 +15692,7 @@ class CacheKeepManager {
15602
15692
  }
15603
15693
  const objectData = data && typeof data === "object" && !Array.isArray(data) ? data : null;
15604
15694
  const usage = objectData?.usage;
15695
+ onAccepted?.(receivedAt);
15605
15696
  return { ok: true, ...usage && { usage } };
15606
15697
  } catch (error) {
15607
15698
  const failure = classifyCacheKeepFailure(error, stage, responseStatus);
@@ -15628,7 +15719,10 @@ class CacheKeepManager {
15628
15719
  }
15629
15720
  }
15630
15721
  async prewarm(target, now) {
15631
- const result = await this.sendPrewarm(target);
15722
+ let acceptedAt;
15723
+ const result = await this.sendPrewarm(target, (receivedAt) => {
15724
+ acceptedAt = receivedAt;
15725
+ });
15632
15726
  if (!result.ok) {
15633
15727
  if (result.refused === true) {
15634
15728
  this.removeTarget(target, result.reason, now, {
@@ -15658,7 +15752,13 @@ class CacheKeepManager {
15658
15752
  }
15659
15753
  return;
15660
15754
  }
15661
- target.cacheExpiresAt = now + CACHE_KEEP_TTL_MS;
15755
+ if (this.targets.get(target.id) !== target)
15756
+ return;
15757
+ acceptedAt ??= this.options.now?.() ?? Date.now();
15758
+ target.ttlMs = CACHE_KEEP_TTL_MS;
15759
+ target.lastTouchAt = acceptedAt;
15760
+ target.lastTouchKind = "warm";
15761
+ target.cacheExpiresAt = acceptedAt + CACHE_KEEP_TTL_MS;
15662
15762
  target.nextPrewarmAt = target.cacheExpiresAt - CACHE_KEEP_PREWARM_LEAD_MS;
15663
15763
  target.consecutiveFailures = 0;
15664
15764
  logger2.debug("cachekeep", "prewarm succeeded", {
@@ -15671,6 +15771,7 @@ class CacheKeepManager {
15671
15771
  import { randomUUID as randomUUID15 } from "node:crypto";
15672
15772
  import {
15673
15773
  link,
15774
+ lstat as lstat13,
15674
15775
  mkdir as mkdir11,
15675
15776
  readdir as readdir3,
15676
15777
  readFile as readFile12,
@@ -15679,7 +15780,8 @@ import {
15679
15780
  writeFile as writeFile4
15680
15781
  } from "node:fs/promises";
15681
15782
  import { tmpdir as tmpdir6 } from "node:os";
15682
- import { join as join21 } from "node:path";
15783
+ import * as nodePath3 from "node:path";
15784
+ import { dirname as dirname18, join as join21 } from "node:path";
15683
15785
 
15684
15786
  // src/holder-registry.ts
15685
15787
  import { execFile } from "node:child_process";
@@ -15739,7 +15841,7 @@ import { basename as basename7, dirname as dirname14, join as join16, resolve as
15739
15841
 
15740
15842
  // src/sticky-routing.ts
15741
15843
  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";
15844
+ import { mkdir as mkdir9, readFile as readFile8, rename as rename11, rm as rm6, stat as stat10, writeFile as writeFile3 } from "node:fs/promises";
15743
15845
  import { basename as basename6, dirname as dirname13, join as join15 } from "node:path";
15744
15846
 
15745
15847
  // src/native-vault-seed.ts
@@ -17148,7 +17250,7 @@ async function recordQuota(rt, id, attribution, observation) {
17148
17250
  }
17149
17251
 
17150
17252
  // ../../node_modules/@cortexkit/common-auth/dist/store/limits-namespace.js
17151
- async function updatePoolLimitsNamespace(rt, mutator) {
17253
+ async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
17152
17254
  assertLimitsWriteAllowed();
17153
17255
  const { ctx } = rt;
17154
17256
  await runOperation(ctx, "updateLimitsNamespace", undefined, undefined, async (locks, progress) => {
@@ -17168,13 +17270,21 @@ async function updatePoolLimitsNamespace(rt, mutator) {
17168
17270
  operation: "updateLimitsNamespace",
17169
17271
  rowId: undefined
17170
17272
  };
17171
- await writeJsonAtomic(ctx.configPath, config, {
17172
- beforeRename: async () => {
17173
- await ctx.onStep?.("before-config-write", info);
17174
- await locks.assertAll();
17175
- }
17176
- });
17273
+ try {
17274
+ await writeJsonAtomic(ctx.configPath, config, {
17275
+ beforeRename: async () => {
17276
+ await ctx.onStep?.("before-config-write", info);
17277
+ await locks.assertAll();
17278
+ options.beforePublish?.();
17279
+ }
17280
+ });
17281
+ } catch (error) {
17282
+ if (error && typeof error === "object" && "published" in error && error.published === true)
17283
+ options.onPublished?.();
17284
+ throw error;
17285
+ }
17177
17286
  progress.writes++;
17287
+ options.onPublished?.();
17178
17288
  await ctx.onStep?.("after-config-write", info);
17179
17289
  });
17180
17290
  }
@@ -19162,7 +19272,7 @@ function openPoolStore(options) {
19162
19272
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
19163
19273
  readSettings: () => readPoolSettings(rt),
19164
19274
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
19165
- updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
19275
+ updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
19166
19276
  recordIdentity: (id, identity2, attribution, callOptions) => recordRowIdentity(rt, id, identity2, attribution, callOptions),
19167
19277
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
19168
19278
  recordQuota: record2,
@@ -19571,6 +19681,9 @@ function toNativeQuotaMap(snapshot) {
19571
19681
  const json = JSON.parse(JSON.stringify(snapshot));
19572
19682
  if (!isNativeOAuthQuotaSnapshot(json))
19573
19683
  throw new NativeQuotaCodecError;
19684
+ return encodeNativeQuotaMap(json);
19685
+ }
19686
+ function encodeNativeQuotaMap(json) {
19574
19687
  const { five_hour, seven_day, scoped, ...metadata } = json;
19575
19688
  const limits = [];
19576
19689
  const remainingPercent = {};
@@ -19630,11 +19743,18 @@ function reading(value) {
19630
19743
  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
19744
  }
19632
19745
  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]));
19746
+ if (Array.isArray(a) && Array.isArray(b)) {
19747
+ if (a.length !== b.length)
19748
+ return false;
19749
+ for (let i = 0;i < a.length; i++) {
19750
+ if (!equalJson(a[i], b[i]))
19751
+ return false;
19752
+ }
19753
+ return true;
19754
+ }
19635
19755
  if (record3(a) && record3(b))
19636
19756
  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;
19757
+ return a !== undefined && a === b;
19638
19758
  }
19639
19759
  function fromNativeQuotaMap(value) {
19640
19760
  if (!record3(value) || !keys(value, ["limits", "anthropic"], ["budget"]) || !isQuotaMap(value) || !value.limits.every(reading) || !nativeMetadata(value.anthropic))
@@ -19676,7 +19796,7 @@ function fromNativeQuotaMap(value) {
19676
19796
  };
19677
19797
  });
19678
19798
  }
19679
- if (!equalJson(toNativeQuotaMap(snapshot), value))
19799
+ if (!isNativeOAuthQuotaSnapshot(snapshot) || !equalJson(encodeNativeQuotaMap(snapshot), value))
19680
19800
  throw new NativeQuotaCodecError;
19681
19801
  return snapshot;
19682
19802
  }
@@ -20143,20 +20263,36 @@ function checkPath(path2) {
20143
20263
  if (!isAbsolute4(path2))
20144
20264
  throw new NativeRuntimeError("unsafe-runtime");
20145
20265
  }
20266
+ var runtimeCacheLimit = 4;
20267
+ var runtimeCache = new Map;
20268
+ function runtimeFileIdentity(info) {
20269
+ return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
20270
+ }
20271
+ function freezeRuntime(value) {
20272
+ if (value === null || typeof value !== "object")
20273
+ return;
20274
+ for (const child of Object.values(value))
20275
+ freezeRuntime(child);
20276
+ Object.freeze(value);
20277
+ }
20146
20278
  async function readNativeRuntime(path2, storageId, ownership = {}) {
20147
- checkPath(path2);
20148
- if (!digest(storageId))
20149
- throw new NativeRuntimeError("invalid-runtime");
20150
20279
  const noFollow = constants2.O_NOFOLLOW ?? 0;
20151
20280
  try {
20281
+ checkPath(path2);
20282
+ if (!digest(storageId))
20283
+ throw new NativeRuntimeError("invalid-runtime");
20152
20284
  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))
20285
+ const info = await lstat6(path2, { bigint: true });
20286
+ if (!info.isFile() || !await isOwnerOnly(path2, () => (info.mode & 0o777n) === 0o600n && (typeof process.geteuid !== "function" || info.uid === BigInt(process.geteuid())), ownership))
20155
20287
  throw new NativeRuntimeError("unsafe-runtime");
20288
+ const identity2 = runtimeFileIdentity(info);
20289
+ const cached = runtimeCache.get(path2);
20290
+ if (cached?.storageId === storageId && cached.identity === identity2)
20291
+ return { status: "ready", state: cached.state };
20156
20292
  const file = await open8(path2, constants2.O_RDONLY | noFollow);
20157
20293
  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))
20294
+ const opened = await file.stat({ bigint: true });
20295
+ if (!opened.isFile() || !await isOwnerOnly(path2, () => (opened.mode & 0o777n) === 0o600n && (typeof process.geteuid !== "function" || opened.uid === BigInt(process.geteuid())), ownership))
20160
20296
  throw new NativeRuntimeError("unsafe-runtime");
20161
20297
  if (!noFollow && (opened.dev !== info.dev || opened.ino !== info.ino)) {
20162
20298
  if (attempt === 0)
@@ -20171,16 +20307,25 @@ async function readNativeRuntime(path2, storageId, ownership = {}) {
20171
20307
  throw new NativeRuntimeError("invalid-runtime");
20172
20308
  throw error;
20173
20309
  }
20174
- return {
20175
- status: "ready",
20176
- state: decodeNativeRuntime(parseJsonRedacted(contents), storageId)
20177
- };
20310
+ const state = decodeNativeRuntime(parseJsonRedacted(contents), storageId);
20311
+ freezeRuntime(state);
20312
+ if (runtimeFileIdentity(opened) === identity2) {
20313
+ runtimeCache.delete(path2);
20314
+ runtimeCache.set(path2, { storageId, identity: identity2, state });
20315
+ if (runtimeCache.size > runtimeCacheLimit) {
20316
+ const oldest = runtimeCache.keys().next().value;
20317
+ if (oldest !== undefined)
20318
+ runtimeCache.delete(oldest);
20319
+ }
20320
+ }
20321
+ return { status: "ready", state };
20178
20322
  } finally {
20179
20323
  await file.close();
20180
20324
  }
20181
20325
  }
20182
20326
  throw new NativeRuntimeError("unsafe-runtime");
20183
20327
  } catch (error) {
20328
+ runtimeCache.delete(path2);
20184
20329
  if (missing(error))
20185
20330
  return { status: "missing" };
20186
20331
  if (error instanceof NativeRuntimeError)
@@ -21915,7 +22060,7 @@ class StickySessionRouter {
21915
22060
  }
21916
22061
  async readStateMtimeNs() {
21917
22062
  try {
21918
- return (await stat9(this.options.path, { bigint: true })).mtimeNs;
22063
+ return (await stat10(this.options.path, { bigint: true })).mtimeNs;
21919
22064
  } catch (error) {
21920
22065
  if (error.code === "ENOENT")
21921
22066
  return 0n;
@@ -23307,8 +23452,8 @@ async function linuxIncarnation(pid) {
23307
23452
  if (!boot)
23308
23453
  return null;
23309
23454
  try {
23310
- const stat10 = await readFile11(`/proc/${pid}/stat`, "utf8");
23311
- const fields2 = stat10.slice(stat10.lastIndexOf(")") + 2).split(" ");
23455
+ const stat11 = await readFile11(`/proc/${pid}/stat`, "utf8");
23456
+ const fields2 = stat11.slice(stat11.lastIndexOf(")") + 2).split(" ");
23312
23457
  const start = fields2[19];
23313
23458
  return start && /^\d+$/.test(start) ? `${boot}:${start}` : null;
23314
23459
  } catch {
@@ -23637,8 +23782,28 @@ function resetNativeHolderRegistryForTests() {
23637
23782
  ownIncarnation = undefined;
23638
23783
  }
23639
23784
 
23785
+ // src/host-paths.ts
23786
+ import { homedir as homedir5 } from "node:os";
23787
+ import * as nodePath2 from "node:path";
23788
+ function getHostHome(env = process.env, platform = process.platform) {
23789
+ return (platform === "win32" ? env.USERPROFILE || env.HOME : env.HOME) || homedir5();
23790
+ }
23791
+ function getHostDataHome(env = process.env, platform = process.platform, pathApi = nodePath2) {
23792
+ const xdg = env.XDG_DATA_HOME?.trim();
23793
+ return xdg ? pathApi.resolve(xdg) : pathApi.join(getHostHome(env, platform), ".local", "share");
23794
+ }
23795
+
23640
23796
  // src/cachekeep-registry.ts
23641
23797
  var CACHE_KEEP_REGISTRY_LEASE_MS = 3 * 60000;
23798
+ var CACHE_KEEP_STOP_REASONS = [
23799
+ "cost-cap",
23800
+ "schedule",
23801
+ "evicted",
23802
+ "policy-refused",
23803
+ "retries-exhausted",
23804
+ "session-forgotten",
23805
+ "disabled"
23806
+ ];
23642
23807
  function normalizeSession(value) {
23643
23808
  if (!value || typeof value !== "object" || Array.isArray(value))
23644
23809
  return;
@@ -23649,7 +23814,28 @@ function normalizeSession(value) {
23649
23814
  return {
23650
23815
  id: record8.id,
23651
23816
  cacheExpiresAt: record8.cacheExpiresAt,
23652
- nextPrewarmAt: record8.nextPrewarmAt
23817
+ nextPrewarmAt: record8.nextPrewarmAt,
23818
+ ...typeof record8.ttlMs === "number" && Number.isFinite(record8.ttlMs) && record8.ttlMs > 0 && { ttlMs: record8.ttlMs },
23819
+ ...typeof record8.lastTouchAt === "number" && Number.isFinite(record8.lastTouchAt) && {
23820
+ lastTouchAt: record8.lastTouchAt
23821
+ },
23822
+ ...(record8.lastTouchKind === "response" || record8.lastTouchKind === "warm") && {
23823
+ lastTouchKind: record8.lastTouchKind
23824
+ },
23825
+ ...normalizeStopped(record8.warmStopped)
23826
+ };
23827
+ }
23828
+ function normalizeStopped(value) {
23829
+ if (!value || typeof value !== "object")
23830
+ return {};
23831
+ const stopped = value;
23832
+ if (typeof stopped.at !== "number" || !Number.isFinite(stopped.at) || !CACHE_KEEP_STOP_REASONS.includes(stopped.reason))
23833
+ return {};
23834
+ return {
23835
+ warmStopped: {
23836
+ at: stopped.at,
23837
+ reason: stopped.reason
23838
+ }
23653
23839
  };
23654
23840
  }
23655
23841
  function normalizeRecord(value) {
@@ -23671,41 +23857,69 @@ function normalizeRecord(value) {
23671
23857
  function isExpiredRecord(record8, now, leaseMs) {
23672
23858
  return record8.updatedAt <= now && now - record8.updatedAt > leaseMs;
23673
23859
  }
23674
- function getDefaultCacheKeepRegistryDirectory(scope) {
23860
+ function getLegacyCacheKeepRegistryDirectory(scope) {
23675
23861
  return join21(tmpdir6(), "opencode-anthropic-auth", "cachekeep-sessions", scope);
23676
23862
  }
23863
+ function getDefaultCacheKeepRegistryDirectory(scope, env = process.env, platform = process.platform, pathApi = nodePath3) {
23864
+ return pathApi.join(getHostDataHome(env, platform, pathApi), "cortexkit", "anthropic-auth", "cachekeep-sessions", scope);
23865
+ }
23866
+ function getCacheKeepRegistryDirectories(scope, override, env = process.env) {
23867
+ const directory = override || env[scope === "pi" ? "PI_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR" : "OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR"];
23868
+ return {
23869
+ directory: directory || getDefaultCacheKeepRegistryDirectory(scope, env),
23870
+ legacyDirectory: directory ? undefined : getLegacyCacheKeepRegistryDirectory(scope)
23871
+ };
23872
+ }
23677
23873
 
23678
23874
  class CacheKeepSessionRegistry {
23679
23875
  options;
23680
- filePath;
23876
+ directories;
23877
+ filePaths;
23681
23878
  writeChain = Promise.resolve();
23682
23879
  lastSweepAt;
23683
23880
  constructor(options) {
23684
23881
  this.options = options;
23685
23882
  const instanceId = options.instanceId ?? `${process.pid}-${randomUUID15()}`;
23686
- this.filePath = join21(options.directory, `${instanceId}.json`);
23883
+ this.directories = [
23884
+ ...new Set([options.directory, options.legacyDirectory].filter((dir) => !!dir))
23885
+ ];
23886
+ this.filePaths = this.directories.map((dir) => join21(dir, `${instanceId}.json`));
23687
23887
  }
23688
23888
  publish(sessions) {
23689
23889
  const snapshot = sessions.map((session) => ({ ...session }));
23690
23890
  this.writeChain = this.writeChain.catch(() => {}).then(async () => {
23691
23891
  const now = this.options.now?.() ?? Date.now();
23692
23892
  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);
23893
+ const record8 = {
23894
+ version: 1,
23895
+ updatedAt: now,
23896
+ sessions: snapshot,
23897
+ writer: writerStamp()
23898
+ };
23899
+ for (const filePath of this.filePaths) {
23900
+ if (snapshot.length === 0) {
23901
+ await rm7(filePath, { force: true });
23902
+ continue;
23903
+ }
23904
+ const directory = dirname18(filePath);
23905
+ if (!await ensureWindowsOwnerOnlyDirectory(directory, this.options.ownerOnly)) {
23906
+ await mkdir11(directory, { recursive: true, mode: 448 });
23907
+ }
23908
+ const stat11 = await lstat13(directory);
23909
+ if (!stat11.isDirectory() || stat11.isSymbolicLink() || !await isOwnerOnly(directory, () => stat11.uid === process.getuid?.() && (stat11.mode & 511) === 448, this.options.ownerOnly))
23910
+ throw new Error("Unsafe CacheKeep registry directory");
23911
+ const tempPath = `${filePath}.${randomUUID15()}.tmp`;
23912
+ try {
23913
+ const bytes = `${JSON.stringify(record8)}
23914
+ `;
23915
+ if (!await createWindowsOwnerOnly(tempPath, bytes, this.options.ownerOnly))
23916
+ await writeFile4(tempPath, bytes, { flag: "wx", mode: 384 });
23917
+ await renameWithWindowsSharingRetry(tempPath, filePath, {
23918
+ platform: this.options.ownerOnly?.platform
23919
+ });
23920
+ } finally {
23921
+ await rm7(tempPath, { force: true });
23922
+ }
23709
23923
  }
23710
23924
  await this.sweepExpiredRecords(now, leaseMs);
23711
23925
  });
@@ -23716,15 +23930,9 @@ class CacheKeepSessionRegistry {
23716
23930
  const now = this.options.now?.() ?? Date.now();
23717
23931
  const leaseMs = this.options.leaseMs ?? CACHE_KEEP_REGISTRY_LEASE_MS;
23718
23932
  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) => {
23933
+ const records = await Promise.all((await this.recordPaths()).map(async (path2) => {
23726
23934
  try {
23727
- const raw = await readFile12(join21(this.options.directory, name), "utf8");
23935
+ const raw = await readFile12(path2, "utf8");
23728
23936
  return normalizeRecord(JSON.parse(raw));
23729
23937
  } catch {
23730
23938
  return;
@@ -23752,22 +23960,32 @@ class CacheKeepSessionRegistry {
23752
23960
  }
23753
23961
  async dispose() {
23754
23962
  await this.writeChain.catch(() => {});
23755
- await rm7(this.filePath, { force: true });
23963
+ await Promise.all(this.filePaths.map((path2) => rm7(path2, { force: true })));
23964
+ }
23965
+ async recordPaths() {
23966
+ return (await Promise.all(this.directories.map(async (directory) => {
23967
+ try {
23968
+ return (await readdir3(directory)).filter((name) => name.endsWith(".json")).map((name) => join21(directory, name));
23969
+ } catch {
23970
+ return [];
23971
+ }
23972
+ }))).flat();
23973
+ }
23974
+ async mayRemove(recordPath, record8, now, leaseMs) {
23975
+ if (!isExpiredRecord(record8, now, leaseMs))
23976
+ return false;
23977
+ const pid = Number(/(?:^|[/\\])(\d+)-[^/\\]+\.json(?:\..+\.sweep)?$/.exec(recordPath)?.[1]);
23978
+ if (!Number.isSafeInteger(pid) || pid <= 0)
23979
+ return false;
23980
+ return !await holderEntryIsLive({ pid, incarnation: null, registeredAt: record8.updatedAt }, this.options.liveness);
23756
23981
  }
23757
23982
  async sweepExpiredRecords(now, leaseMs) {
23758
23983
  if (this.lastSweepAt !== undefined && now - this.lastSweepAt < leaseMs) {
23759
23984
  return;
23760
23985
  }
23761
23986
  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)
23987
+ await Promise.all((await this.recordPaths()).map(async (recordPath) => {
23988
+ if (this.filePaths.includes(recordPath))
23771
23989
  return;
23772
23990
  let initialRecord;
23773
23991
  try {
@@ -23775,7 +23993,7 @@ class CacheKeepSessionRegistry {
23775
23993
  } catch {
23776
23994
  return;
23777
23995
  }
23778
- if (!initialRecord || !isExpiredRecord(initialRecord, now, leaseMs)) {
23996
+ if (!initialRecord || !await this.mayRemove(recordPath, initialRecord, now, leaseMs)) {
23779
23997
  return;
23780
23998
  }
23781
23999
  const sweptPath = `${recordPath}.${randomUUID15()}.sweep`;
@@ -23790,7 +24008,7 @@ class CacheKeepSessionRegistry {
23790
24008
  raw = await readFile12(sweptPath, "utf8");
23791
24009
  record8 = normalizeRecord(JSON.parse(raw));
23792
24010
  } catch {}
23793
- if (record8 && isExpiredRecord(record8, now, leaseMs)) {
24011
+ if (record8 && await this.mayRemove(recordPath, record8, now, leaseMs)) {
23794
24012
  try {
23795
24013
  await rm7(sweptPath, { force: true });
23796
24014
  } catch {}
@@ -23813,11 +24031,12 @@ class CacheKeepSessionRegistry {
23813
24031
  if (raw === undefined)
23814
24032
  return;
23815
24033
  try {
23816
- await writeFile4(recordPath, raw, {
23817
- encoding: "utf8",
23818
- flag: "wx",
23819
- mode: 384
23820
- });
24034
+ if (!await createWindowsOwnerOnly(recordPath, raw, this.options.ownerOnly))
24035
+ await writeFile4(recordPath, raw, {
24036
+ encoding: "utf8",
24037
+ flag: "wx",
24038
+ mode: 384
24039
+ });
23821
24040
  } catch (writeError) {
23822
24041
  const writeCode = writeError && typeof writeError === "object" && "code" in writeError ? writeError.code : undefined;
23823
24042
  if (writeCode !== "EEXIST")
@@ -27183,7 +27402,7 @@ import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node
27183
27402
  // src/migration-source.ts
27184
27403
  import { createHash as createHash22 } from "node:crypto";
27185
27404
  import { constants as constants3 } from "node:fs";
27186
- import { lstat as lstat13, open as open10 } from "node:fs/promises";
27405
+ import { lstat as lstat14, open as open10 } from "node:fs/promises";
27187
27406
  class NativeMigrationSourceError extends Error {
27188
27407
  role;
27189
27408
  code;
@@ -27226,7 +27445,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27226
27445
  });
27227
27446
  let initial;
27228
27447
  try {
27229
- initial = await lstat13(path2, { bigint: true });
27448
+ initial = await lstat14(path2, { bigint: true });
27230
27449
  } catch (error) {
27231
27450
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
27232
27451
  return missing2;
@@ -27264,7 +27483,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
27264
27483
  chunks.push(chunk.subarray(0, read.bytesRead));
27265
27484
  }
27266
27485
  const after = await handle.stat({ bigint: true });
27267
- const current = await lstat13(path2, { bigint: true });
27486
+ const current = await lstat14(path2, { bigint: true });
27268
27487
  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
27488
  throw new NativeMigrationSourceError(role, "source-changed");
27270
27489
  }
@@ -33234,8 +33453,8 @@ function relayGeneration(input) {
33234
33453
  }
33235
33454
  // src/native-host-auth-write.ts
33236
33455
  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";
33456
+ import { lstat as lstat15, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
33457
+ import { dirname as dirname19, isAbsolute as isAbsolute6, join as join22 } from "node:path";
33239
33458
  class NativeHostAuthWriteError extends Error {
33240
33459
  code;
33241
33460
  effect;
@@ -33296,7 +33515,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33296
33515
  const removingFile = host === "pi" && Object.keys(next).length === 0;
33297
33516
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
33298
33517
  if (!removingFile) {
33299
- stage = join22(dirname18(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33518
+ stage = join22(dirname19(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
33300
33519
  const bytes = `${JSON.stringify(next, null, 2)}
33301
33520
  `;
33302
33521
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
@@ -33346,7 +33565,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
33346
33565
  } finally {
33347
33566
  if (stage && ownedStage) {
33348
33567
  try {
33349
- const current = await lstat14(stage);
33568
+ const current = await lstat15(stage);
33350
33569
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
33351
33570
  await unlink7(stage);
33352
33571
  } catch {}
@@ -33356,8 +33575,8 @@ async function writeNativeHostAuth(input, hooks = {}) {
33356
33575
 
33357
33576
  // src/native-migration.ts
33358
33577
  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";
33578
+ import { lstat as lstat16, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
33579
+ import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
33361
33580
  class NativeMigrationError extends Error {
33362
33581
  code;
33363
33582
  constructor(code) {
@@ -33406,7 +33625,7 @@ function owned(snapshot) {
33406
33625
  }
33407
33626
  async function absent(path2) {
33408
33627
  try {
33409
- await lstat15(path2);
33628
+ await lstat16(path2);
33410
33629
  return false;
33411
33630
  } catch (error) {
33412
33631
  if (error instanceof Error && "code" in error && error.code === "ENOENT")
@@ -34110,7 +34329,7 @@ async function runNativeMigration(input, hooks = {}) {
34110
34329
  refuse3();
34111
34330
  await step("before:host");
34112
34331
  await recheck();
34113
- await mkdir12(dirname19(operation.hostAuthPath), {
34332
+ await mkdir12(dirname20(operation.hostAuthPath), {
34114
34333
  recursive: true,
34115
34334
  mode: 448
34116
34335
  });
@@ -36590,7 +36809,7 @@ function waitForRequest(pending, signal) {
36590
36809
  });
36591
36810
  }
36592
36811
  // src/native-vault-connection.ts
36593
- import { dirname as dirname21, join as join23, resolve as resolve16 } from "node:path";
36812
+ import { dirname as dirname22, join as join23, resolve as resolve16 } from "node:path";
36594
36813
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
36595
36814
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
36596
36815
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -36600,13 +36819,13 @@ function placeholderSecret(integrationID) {
36600
36819
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
36601
36820
  import { createHash as createHash25 } from "node:crypto";
36602
36821
  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";
36822
+ import { lstat as lstat17, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
36823
+ import { dirname as dirname21, resolve as resolve15 } from "node:path";
36605
36824
  import { setTimeout as sleep } from "node:timers/promises";
36606
36825
 
36607
36826
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
36608
36827
  import { rmdirSync, statSync as statSync5, utimesSync } from "node:fs";
36609
- import { mkdir as mkdir13, rmdir, stat as stat10, utimes } from "node:fs/promises";
36828
+ import { mkdir as mkdir13, rmdir, stat as stat11, utimes } from "node:fs/promises";
36610
36829
  var STALE = 30000;
36611
36830
  var RENEWAL_STALE = 1e4;
36612
36831
  var UPDATE = 3000;
@@ -36650,7 +36869,7 @@ async function acquire(path2, stale) {
36650
36869
  throw held();
36651
36870
  let mtime;
36652
36871
  try {
36653
- mtime = (await stat10(path2)).mtime.getTime();
36872
+ mtime = (await stat11(path2)).mtime.getTime();
36654
36873
  } catch (error2) {
36655
36874
  if (errorCode4(error2) === "ENOENT")
36656
36875
  return acquire(path2, 0);
@@ -36663,7 +36882,7 @@ async function acquire(path2, stale) {
36663
36882
  }
36664
36883
  let created;
36665
36884
  try {
36666
- const st = await stat10(path2);
36885
+ const st = await stat11(path2);
36667
36886
  created = { dev: st.dev, ino: st.ino };
36668
36887
  } catch {
36669
36888
  created = undefined;
@@ -36673,14 +36892,14 @@ async function acquire(path2, stale) {
36673
36892
  const probe2 = new Date(Math.ceil(Date.now() / 1000) * 1000 + 5);
36674
36893
  await utimes(path2, probe2, probe2);
36675
36894
  }
36676
- const observed = await stat10(path2);
36895
+ const observed = await stat11(path2);
36677
36896
  const mtime = observed.mtime.getTime();
36678
36897
  precision ??= mtime % 1000 === 0 ? "s" : "ms";
36679
36898
  return { dev: observed.dev, ino: observed.ino, mtime };
36680
36899
  } catch (error) {
36681
36900
  try {
36682
36901
  if (created) {
36683
- const current = await stat10(path2).catch(() => {
36902
+ const current = await stat11(path2).catch(() => {
36684
36903
  return;
36685
36904
  });
36686
36905
  if (current && current.dev === created.dev && current.ino === created.ino)
@@ -36780,7 +36999,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
36780
36999
  }
36781
37000
  let observed;
36782
37001
  try {
36783
- observed = await stat10(path2);
37002
+ observed = await stat11(path2);
36784
37003
  } catch (error) {
36785
37004
  if (errorCode4(error) !== "ENOENT")
36786
37005
  throw error;
@@ -36900,13 +37119,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
36900
37119
  let file;
36901
37120
  try {
36902
37121
  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) {
37122
+ const stat12 = await file.stat();
37123
+ if (!stat12.isFile() || privateFile && (stat12.mode & 511) !== 384) {
36905
37124
  throw new PiSlotError("unsafe-path");
36906
37125
  }
36907
37126
  await afterReadCheck?.(path2);
36908
- const current = await lstat16(path2);
36909
- if (!current.isFile() || current.dev !== stat11.dev || current.ino !== stat11.ino) {
37127
+ const current = await lstat17(path2);
37128
+ if (!current.isFile() || current.dev !== stat12.dev || current.ino !== stat12.ino) {
36910
37129
  throw new PiSlotError("unsafe-path");
36911
37130
  }
36912
37131
  const bytes = await file.readFile();
@@ -37038,9 +37257,9 @@ function createPiSlot(options, onStep, hooks) {
37038
37257
  };
37039
37258
  try {
37040
37259
  if (windowsPrivateFiles)
37041
- await ensurePrivateDirectory(dirname20(authPath));
37260
+ await ensurePrivateDirectory(dirname21(authPath));
37042
37261
  else
37043
- await mkdir14(dirname20(authPath), { recursive: true, mode: 448 });
37262
+ await mkdir14(dirname21(authPath), { recursive: true, mode: 448 });
37044
37263
  const deadline = Date.now() + timeout;
37045
37264
  let retry = 0;
37046
37265
  while (!release2) {
@@ -37080,7 +37299,7 @@ function createPiSlot(options, onStep, hooks) {
37080
37299
  async function deleteStash(assertLock) {
37081
37300
  assertLock();
37082
37301
  await unlink9(stashPath);
37083
- await syncDir(dirname20(stashPath));
37302
+ await syncDir(dirname21(stashPath));
37084
37303
  onStep?.("stash-deleted");
37085
37304
  }
37086
37305
  return {
@@ -37100,10 +37319,10 @@ function createPiSlot(options, onStep, hooks) {
37100
37319
  throw new PiSlotError("conflict");
37101
37320
  if (!stash) {
37102
37321
  if (windowsPrivateFiles)
37103
- await ensurePrivateDirectory(dirname20(stashPath));
37322
+ await ensurePrivateDirectory(dirname21(stashPath));
37104
37323
  else {
37105
- await mkdir14(dirname20(stashPath), { recursive: true, mode: 448 });
37106
- const dir = await lstat16(dirname20(stashPath));
37324
+ await mkdir14(dirname21(stashPath), { recursive: true, mode: 448 });
37325
+ const dir = await lstat17(dirname21(stashPath));
37107
37326
  if (!dir.isDirectory() || (dir.mode & 511) !== 448)
37108
37327
  throw new PiSlotError("unsafe-path");
37109
37328
  }
@@ -37144,7 +37363,7 @@ function createPiSlot(options, onStep, hooks) {
37144
37363
  function nativePiAuthSlotPaths(options) {
37145
37364
  return {
37146
37365
  authPath: resolve16(options.authPath),
37147
- stashPath: join23(dirname21(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37366
+ stashPath: join23(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
37148
37367
  provider: "anthropic",
37149
37368
  placeholderKey: placeholderSecret("anthropic")
37150
37369
  };
@@ -37276,7 +37495,7 @@ function createAnthropicOAuthFetch(options = {}) {
37276
37495
  // src/prime.ts
37277
37496
  import { createHash as createHash26 } from "node:crypto";
37278
37497
  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";
37498
+ import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat12, writeFile as writeFile5 } from "node:fs/promises";
37280
37499
  import { tmpdir as tmpdir7 } from "node:os";
37281
37500
  import { join as join24, resolve as resolve17 } from "node:path";
37282
37501
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
@@ -37695,7 +37914,7 @@ class PrimeManager {
37695
37914
  const bootstrapMarkerPath = primeBootstrapMarkerPath(markerDir, evaluation.id);
37696
37915
  const expectedMarkerPath = storedResetEpoch === undefined ? bootstrapMarkerPath : primeMarkerPath(markerDir, evaluation.id, storedResetEpoch);
37697
37916
  try {
37698
- await stat11(expectedMarkerPath);
37917
+ await stat12(expectedMarkerPath);
37699
37918
  return;
37700
37919
  } catch (error) {
37701
37920
  if (error.code !== "ENOENT")
@@ -37936,7 +38155,7 @@ class PrimeManager {
37936
38155
  for (const entry2 of entries) {
37937
38156
  try {
37938
38157
  const path2 = join24(dir, entry2);
37939
- const s = await stat11(path2);
38158
+ const s = await stat12(path2);
37940
38159
  if (s.isDirectory()) {
37941
38160
  swept += await this.sweepMarkerDirectory(path2, now);
37942
38161
  continue;
@@ -37960,13 +38179,13 @@ class PrimeManager {
37960
38179
  import { randomUUID as randomUUID19 } from "node:crypto";
37961
38180
  import {
37962
38181
  chmod as chmod3,
37963
- lstat as lstat17,
38182
+ lstat as lstat18,
37964
38183
  mkdir as mkdir16,
37965
38184
  readdir as readdir5,
37966
38185
  readFile as readFile13,
37967
38186
  rename as rename14,
37968
38187
  rm as rm9,
37969
- stat as stat12,
38188
+ stat as stat13,
37970
38189
  writeFile as writeFile6
37971
38190
  } from "node:fs/promises";
37972
38191
  import { tmpdir as tmpdir8 } from "node:os";
@@ -38198,11 +38417,11 @@ class QuotaHeaderFeedRegistry {
38198
38417
  if (path2 === this.filePath)
38199
38418
  return;
38200
38419
  try {
38201
- const file = await stat12(path2);
38420
+ const file = await stat13(path2);
38202
38421
  if (file.mtimeMs > now || now - file.mtimeMs < leaseMs)
38203
38422
  return;
38204
38423
  await this.options.beforeRemoveFile?.(path2);
38205
- const current = await lstat17(path2);
38424
+ const current = await lstat18(path2);
38206
38425
  if (current.ino !== file.ino || current.mtimeMs !== file.mtimeMs)
38207
38426
  return;
38208
38427
  await (this.options.removeFile ?? ((target2) => rm9(target2)))(path2);
@@ -38404,7 +38623,7 @@ function buildClaudeQuotaSummary(input) {
38404
38623
  }
38405
38624
  // src/request-gzip.ts
38406
38625
  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";
38626
+ import { basename as basename10, dirname as dirname23, join as join26 } from "node:path";
38408
38627
  import { promisify } from "node:util";
38409
38628
  import { gzip } from "node:zlib";
38410
38629
  var gzipAsync = promisify(gzip);
@@ -38528,7 +38747,7 @@ class RequestGzipLatch {
38528
38747
  return;
38529
38748
  const temporary = `${this.path}.${process.pid}.tmp`;
38530
38749
  try {
38531
- await mkdir17(dirname22(this.path), { recursive: true });
38750
+ await mkdir17(dirname23(this.path), { recursive: true });
38532
38751
  await writeFile7(temporary, `${JSON.stringify({ latchedAt: this.now(), status })}
38533
38752
  `, { mode: 384 });
38534
38753
  await rename15(temporary, this.path);
@@ -38550,7 +38769,7 @@ function getRequestGzipLatch(path2) {
38550
38769
  function getRequestGzipLatchPath(accountStoragePath) {
38551
38770
  const name = basename10(accountStoragePath);
38552
38771
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
38553
- return join26(dirname22(accountStoragePath), `${stem}-request-gzip.json`);
38772
+ return join26(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
38554
38773
  }
38555
38774
  async function decideRequestGzip(options) {
38556
38775
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -38779,12 +38998,12 @@ function executeLaneStartCommand(input) {
38779
38998
  }
38780
38999
  // src/state-layout-decision.ts
38781
39000
  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";
39001
+ import { homedir as homedir8 } from "node:os";
39002
+ import { basename as basename13, dirname as dirname25, join as join30 } from "node:path";
38784
39003
 
38785
39004
  // src/layout-fence.ts
38786
39005
  import { open as open13, readdir as readdir6 } from "node:fs/promises";
38787
- import { homedir as homedir5 } from "node:os";
39006
+ import { homedir as homedir6 } from "node:os";
38788
39007
  import { basename as basename11, join as join27, resolve as resolve18 } from "node:path";
38789
39008
  var STATE_PATH_OVERRIDE_VARIABLES = [
38790
39009
  "OPENCODE_ANTHROPIC_AUTH_FILE",
@@ -38863,7 +39082,7 @@ async function holderFenceBlockers(input) {
38863
39082
  }
38864
39083
  return blockers;
38865
39084
  }
38866
- function defaultPreNArtifactLocations(env = process.env, home = homedir5()) {
39085
+ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
38867
39086
  const root = anthropicAuthStateRoot({
38868
39087
  xdgStateHome: env.XDG_STATE_HOME,
38869
39088
  home,
@@ -38875,8 +39094,10 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir5()) {
38875
39094
  rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
38876
39095
  cacheKeepDirs: [
38877
39096
  ...new Set([
38878
- getDefaultCacheKeepRegistryDirectory("opencode"),
38879
- getDefaultCacheKeepRegistryDirectory("pi"),
39097
+ getDefaultCacheKeepRegistryDirectory("opencode", env),
39098
+ getDefaultCacheKeepRegistryDirectory("pi", env),
39099
+ getLegacyCacheKeepRegistryDirectory("opencode"),
39100
+ getLegacyCacheKeepRegistryDirectory("pi"),
38880
39101
  env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR?.trim(),
38881
39102
  env.PI_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR?.trim()
38882
39103
  ].filter((dir) => Boolean(dir)))
@@ -38982,8 +39203,8 @@ function describeFenceBlocker(blocker) {
38982
39203
 
38983
39204
  // src/state-layout-move.ts
38984
39205
  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";
39206
+ import { lstat as lstat19, readdir as readdir7, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
39207
+ import { basename as basename12, dirname as dirname24, join as join28, sep as sep2 } from "node:path";
38987
39208
  var ACCOUNT_FILE = "anthropic-auth.json";
38988
39209
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
38989
39210
  var LAYOUT_LOCK_NAME = "runtime-layout";
@@ -39063,7 +39284,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
39063
39284
  } catch (error) {
39064
39285
  if (error instanceof LockContentionError)
39065
39286
  throw error;
39066
- throw new HolderRegistrationError("unavailable", dirname23(holderFile), error);
39287
+ throw new HolderRegistrationError("unavailable", dirname24(holderFile), error);
39067
39288
  }
39068
39289
  }
39069
39290
  async function acquireHolderLocks(dataset, ctx) {
@@ -39273,7 +39494,7 @@ function restoringPath(path2, attempt) {
39273
39494
  }
39274
39495
  async function exists3(path2) {
39275
39496
  try {
39276
- await lstat18(path2);
39497
+ await lstat19(path2);
39277
39498
  return true;
39278
39499
  } catch (error) {
39279
39500
  if (errorCode6(error) === "ENOENT")
@@ -39283,7 +39504,7 @@ async function exists3(path2) {
39283
39504
  }
39284
39505
  async function removeOwnStaging(path2) {
39285
39506
  try {
39286
- const info = await lstat18(path2);
39507
+ const info = await lstat19(path2);
39287
39508
  if (info.isFile())
39288
39509
  await unlink10(path2);
39289
39510
  } catch (error) {
@@ -39309,10 +39530,10 @@ function recordFilesProblem(record9, dataset) {
39309
39530
  return;
39310
39531
  }
39311
39532
  async function movePreconditionFailure(dataset, platform) {
39312
- const oldInfo = await stat13(dataset.oldDir);
39533
+ const oldInfo = await stat14(dataset.oldDir);
39313
39534
  let subInfo;
39314
39535
  try {
39315
- subInfo = await stat13(dataset.sub);
39536
+ subInfo = await stat14(dataset.sub);
39316
39537
  } catch (error) {
39317
39538
  if (errorCode6(error) !== "ENOENT")
39318
39539
  throw error;
@@ -39326,7 +39547,7 @@ async function movePreconditionFailure(dataset, platform) {
39326
39547
  for (const path2 of new Set([slot.configured, slot.from])) {
39327
39548
  let info;
39328
39549
  try {
39329
- info = await lstat18(path2);
39550
+ info = await lstat19(path2);
39330
39551
  } catch (error) {
39331
39552
  if (errorCode6(error) === "ENOENT")
39332
39553
  continue;
@@ -39337,13 +39558,13 @@ async function movePreconditionFailure(dataset, platform) {
39337
39558
  if (platform !== "win32" && typeof process.getuid === "function" && info.uid !== process.getuid())
39338
39559
  return `${path2} belongs to another user`;
39339
39560
  }
39340
- if (dirname23(slot.from) !== dataset.oldDir || basename12(slot.from) !== basename12(slot.configured))
39561
+ if (dirname24(slot.from) !== dataset.oldDir || basename12(slot.from) !== basename12(slot.configured))
39341
39562
  return `${slot.configured} resolves to ${slot.from}, not to a file of its own in the config folder`;
39342
39563
  const fromExists = await exists3(slot.from);
39343
39564
  anyOld ||= fromExists;
39344
39565
  if (await exists3(slot.to)) {
39345
39566
  if (fromExists) {
39346
- const [a, b] = await Promise.all([lstat18(slot.from), lstat18(slot.to)]);
39567
+ const [a, b] = await Promise.all([lstat19(slot.from), lstat19(slot.to)]);
39347
39568
  if (a.dev === b.dev && a.ino === b.ino)
39348
39569
  return `${slot.from} and ${slot.to} are the same file`;
39349
39570
  }
@@ -39761,7 +39982,7 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
39761
39982
  // src/state-layout-restore.ts
39762
39983
  import { randomUUID as randomUUID21 } from "node:crypto";
39763
39984
  import { readFile as readFile16 } from "node:fs/promises";
39764
- import { homedir as homedir6 } from "node:os";
39985
+ import { homedir as homedir7 } from "node:os";
39765
39986
  import { join as join29 } from "node:path";
39766
39987
  var DATA_ROLES = [
39767
39988
  "localPoolState",
@@ -40039,7 +40260,7 @@ async function newRestoreProblems(record9, dataset, options) {
40039
40260
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
40040
40261
  }
40041
40262
  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());
40263
+ const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40043
40264
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness))
40044
40265
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
40045
40266
  for (const slot of dataset.slots) {
@@ -40151,7 +40372,7 @@ function finished(record9) {
40151
40372
  }
40152
40373
  async function restoreLegacyLayout(options = {}) {
40153
40374
  const env = options.env ?? process.env;
40154
- const home = options.home ?? homedir6();
40375
+ const home = options.home ?? homedir7();
40155
40376
  const overrides = statePathOverrides(env);
40156
40377
  if (overrides.length)
40157
40378
  throw refused2(`${RESTORE_LEGACY_COMMAND} works only on OpenCode's own config folder. Unset ${overrides.join(", ")} and run it again.`);
@@ -40325,7 +40546,7 @@ async function registerHeld(holderFile, paths, kind, identity3, options, ctx) {
40325
40546
  assertOwned: () => ctx.stack.assertAll()
40326
40547
  });
40327
40548
  } catch (error) {
40328
- throw error instanceof HolderRegistrationError ? error : new HolderRegistrationError("unavailable", dirname24(holderFile), error);
40549
+ throw error instanceof HolderRegistrationError ? error : new HolderRegistrationError("unavailable", dirname25(holderFile), error);
40329
40550
  }
40330
40551
  }
40331
40552
  function deferLegacyRegistration(paths, dir, options, error) {
@@ -40447,7 +40668,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
40447
40668
  }
40448
40669
  let names2;
40449
40670
  try {
40450
- names2 = await readdir8(dirname24(journal));
40671
+ names2 = await readdir8(dirname25(journal));
40451
40672
  } catch (error) {
40452
40673
  if (error?.code === "ENOENT")
40453
40674
  return false;
@@ -40466,7 +40687,7 @@ async function recordedMovingJournal(journal, identity3, options) {
40466
40687
  try {
40467
40688
  const target2 = stateHomeTargetFor(identity3, {
40468
40689
  env: options.env ?? process.env,
40469
- home: options.home ?? homedir7()
40690
+ home: options.home ?? homedir8()
40470
40691
  });
40471
40692
  const record9 = await readStateLayoutRecord(await canonicalPath(target2.dir));
40472
40693
  if (record9?.barriers.journal !== "present")
@@ -40507,7 +40728,7 @@ function stateFolderUnreadable(dir, cause) {
40507
40728
  }
40508
40729
  async function decideOpenCodeStateLayout(options) {
40509
40730
  const env = options.env ?? process.env;
40510
- const home = options.home ?? homedir7();
40731
+ const home = options.home ?? homedir8();
40511
40732
  const fs3 = options.fs ?? defaultStateLayoutFs();
40512
40733
  const configDir = getOpenCodeConfigDir(env, home);
40513
40734
  const newContext = () => ({
@@ -40521,7 +40742,7 @@ async function decideOpenCodeStateLayout(options) {
40521
40742
  });
40522
40743
  if (isExplicit(env)) {
40523
40744
  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`);
40745
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname25(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
40525
40746
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
40526
40747
  const registration = await registerNativePoolHolder({
40527
40748
  paths,
@@ -40681,9 +40902,9 @@ async function ensureSubfolder(sub, fs3) {
40681
40902
  const created = await mkdir18(sub, { recursive: true, mode: 448 });
40682
40903
  if (created === undefined)
40683
40904
  return;
40684
- for (let dir = dirname24(sub);; dir = dirname24(dir)) {
40905
+ for (let dir = dirname25(sub);; dir = dirname25(dir)) {
40685
40906
  await fs3.syncDirectory(dir);
40686
- if (dir === dirname24(created) || dir === dirname24(dir))
40907
+ if (dir === dirname25(created) || dir === dirname25(dir))
40687
40908
  break;
40688
40909
  }
40689
40910
  } catch (error) {
@@ -40761,7 +40982,7 @@ async function underLayoutLock(dataset, options, ctx, overrides, neverMove) {
40761
40982
  return stay([RELOCATION_MOVE_DISABLED_REASON], false);
40762
40983
  const holdersMark = ctx.stack.size;
40763
40984
  const files = [...dataset.slots.flatMap((slot) => [slot.from, slot.to])];
40764
- const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir7());
40985
+ const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir8());
40765
40986
  const checkArtifacts = async () => {
40766
40987
  const found = await preNArtifactBlockers(artifacts, options.liveness?.pidAlive, options.liveness);
40767
40988
  return found.length ? found.map(describeFenceBlocker).join("; ") : undefined;
@@ -40828,7 +41049,7 @@ async function stateLayoutFenceStep(ctx) {
40828
41049
  var processDecisions = new Map;
40829
41050
  function decisionKey(options) {
40830
41051
  const env = options.env ?? process.env;
40831
- const home = options.home ?? homedir7();
41052
+ const home = options.home ?? homedir8();
40832
41053
  return JSON.stringify([
40833
41054
  getOpenCodeConfigDir(env, home),
40834
41055
  home,
@@ -40926,6 +41147,136 @@ function isRecord20(value) {
40926
41147
  function supportsTurnEndNote(model) {
40927
41148
  return resolveClaudeModelCapabilities(model)?.turnEndNote === true;
40928
41149
  }
41150
+ var runnerReports = new Map;
41151
+ var SKIP_REPORT_LIMIT = 512;
41152
+ var RUNNER_REPORT_SESSION_LIMIT = 1024;
41153
+ function readRunnerNotes(handle) {
41154
+ try {
41155
+ const read = handle.turn_notes;
41156
+ if (typeof read !== "function")
41157
+ return [];
41158
+ const answer = read.call(handle);
41159
+ if (answer !== null && (typeof answer === "object" || typeof answer === "function") && typeof Reflect.get(answer, "then") === "function") {
41160
+ Promise.resolve(answer).catch(() => {});
41161
+ return [];
41162
+ }
41163
+ if (!Array.isArray(answer))
41164
+ return [];
41165
+ const notes = [];
41166
+ for (let index = 0;index < answer.length; index++) {
41167
+ try {
41168
+ const entry2 = answer[index];
41169
+ if (!isRecord20(entry2) || Array.isArray(entry2))
41170
+ continue;
41171
+ const { after_tool_use_id, text: text6 } = entry2;
41172
+ if (typeof after_tool_use_id !== "string" || typeof text6 !== "string" || !text6.trim() || new TextEncoder().encode(text6).byteLength > 16384)
41173
+ continue;
41174
+ notes.push({ after_tool_use_id, text: text6 });
41175
+ } catch {}
41176
+ }
41177
+ return notes;
41178
+ } catch {
41179
+ return [];
41180
+ }
41181
+ }
41182
+ function runnerNotes(sessionId) {
41183
+ try {
41184
+ const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
41185
+ if (typeof routing !== "function")
41186
+ return;
41187
+ const handle = routing(sessionId);
41188
+ if (isRecord20(handle) && typeof handle.turn_notes === "function")
41189
+ return { handle, notes: readRunnerNotes(handle) };
41190
+ } catch {
41191
+ return;
41192
+ }
41193
+ }
41194
+ function reportRunnerNote(handle, payload) {
41195
+ Promise.resolve().then(() => {
41196
+ const report = handle.report;
41197
+ if (typeof report === "function")
41198
+ return report.call(handle, payload);
41199
+ }).catch(() => {});
41200
+ }
41201
+ function applyRunnerTurnNotes(body, options) {
41202
+ if (!options.sessionId)
41203
+ return 0;
41204
+ const runner = runnerNotes(options.sessionId);
41205
+ if (!runner)
41206
+ return 0;
41207
+ let reported3 = runnerReports.get(options.sessionId);
41208
+ if (reported3) {
41209
+ runnerReports.delete(options.sessionId);
41210
+ } else {
41211
+ reported3 = { models: new Map, skipped: new Set };
41212
+ if (runnerReports.size >= RUNNER_REPORT_SESSION_LIMIT) {
41213
+ const oldest = runnerReports.keys().next();
41214
+ if (!oldest.done)
41215
+ runnerReports.delete(oldest.value);
41216
+ }
41217
+ }
41218
+ runnerReports.set(options.sessionId, reported3);
41219
+ const supported = options.isOAuth && supportsTurnEndNote(body.model);
41220
+ const model = options.modelId;
41221
+ if (reported3.models.get(model) !== supported) {
41222
+ reported3.models.set(model, supported);
41223
+ reportRunnerNote(runner.handle, {
41224
+ kind: "turn_notes_supported",
41225
+ model,
41226
+ supported
41227
+ });
41228
+ }
41229
+ const messages = Array.isArray(body.messages) ? body.messages : [];
41230
+ const anchors = new Map;
41231
+ for (const [index, message] of messages.entries()) {
41232
+ if (!isRecord20(message) || message.role !== "user" || !Array.isArray(message.content))
41233
+ continue;
41234
+ for (const block of message.content) {
41235
+ if (isRecord20(block) && block.type === "tool_result" && typeof block.tool_use_id === "string" && !anchors.has(block.tool_use_id))
41236
+ anchors.set(block.tool_use_id, index);
41237
+ }
41238
+ }
41239
+ const insertions = new Map;
41240
+ let inserted = 0;
41241
+ for (const note of runner.notes) {
41242
+ const index = anchors.get(note.after_tool_use_id);
41243
+ const next = index === undefined ? undefined : messages[index + 1];
41244
+ const reason = !options.isOAuth ? "not_oauth" : !supported ? "unsupported_model" : index === undefined ? "anchor_missing" : isRecord20(next) && next.role === "user" ? "before_user_message" : undefined;
41245
+ if (reason) {
41246
+ if (!reported3.skipped.has(note.after_tool_use_id)) {
41247
+ if (reported3.skipped.size >= SKIP_REPORT_LIMIT) {
41248
+ const oldest = reported3.skipped.values().next();
41249
+ if (!oldest.done)
41250
+ reported3.skipped.delete(oldest.value);
41251
+ }
41252
+ reported3.skipped.add(note.after_tool_use_id);
41253
+ reportRunnerNote(runner.handle, {
41254
+ kind: "turn_note_skipped",
41255
+ after_tool_use_id: note.after_tool_use_id,
41256
+ reason
41257
+ });
41258
+ }
41259
+ continue;
41260
+ }
41261
+ if (index === undefined)
41262
+ continue;
41263
+ const bucket = insertions.get(index) ?? [];
41264
+ bucket.push(note);
41265
+ insertions.set(index, bucket);
41266
+ inserted++;
41267
+ }
41268
+ if (inserted) {
41269
+ body.messages = messages.flatMap((message, index) => [
41270
+ message,
41271
+ ...(insertions.get(index) ?? []).map((note) => ({
41272
+ role: "system",
41273
+ clear_at: "next_user_message",
41274
+ content: note.text
41275
+ }))
41276
+ ]);
41277
+ }
41278
+ return inserted;
41279
+ }
40929
41280
  function applyTurnEndNotes(body, options = {}) {
40930
41281
  if (!supportsTurnEndNote(body.model) || !Array.isArray(body.messages))
40931
41282
  return 0;
@@ -41238,8 +41589,11 @@ export {
41238
41589
  getMaxSameAccountWait,
41239
41590
  getLogLevel,
41240
41591
  getLogFilePath,
41592
+ getLegacyCacheKeepRegistryDirectory,
41241
41593
  getKillswitchThresholdsForAccount,
41242
41594
  getKillswitchConfig,
41595
+ getHostHome,
41596
+ getHostDataHome,
41243
41597
  getHostClaustrumEnrollmentPaths,
41244
41598
  getFallbackReauthLabels,
41245
41599
  getDumpDirectory,
@@ -41254,6 +41608,7 @@ export {
41254
41608
  getClaudeCodeIdentityForVerifiedAccount,
41255
41609
  getClaudeCodeIdentity,
41256
41610
  getCacheKeepWindow,
41611
+ getCacheKeepRegistryDirectories,
41257
41612
  getCache1hPersistentMode,
41258
41613
  getCache1hMode,
41259
41614
  getAccountStoragePath,
@@ -41381,6 +41736,7 @@ export {
41381
41736
  askRouting,
41382
41737
  applyTurnEndNotes,
41383
41738
  applyThinkingBindingControls,
41739
+ applyRunnerTurnNotes,
41384
41740
  applyMidConversationOutputConfig,
41385
41741
  applyCustomHeaders,
41386
41742
  applyClaudeCodeMetadata,
@@ -41566,6 +41922,7 @@ export {
41566
41922
  CACHE_KEEP_TRANSIENT_RETRY_STEP_MS,
41567
41923
  CACHE_KEEP_TRANSIENT_RETRY_MAX_MS,
41568
41924
  CACHE_KEEP_TICK_MS,
41925
+ CACHE_KEEP_STOP_REASONS,
41569
41926
  CACHE_KEEP_RETRY_MAX_MS,
41570
41927
  CACHE_KEEP_RETRY_JITTER_MAX_MS,
41571
41928
  CACHE_KEEP_RETRY_BASE_MS,