@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/dist/cli.js +689 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +130 -67
  4. package/dist/index.js +734 -191
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +159 -72
  7. package/dist/server.js +734 -194
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +1 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +22 -2
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +36 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +74 -9
  18. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  19. package/dist/src/common-auth-embedded/claustrum/hub.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  21. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +2 -0
  23. package/dist/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  24. package/dist/src/common-auth-embedded/claustrum/usage.js +145 -0
  25. package/dist/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  26. package/dist/src/common-auth-embedded/commands/builtins.js +38 -0
  27. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  28. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  29. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  30. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  31. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  32. package/dist/src/common-auth-embedded/limits/axes.d.ts +63 -0
  33. package/dist/src/common-auth-embedded/limits/decide.d.ts +141 -0
  34. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  35. package/dist/src/common-auth-embedded/limits/families.d.ts +57 -0
  36. package/dist/src/common-auth-embedded/limits/marker.d.ts +64 -0
  37. package/dist/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  38. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  39. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  40. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  41. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  42. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  43. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  44. package/dist/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  45. package/dist/src/common-auth-embedded/opencode2/install.js +161 -18
  46. package/dist/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  47. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  48. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  49. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  50. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  51. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  52. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  53. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  54. package/dist/src/common-auth-embedded/source-output.json +254 -118
  55. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  56. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  57. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  58. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  59. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  60. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  61. package/dist/src/common-auth-embedded/store/limits-namespace.js +34 -0
  62. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  63. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  64. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  65. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  66. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  67. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  68. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  69. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  70. package/dist/src/runtime-layout.d.ts +9 -2
  71. package/dist/src/runtime-layout.d.ts.map +1 -1
  72. package/dist/src/runtime-layout.js +8 -8
  73. package/dist/src/runtime-layout.js.map +1 -1
  74. package/dist/src/setup.d.ts.map +1 -1
  75. package/dist/src/setup.js +29 -40
  76. package/dist/src/setup.js.map +1 -1
  77. package/dist/tui-build-map.json +9 -9
  78. package/dist/tui-ga-build-map.json +1 -1
  79. package/dist/types/src/cli.d.ts +1 -0
  80. package/dist/types/src/cli.d.ts.map +1 -1
  81. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  82. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  83. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  84. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  85. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  86. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  87. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  88. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  89. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +63 -0
  90. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +141 -0
  91. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  92. package/dist/types/src/common-auth-embedded/limits/families.d.ts +57 -0
  93. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +64 -0
  94. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  95. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  96. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  97. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  98. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  99. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  100. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  101. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  102. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  103. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  104. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  105. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  106. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  107. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  108. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  109. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  110. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  111. package/dist/types/src/runtime-layout.d.ts +9 -2
  112. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  113. package/dist/types/src/setup.d.ts.map +1 -1
  114. package/package.json +2 -2
  115. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  116. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  117. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  118. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  119. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  120. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  121. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  122. package/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  123. package/src/common-auth-embedded/claustrum/roster.js +2 -0
  124. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  125. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  126. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  127. package/src/common-auth-embedded/commands/builtins.js +38 -0
  128. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  129. package/src/common-auth-embedded/fs/private-files.js +7 -0
  130. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  131. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  132. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  133. package/src/common-auth-embedded/limits/axes.d.ts +63 -0
  134. package/src/common-auth-embedded/limits/decide.d.ts +141 -0
  135. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  136. package/src/common-auth-embedded/limits/families.d.ts +57 -0
  137. package/src/common-auth-embedded/limits/marker.d.ts +64 -0
  138. package/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  139. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  140. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  141. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  142. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  143. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  144. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  145. package/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  146. package/src/common-auth-embedded/opencode2/install.js +161 -18
  147. package/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  148. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  149. package/src/common-auth-embedded/routing/admission.js +17 -7
  150. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  151. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  152. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  153. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  154. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  155. package/src/common-auth-embedded/source-output.json +254 -118
  156. package/src/common-auth-embedded/store/attribution.js +3 -2
  157. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  158. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  159. package/src/common-auth-embedded/store/hooks.js +20 -5
  160. package/src/common-auth-embedded/store/index.d.ts +1 -0
  161. package/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  162. package/src/common-auth-embedded/store/limits-namespace.js +34 -0
  163. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  164. package/src/common-auth-embedded/store/pool.js +2 -0
  165. package/src/common-auth-embedded/store/provider-state.js +5 -5
  166. package/src/common-auth-embedded/store/refresh.js +1 -1
  167. package/src/common-auth-embedded/store/schema.js +9 -4
  168. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  169. package/src/common-auth-embedded/store/settings.js +11 -4
  170. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  171. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  172. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  173. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
package/dist/cli.js CHANGED
@@ -634,6 +634,9 @@ function loadBackend() {
634
634
  });
635
635
  return backend;
636
636
  }
637
+ function isWindowsSharingViolation(error) {
638
+ return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
639
+ }
637
640
  async function privateOperation(path2, stage, operation) {
638
641
  try {
639
642
  return await operation();
@@ -8566,6 +8569,48 @@ var init_identity = __esm({
8566
8569
  }
8567
8570
  });
8568
8571
 
8572
+ // ../core/dist/common-auth-embedded/store/hooks.js
8573
+ import { AsyncLocalStorage } from "node:async_hooks";
8574
+ function assertNotInsideHook(operation) {
8575
+ if (insideHook.getStore() !== void 0)
8576
+ throw new PoolReentryError(operation);
8577
+ }
8578
+ function assertLimitsWriteAllowed() {
8579
+ if (insideHook.getStore()?.storeLocksReleased === false || insideCodec.getStore())
8580
+ throw new PoolReentryError("updateLimitsNamespace");
8581
+ }
8582
+ function runInsideCodec(fn) {
8583
+ return insideCodec.run(true, fn);
8584
+ }
8585
+ function runInsideHook(operation, fn, storeLocksReleased = false) {
8586
+ return insideHook.run({
8587
+ operation,
8588
+ storeLocksReleased: storeLocksReleased && insideHook.getStore()?.storeLocksReleased !== false
8589
+ }, async () => await fn());
8590
+ }
8591
+ async function callFailureHook(operation, hook, rowId2, error, logger2) {
8592
+ if (!hook)
8593
+ return;
8594
+ try {
8595
+ await runInsideHook(operation, () => hook(rowId2, error), true);
8596
+ } catch (hookError) {
8597
+ logger2?.warn("store failure hook threw; the original failure stands", {
8598
+ operation,
8599
+ rowId: rowId2,
8600
+ error: hookError instanceof Error ? hookError.message : String(hookError)
8601
+ });
8602
+ }
8603
+ }
8604
+ var insideHook, insideCodec;
8605
+ var init_hooks = __esm({
8606
+ "../core/dist/common-auth-embedded/store/hooks.js"() {
8607
+ "use strict";
8608
+ init_errors();
8609
+ insideHook = new AsyncLocalStorage();
8610
+ insideCodec = new AsyncLocalStorage();
8611
+ }
8612
+ });
8613
+
8569
8614
  // ../core/dist/common-auth-embedded/fs/atomic-write.js
8570
8615
  import { randomUUID as randomUUID6 } from "node:crypto";
8571
8616
  import { mkdir as mkdir6, open as open3, rename as rename5, rm as rm3 } from "node:fs/promises";
@@ -8947,37 +8992,83 @@ async function acquireRefreshFileLockWithClock(options) {
8947
8992
  await rm4(path2, { recursive: true, force: true }).catch(() => {
8948
8993
  });
8949
8994
  }
8950
- async function releaseEvictionMarker() {
8951
- if (await ownsEvictionMarker()) {
8952
- await removeLeaseObject(evictPath);
8953
- }
8995
+ function isRetryableRemoval(error, path2) {
8996
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
8997
+ return false;
8998
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
8999
+ }
9000
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
9001
+ let original;
9002
+ let delayMs = 5;
9003
+ while (await stillOwned()) {
9004
+ try {
9005
+ await removeLeaseObject(path2);
9006
+ return;
9007
+ } catch (error) {
9008
+ if (!isRetryableRemoval(error, path2))
9009
+ throw error;
9010
+ original ??= error;
9011
+ }
9012
+ const remainingMs = deadline - performance.now();
9013
+ if (remainingMs <= 0)
9014
+ throw original;
9015
+ await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9016
+ if (performance.now() >= deadline)
9017
+ throw original;
9018
+ delayMs = Math.min(delayMs * 2, 50);
9019
+ }
9020
+ }
9021
+ async function releaseEvictionMarker(deadline) {
9022
+ let ownedDirectory;
9023
+ await removeOwnedLeaseObject(evictPath, async () => {
9024
+ if (!windowsPrivateFiles)
9025
+ return ownsEvictionMarker();
9026
+ const current = await lstat3(evictPath).catch((error) => {
9027
+ if (error.code !== "ENOENT")
9028
+ throw error;
9029
+ return void 0;
9030
+ });
9031
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9032
+ return false;
9033
+ if (await ownsEvictionMarker()) {
9034
+ ownedDirectory = current;
9035
+ return true;
9036
+ }
9037
+ if (!ownedDirectory)
9038
+ return false;
9039
+ try {
9040
+ await stat3(evictOwnerPath);
9041
+ return false;
9042
+ } catch (error) {
9043
+ if (error.code !== "ENOENT")
9044
+ throw error;
9045
+ return true;
9046
+ }
9047
+ }, deadline);
8954
9048
  }
8955
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
9049
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
8956
9050
  if (!created)
8957
9051
  return false;
8958
- let current;
8959
- try {
8960
- const st = await lstat3(evictPath);
8961
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
8962
- } catch {
8963
- return false;
8964
- }
8965
- if (!sameMarkerDirectory(created, current))
8966
- return false;
9052
+ let stillOurs = false;
8967
9053
  try {
8968
- await stat3(evictOwnerPath);
8969
- return true;
8970
- } catch (error) {
8971
- if (error.code !== "ENOENT")
8972
- return true;
8973
- }
8974
- try {
8975
- await removeLeaseObject(evictPath);
9054
+ await removeOwnedLeaseObject(evictPath, async () => {
9055
+ stillOurs = false;
9056
+ const st = await lstat3(evictPath).catch(() => void 0);
9057
+ if (!st || !sameMarkerDirectory(created, st))
9058
+ return false;
9059
+ stillOurs = true;
9060
+ try {
9061
+ await stat3(evictOwnerPath);
9062
+ return false;
9063
+ } catch (error) {
9064
+ return error.code === "ENOENT";
9065
+ }
9066
+ }, deadline);
8976
9067
  } catch {
8977
9068
  }
8978
- return true;
9069
+ return stillOurs;
8979
9070
  }
8980
- async function tryAcquireEvictionMarker() {
9071
+ async function tryAcquireEvictionMarker(deadline) {
8981
9072
  if (windowsPrivateFiles)
8982
9073
  await createPrivateDirectoryExclusive(evictPath);
8983
9074
  else
@@ -9001,11 +9092,11 @@ async function acquireRefreshFileLockWithClock(options) {
9001
9092
  else
9002
9093
  await createExclusiveText(evictOwnerPath, bytes);
9003
9094
  } catch (error) {
9004
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
9095
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9005
9096
  if (isLostMarkerRaceError(error) && !stillOurs)
9006
9097
  return false;
9007
9098
  try {
9008
- await releaseEvictionMarker();
9099
+ await releaseEvictionMarker(deadline);
9009
9100
  } catch {
9010
9101
  }
9011
9102
  throw error;
@@ -9014,7 +9105,7 @@ async function acquireRefreshFileLockWithClock(options) {
9014
9105
  await options.onStep("eviction-marker-acquired");
9015
9106
  return true;
9016
9107
  }
9017
- async function recoverStaleEvictionMarker() {
9108
+ async function recoverStaleEvictionMarker(deadline) {
9018
9109
  let evictStat;
9019
9110
  try {
9020
9111
  evictStat = await stat3(evictPath);
@@ -9059,12 +9150,22 @@ async function acquireRefreshFileLockWithClock(options) {
9059
9150
  }
9060
9151
  if (options.onStep)
9061
9152
  await options.onStep("stale-marker-claimed");
9062
- await removeLeaseObject(claimedPath);
9153
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9154
+ await removeOwnedLeaseObject(claimedPath, async () => {
9155
+ if (!claimedIdentity)
9156
+ return true;
9157
+ const current = await lstat3(claimedPath).catch((error) => {
9158
+ if (error.code !== "ENOENT")
9159
+ throw error;
9160
+ return void 0;
9161
+ });
9162
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
9163
+ }, deadline);
9063
9164
  return "recovered";
9064
9165
  }
9065
- async function withEvictionMarker(action) {
9166
+ async function withEvictionMarker(action, deadline) {
9066
9167
  try {
9067
- if (!await tryAcquireEvictionMarker())
9168
+ if (!await tryAcquireEvictionMarker(deadline))
9068
9169
  return false;
9069
9170
  } catch (error) {
9070
9171
  if (error.code === "EEXIST") {
@@ -9081,11 +9182,23 @@ async function acquireRefreshFileLockWithClock(options) {
9081
9182
  }
9082
9183
  throw error;
9083
9184
  }
9185
+ let actionFailed = false;
9186
+ let actionError;
9084
9187
  try {
9085
9188
  await action();
9086
- } finally {
9087
- await releaseEvictionMarker();
9189
+ } catch (error) {
9190
+ actionFailed = true;
9191
+ actionError = error;
9192
+ }
9193
+ try {
9194
+ await releaseEvictionMarker(deadline);
9195
+ } catch (error) {
9196
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
9197
+ throw actionError;
9198
+ throw error;
9088
9199
  }
9200
+ if (actionFailed)
9201
+ throw actionError;
9089
9202
  return true;
9090
9203
  }
9091
9204
  async function relinquishLockAfterMarkerLoss() {
@@ -9322,6 +9435,7 @@ async function acquireRefreshFileLockWithClock(options) {
9322
9435
  await renewalInFlight;
9323
9436
  const deadline = performance.now() + EVICT_TTL + 1e3;
9324
9437
  let delayMs = 5;
9438
+ let removalError;
9325
9439
  for (; ; ) {
9326
9440
  try {
9327
9441
  let removalConfirmed = false;
@@ -9346,7 +9460,7 @@ async function acquireRefreshFileLockWithClock(options) {
9346
9460
  return;
9347
9461
  await removeLeaseObject(lockPath);
9348
9462
  removalConfirmed = true;
9349
- });
9463
+ }, deadline);
9350
9464
  if (markerAcquired) {
9351
9465
  if (windowsPrivateFiles && !removalConfirmed)
9352
9466
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -9357,20 +9471,25 @@ async function acquireRefreshFileLockWithClock(options) {
9357
9471
  }
9358
9472
  if (signal?.aborted)
9359
9473
  return;
9360
- await recoverStaleEvictionMarker();
9474
+ await recoverStaleEvictionMarker(deadline);
9361
9475
  } catch (error) {
9362
- if (windowsPrivateFiles)
9363
- throw error;
9364
- return;
9476
+ if (!isRetryableRemoval(error, lockPath)) {
9477
+ if (windowsPrivateFiles)
9478
+ throw error;
9479
+ return;
9480
+ }
9481
+ removalError ??= error;
9365
9482
  }
9366
9483
  const remainingMs = deadline - performance.now();
9367
9484
  if (remainingMs <= 0)
9368
9485
  break;
9369
9486
  await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9487
+ if (windowsPrivateFiles && performance.now() >= deadline)
9488
+ break;
9370
9489
  delayMs = Math.min(delayMs * 2, 50);
9371
9490
  }
9372
9491
  if (windowsPrivateFiles)
9373
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
9492
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9374
9493
  code: "ETIMEDOUT"
9375
9494
  });
9376
9495
  }
@@ -9394,7 +9513,7 @@ function lockPathFor(target, name) {
9394
9513
  return `${target}.${name}.lock`;
9395
9514
  }
9396
9515
  function isChangingLockRead(error, target, name) {
9397
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.reason !== "io-error" || error.win32Code !== 32 && error.win32Code !== 303 || error.stage !== "read" && error.stage !== "verify")
9516
+ if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
9398
9517
  return false;
9399
9518
  const path2 = resolve3(lockPathFor(target, name));
9400
9519
  return error.path === path2 || error.path === join6(path2, "owner.json");
@@ -9466,37 +9585,6 @@ var init_with_lock = __esm({
9466
9585
  }
9467
9586
  });
9468
9587
 
9469
- // ../core/dist/common-auth-embedded/store/hooks.js
9470
- import { AsyncLocalStorage } from "node:async_hooks";
9471
- function assertNotInsideHook(operation) {
9472
- if (insideHook.getStore() !== void 0)
9473
- throw new PoolReentryError(operation);
9474
- }
9475
- function runInsideHook(operation, fn) {
9476
- return insideHook.run(operation, async () => await fn());
9477
- }
9478
- async function callFailureHook(operation, hook, rowId2, error, logger2) {
9479
- if (!hook)
9480
- return;
9481
- try {
9482
- await runInsideHook(operation, () => hook(rowId2, error));
9483
- } catch (hookError) {
9484
- logger2?.warn("store failure hook threw; the original failure stands", {
9485
- operation,
9486
- rowId: rowId2,
9487
- error: hookError instanceof Error ? hookError.message : String(hookError)
9488
- });
9489
- }
9490
- }
9491
- var insideHook;
9492
- var init_hooks = __esm({
9493
- "../core/dist/common-auth-embedded/store/hooks.js"() {
9494
- "use strict";
9495
- init_errors();
9496
- insideHook = new AsyncLocalStorage();
9497
- }
9498
- });
9499
-
9500
9588
  // ../core/dist/common-auth-embedded/store/refresh-lock.js
9501
9589
  async function acquirePoolLock(spec, defaults, env3) {
9502
9590
  const emit = (type) => {
@@ -9728,7 +9816,7 @@ function stampFor(credential, credentialEpoch2, binding, options = {}) {
9728
9816
  };
9729
9817
  }
9730
9818
  function providerStateDigest(codec, value) {
9731
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
9819
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
9732
9820
  return createHash4("sha256").update(`provider-state\0${JSON.stringify(bound ?? null)}`).digest("hex");
9733
9821
  }
9734
9822
  function boundProviderStateDigest(account, credential, credentialEpoch2, identity3) {
@@ -9895,8 +9983,8 @@ function parseEntry(raw, codec) {
9895
9983
  return void 0;
9896
9984
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
9897
9985
  return void 0;
9898
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
9899
- if ("quota" in raw && !codec.validate(quota))
9986
+ const quota = "quota" in raw && codec.decode ? runInsideCodec(() => codec.decode?.(raw.quota)) : raw.quota;
9987
+ if ("quota" in raw && !runInsideCodec(() => codec.validate(quota)))
9900
9988
  return void 0;
9901
9989
  if ("staged" in raw && !parseReservation(raw.staged))
9902
9990
  return void 0;
@@ -10068,7 +10156,7 @@ function providerStateFields(account, credential, credentialEpoch2, identity3, c
10068
10156
  if (digest3 === void 0)
10069
10157
  return { providerStateDropped: "uncovered" };
10070
10158
  const value = account[PROVIDER_STATE_KEY];
10071
- if (!codec?.validate(value))
10159
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
10072
10160
  return { providerStateDropped: "invalid" };
10073
10161
  if (providerStateDigest(codec, value) !== digest3)
10074
10162
  return { providerStateDropped: "uncovered" };
@@ -10145,6 +10233,7 @@ var POOL_KEY, POOL_SCHEMA_VERSION, POOL_ROWS_KEY, POOL_RETIRED_EPOCHS_KEY, LEGAC
10145
10233
  var init_schema = __esm({
10146
10234
  "../core/dist/common-auth-embedded/store/schema.js"() {
10147
10235
  "use strict";
10236
+ init_hooks();
10148
10237
  POOL_KEY = "commonAuthPool";
10149
10238
  POOL_SCHEMA_VERSION = 1;
10150
10239
  POOL_ROWS_KEY = "rows";
@@ -10845,8 +10934,8 @@ function assertQuotaRow(id, attribution, row) {
10845
10934
  });
10846
10935
  }
10847
10936
  function mergedQuota(ctx, id, stored, observation) {
10848
- const merged = ctx.codec.merge(stored, observation);
10849
- if (!ctx.codec.validate(merged))
10937
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
10938
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
10850
10939
  throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
10851
10940
  return merged;
10852
10941
  }
@@ -10886,6 +10975,7 @@ var init_attribution = __esm({
10886
10975
  "../core/dist/common-auth-embedded/store/attribution.js"() {
10887
10976
  "use strict";
10888
10977
  init_errors();
10978
+ init_hooks();
10889
10979
  init_mutate();
10890
10980
  init_refresh_lock();
10891
10981
  init_runtime();
@@ -10893,6 +10983,46 @@ var init_attribution = __esm({
10893
10983
  }
10894
10984
  });
10895
10985
 
10986
+ // ../core/dist/common-auth-embedded/store/limits-namespace.js
10987
+ async function updatePoolLimitsNamespace(rt, mutator) {
10988
+ assertLimitsWriteAllowed();
10989
+ const { ctx } = rt;
10990
+ await runOperation(ctx, "updateLimitsNamespace", void 0, void 0, async (locks, progress) => {
10991
+ for (const spec of ctx.storeLocks)
10992
+ await locks.acquire(spec);
10993
+ const result = await readPool(ctx);
10994
+ if (result.status !== "ready")
10995
+ throw notReadyError(result, "updateLimitsNamespace", void 0);
10996
+ const rows = result.rows.map(({ id, credentialEpoch: credentialEpoch2, identity: identity3 }) => ({
10997
+ id,
10998
+ credentialEpoch: credentialEpoch2,
10999
+ identity: identity3
11000
+ }));
11001
+ const envelope = await runInsideHook("updateLimitsNamespace", () => mutator(structuredClone(result.config.commonAuthLimits), rows));
11002
+ const config = { ...result.config, commonAuthLimits: envelope };
11003
+ const info = {
11004
+ operation: "updateLimitsNamespace",
11005
+ rowId: void 0
11006
+ };
11007
+ await writeJsonAtomic2(ctx.configPath, config, {
11008
+ beforeRename: async () => {
11009
+ await ctx.onStep?.("before-config-write", info);
11010
+ await locks.assertAll();
11011
+ }
11012
+ });
11013
+ progress.writes++;
11014
+ await ctx.onStep?.("after-config-write", info);
11015
+ });
11016
+ }
11017
+ var init_limits_namespace = __esm({
11018
+ "../core/dist/common-auth-embedded/store/limits-namespace.js"() {
11019
+ "use strict";
11020
+ init_atomic_write2();
11021
+ init_hooks();
11022
+ init_mutate();
11023
+ }
11024
+ });
11025
+
10896
11026
  // ../core/dist/common-auth-embedded/store/provider-state.js
10897
11027
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
10898
11028
  if (!codec)
@@ -10906,7 +11036,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
10906
11036
  }
10907
11037
  if (normalized === void 0)
10908
11038
  throw refusal2(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
10909
- if (!codec.validate(normalized))
11039
+ if (!runInsideCodec(() => codec.validate(normalized)))
10910
11040
  throw refusal2(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
10911
11041
  return normalized;
10912
11042
  }
@@ -10915,18 +11045,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
10915
11045
  return { kind: "set", value: incoming };
10916
11046
  return {
10917
11047
  kind: "set",
10918
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), "the merged provider state")
11048
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), "the merged provider state")
10919
11049
  };
10920
11050
  }
10921
11051
  function replacementProviderState(codec, row, credentialEpoch2, identity3, incoming) {
10922
11052
  const hook = codec?.onReplace;
10923
- const next = hook ? hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
11053
+ const next = hook ? runInsideCodec(() => hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
10924
11054
  id: row.id,
10925
11055
  credentialEpoch: credentialEpoch2,
10926
11056
  ...row.identity !== void 0 ? { previousIdentity: row.identity } : {},
10927
11057
  ...identity3 !== void 0 ? { identity: identity3 } : {},
10928
11058
  ...incoming !== void 0 ? { incoming: structuredClone(incoming) } : {}
10929
- }) : incoming;
11059
+ })) : incoming;
10930
11060
  if (next === void 0)
10931
11061
  return { kind: "clear" };
10932
11062
  if (!hook)
@@ -13186,7 +13316,7 @@ async function refreshRow(rt, id, provider2, options = {}) {
13186
13316
  if (options.onPersisted) {
13187
13317
  try {
13188
13318
  const persisted = options.onPersisted;
13189
- await runInsideHook("refresh", () => persisted(id, commit.stored));
13319
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
13190
13320
  } catch (cause) {
13191
13321
  throw new PoolOperationError({
13192
13322
  operation: "refresh",
@@ -13295,7 +13425,7 @@ function defineKey(target, key, value) {
13295
13425
  function composeConfig(config, next) {
13296
13426
  const out = {};
13297
13427
  for (const [key, value] of Object.entries(config)) {
13298
- if (POOL_OWNED_KEYS.includes(key))
13428
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
13299
13429
  defineKey(out, key, value);
13300
13430
  else if (Object.hasOwn(next, key))
13301
13431
  defineKey(out, key, next[key]);
@@ -13347,9 +13477,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
13347
13477
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
13348
13478
  if (owned.length > 0)
13349
13479
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
13350
- if (isDeepStrictEqual3(next, current))
13351
- return { settings: current, outcome: "unchanged" };
13480
+ if (Object.hasOwn(next, "commonAuthLimits") && (!Object.hasOwn(current, "commonAuthLimits") || !isDeepStrictEqual3(next.commonAuthLimits, current.commonAuthLimits)))
13481
+ throw settingsRefusal("settings cannot alter commonAuthLimits; use updateLimitsNamespace");
13352
13482
  const config = composeConfig(result.config, next);
13483
+ if (isDeepStrictEqual3(settingsOf2(config), current))
13484
+ return { settings: current, outcome: "unchanged" };
13353
13485
  const info = { operation: "updateSettings", rowId: void 0 };
13354
13486
  await writeJsonAtomic2(ctx.configPath, config, {
13355
13487
  beforeRename: async () => {
@@ -13484,6 +13616,7 @@ function openPoolStore(options) {
13484
13616
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
13485
13617
  readSettings: () => readPoolSettings(rt),
13486
13618
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
13619
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
13487
13620
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
13488
13621
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
13489
13622
  recordQuota: record3,
@@ -13498,6 +13631,7 @@ var init_pool = __esm({
13498
13631
  "../core/dist/common-auth-embedded/store/pool.js"() {
13499
13632
  "use strict";
13500
13633
  init_attribution();
13634
+ init_limits_namespace();
13501
13635
  init_mutate();
13502
13636
  init_provider_state();
13503
13637
  init_publication();
@@ -13603,7 +13737,7 @@ function exclusionFor(id, inputs, now) {
13603
13737
  }
13604
13738
  return void 0;
13605
13739
  }
13606
- function judgeStageOne(id, projection, requiredLabels, now) {
13740
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
13607
13741
  if (projection.limits.length === 0) {
13608
13742
  return {
13609
13743
  id,
@@ -13627,7 +13761,7 @@ function judgeStageOne(id, projection, requiredLabels, now) {
13627
13761
  }
13628
13762
  const exhausted = projection.limits.filter(readsExhausted);
13629
13763
  for (const limit of exhausted) {
13630
- if (futureResetAt(limit, now) === void 0) {
13764
+ if (futureResetAt(limit, now) === void 0 && !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
13631
13765
  return {
13632
13766
  id,
13633
13767
  stage: 1,
@@ -13660,6 +13794,7 @@ function admit(input) {
13660
13794
  const excluded = [];
13661
13795
  const refused2 = [];
13662
13796
  const survivors = [];
13797
+ const needsPull = /* @__PURE__ */ new Set();
13663
13798
  for (const row of input.rows) {
13664
13799
  const exclusion = exclusionFor(row.id, input, input.now);
13665
13800
  if (exclusion) {
@@ -13671,7 +13806,10 @@ function admit(input) {
13671
13806
  continue;
13672
13807
  }
13673
13808
  const projection = projectQuota(row.quota, scope);
13674
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
13809
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
13810
+ if (projection.limits.some((limit) => readsExhausted(limit) && futureResetAt(limit, input.now) === void 0 && lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
13811
+ needsPull.add(row.id);
13812
+ const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
13675
13813
  if (refusal3) {
13676
13814
  refused2.push(refusal3);
13677
13815
  continue;
@@ -13697,7 +13835,10 @@ function admit(input) {
13697
13835
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
13698
13836
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
13699
13837
  refused2.sort(byInput);
13700
- const pulls = refused2.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
13838
+ for (const refusal3 of refused2)
13839
+ if ("pullRequested" in refusal3)
13840
+ needsPull.add(refusal3.id);
13841
+ const pulls = input.rows.filter((row) => needsPull.has(row.id)).map((row) => row.id);
13701
13842
  for (const id of pulls)
13702
13843
  input.requestPull?.(id);
13703
13844
  return { admitted, refused: refused2, excluded, pulls };
@@ -14668,6 +14809,44 @@ function routingSection(options, snap) {
14668
14809
  return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
14669
14810
  }
14670
14811
  });
14812
+ if (options.routing?.sameAccountWait) {
14813
+ const waitLabel = "Longest wait on the same account";
14814
+ const waitChoices = [
14815
+ { value: "0", label: "Don't wait" },
14816
+ { value: "15", label: "15 minutes" },
14817
+ { value: "max", label: "Until the cache expires" }
14818
+ ];
14819
+ const rawWait = record(snap.settings.routing).maxSameAccountWait;
14820
+ const wait2 = String(rawWait === 0 || rawWait === "max" ? rawWait : 15);
14821
+ const waitName = (value) => waitChoices.find((choice) => choice.value === value)?.label ?? value;
14822
+ lines.push(`${waitLabel}: ${waitName(wait2)}`);
14823
+ actions.push({
14824
+ id: "maxSameAccountWait",
14825
+ label: waitLabel,
14826
+ group: ACTIONS_GROUP,
14827
+ knobs: [
14828
+ {
14829
+ kind: "choice",
14830
+ id: "maxSameAccountWait",
14831
+ label: waitLabel,
14832
+ choices: waitChoices,
14833
+ value: wait2
14834
+ }
14835
+ ],
14836
+ run: async ({ values }) => {
14837
+ const value = String(values.maxSameAccountWait);
14838
+ const maxSameAccountWait = value === "max" ? "max" : Number(value);
14839
+ await store.updateSettings((settings) => {
14840
+ settings.routing = {
14841
+ ...record(settings.routing),
14842
+ maxSameAccountWait
14843
+ };
14844
+ return void 0;
14845
+ }, locks);
14846
+ return `${waitLabel} set to ${waitName(value)}.`;
14847
+ }
14848
+ });
14849
+ }
14671
14850
  return {
14672
14851
  id: "routing",
14673
14852
  slot: "routing",
@@ -17732,9 +17911,144 @@ var init_shutdown = __esm({
17732
17911
  }
17733
17912
  });
17734
17913
 
17914
+ // ../core/dist/common-auth-embedded/claustrum/usage.js
17915
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
17916
+ function plain(value) {
17917
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
17918
+ }
17919
+ var ScopedUsageReporter;
17920
+ var init_usage = __esm({
17921
+ "../core/dist/common-auth-embedded/claustrum/usage.js"() {
17922
+ "use strict";
17923
+ ScopedUsageReporter = class {
17924
+ options;
17925
+ #queue = /* @__PURE__ */ new Map();
17926
+ #latest = /* @__PURE__ */ new Map();
17927
+ #errors = /* @__PURE__ */ new Set();
17928
+ #timer;
17929
+ #running;
17930
+ #closing = false;
17931
+ #stopped = false;
17932
+ #dropped = 0;
17933
+ constructor(options) {
17934
+ this.options = options;
17935
+ }
17936
+ state() {
17937
+ return {
17938
+ pending: this.#queue.size,
17939
+ inFlight: this.#running !== void 0,
17940
+ dropped: this.#dropped
17941
+ };
17942
+ }
17943
+ report(credentialId, reading) {
17944
+ if (this.#closing || !this.options.client.reportUsageScoped)
17945
+ return;
17946
+ try {
17947
+ if (!this.options.owns(credentialId)) {
17948
+ this.#dropped++;
17949
+ return;
17950
+ }
17951
+ if (!plain(reading) || "credentialId" in reading || "vouched" in reading)
17952
+ throw new Error("invalid reading");
17953
+ const json = JSON.stringify(reading);
17954
+ if (Buffer.byteLength(json, "utf8") > 15360)
17955
+ throw new Error("oversized reading");
17956
+ const copy = JSON.parse(json);
17957
+ if (!plain(copy) || "credentialId" in copy || "vouched" in copy || typeof copy.observedAtMs !== "number" || !Number.isFinite(copy.observedAtMs))
17958
+ throw new Error("invalid reading");
17959
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
17960
+ this.#dropped++;
17961
+ return;
17962
+ }
17963
+ if (this.#queue.has(credentialId))
17964
+ this.#dropped++;
17965
+ this.#latest.set(credentialId, copy.observedAtMs);
17966
+ this.#queue.set(credentialId, copy);
17967
+ if (!this.#timer && !this.#running) {
17968
+ this.#timer = this.options.setTimeout(() => {
17969
+ this.#timer = void 0;
17970
+ this.#flush();
17971
+ }, 1e3);
17972
+ this.#timer.unref?.();
17973
+ }
17974
+ } catch {
17975
+ this.#dropped++;
17976
+ }
17977
+ }
17978
+ forget(credentialId) {
17979
+ if (this.#queue.delete(credentialId))
17980
+ this.#dropped++;
17981
+ this.#latest.delete(credentialId);
17982
+ }
17983
+ #flush() {
17984
+ if (this.#running || !this.#queue.size || this.#stopped)
17985
+ return this.#running;
17986
+ const running = Promise.resolve().then(async () => {
17987
+ while (!this.#stopped && this.#queue.size) {
17988
+ const entry = this.#queue.entries().next().value;
17989
+ if (!entry)
17990
+ break;
17991
+ const [credentialId, reading] = entry;
17992
+ this.#queue.delete(credentialId);
17993
+ try {
17994
+ const enrollmentToken = await this.options.token();
17995
+ if (this.#stopped || !this.options.owns(credentialId)) {
17996
+ if (!this.#stopped)
17997
+ this.#dropped++;
17998
+ continue;
17999
+ }
18000
+ await this.options.client.reportUsageScoped?.({
18001
+ credentialId,
18002
+ reading,
18003
+ enrollmentToken
18004
+ });
18005
+ } catch (error) {
18006
+ if (!this.#stopped)
18007
+ this.#dropped++;
18008
+ this.#log(error);
18009
+ }
18010
+ }
18011
+ });
18012
+ this.#running = running;
18013
+ void running.finally(() => {
18014
+ this.#running = void 0;
18015
+ });
18016
+ return running;
18017
+ }
18018
+ #log(error) {
18019
+ let code2 = "transport_error";
18020
+ try {
18021
+ if (error instanceof ClaustrumCredentialError3)
18022
+ code2 = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code2;
18023
+ if (this.#errors.has(code2))
18024
+ return;
18025
+ this.#errors.add(code2);
18026
+ this.options.logger.debug("claustrum usage report dropped", { code: code2 });
18027
+ } catch {
18028
+ }
18029
+ }
18030
+ /** Start the final flush; the custody's existing shutdown drain bounds it. */
18031
+ close() {
18032
+ this.#closing = true;
18033
+ if (this.#timer)
18034
+ this.options.clearTimeout(this.#timer);
18035
+ this.#timer = void 0;
18036
+ return this.#flush();
18037
+ }
18038
+ drop() {
18039
+ this.#stopped = true;
18040
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
18041
+ this.#running = void 0;
18042
+ this.#queue.clear();
18043
+ this.#latest.clear();
18044
+ }
18045
+ };
18046
+ }
18047
+ });
18048
+
17735
18049
  // ../core/dist/common-auth-embedded/claustrum/custody.js
17736
18050
  import { channel } from "node:diagnostics_channel";
17737
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
18051
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
17738
18052
  function isScopedCredentialRotation(served, current) {
17739
18053
  return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
17740
18054
  }
@@ -17749,6 +18063,12 @@ function scopedRetryReason(served, current) {
17749
18063
  return "version-unchanged";
17750
18064
  return "rotated";
17751
18065
  }
18066
+ function checkedEnrollmentToken(value) {
18067
+ if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
18068
+ throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
18069
+ }
18070
+ return value.token;
18071
+ }
17752
18072
  function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
17753
18073
  const retry = isScopedCredentialRotation(served, current);
17754
18074
  logger2.debug("scoped 401 re-authorized", {
@@ -17857,6 +18177,7 @@ var init_custody = __esm({
17857
18177
  init_errors2();
17858
18178
  init_host_slot();
17859
18179
  init_shutdown();
18180
+ init_usage();
17860
18181
  init_watch();
17861
18182
  defaultLogger = createLogger2("claustrum");
17862
18183
  phaseDiagnostics = channel("common-auth.claustrum.phases");
@@ -17874,6 +18195,8 @@ var init_custody = __esm({
17874
18195
  #reports = /* @__PURE__ */ new WeakMap();
17875
18196
  #kept = /* @__PURE__ */ new Map();
17876
18197
  #keptAttempts = /* @__PURE__ */ new WeakMap();
18198
+ #usage;
18199
+ #usageServed = /* @__PURE__ */ new Map();
17877
18200
  #setTimeout;
17878
18201
  #clearTimeout;
17879
18202
  #outage = false;
@@ -17888,6 +18211,7 @@ var init_custody = __esm({
17888
18211
  #watches = /* @__PURE__ */ new Set();
17889
18212
  #tokenReads = /* @__PURE__ */ new Set();
17890
18213
  #warnShutdown;
18214
+ #onDrainTimeout;
17891
18215
  #disposing;
17892
18216
  constructor(options) {
17893
18217
  const tokenPath = options.tokenPath;
@@ -17907,13 +18231,21 @@ var init_custody = __esm({
17907
18231
  this.#warnShutdown = shutdownWarning(this.#logger);
17908
18232
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
17909
18233
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
18234
+ this.#usage = new ScopedUsageReporter({
18235
+ client: this.#client,
18236
+ owns: (id) => this.#usageServed.has(id),
18237
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
18238
+ logger: this.#logger,
18239
+ setTimeout: this.#setTimeout,
18240
+ clearTimeout: this.#clearTimeout
18241
+ });
17910
18242
  }
17911
18243
  /** A watch losing its transport is the same outage as an unreachable read. */
17912
18244
  transportLost(error) {
17913
18245
  if (this.#closed || this.#outage)
17914
18246
  return;
17915
18247
  this.#outage = true;
17916
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
18248
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError();
17917
18249
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
17918
18250
  this.#scheduleProbe();
17919
18251
  }
@@ -17982,10 +18314,7 @@ var init_custody = __esm({
17982
18314
  });
17983
18315
  }
17984
18316
  this.#check(signal);
17985
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
17986
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
17987
- }
17988
- return value.token;
18317
+ return checkedEnrollmentToken(value);
17989
18318
  }
17990
18319
  async #call(operation, signal) {
17991
18320
  this.#check(signal);
@@ -18009,7 +18338,7 @@ var init_custody = __esm({
18009
18338
  this.transportLost(error);
18010
18339
  else
18011
18340
  this.reachable();
18012
- if (error instanceof ClaustrumCredentialError3)
18341
+ if (error instanceof ClaustrumCredentialError4)
18013
18342
  throw error;
18014
18343
  if (classifyVaultFailure(error) === "unreachable")
18015
18344
  throw new ClaustrumUnreachableError();
@@ -18039,6 +18368,7 @@ var init_custody = __esm({
18039
18368
  token = await this.#token(signal);
18040
18369
  } catch (error) {
18041
18370
  this.#kept.clear();
18371
+ this.#clearUsageOwnership();
18042
18372
  throw error;
18043
18373
  }
18044
18374
  if (phaseDiagnostics.hasSubscribers)
@@ -18140,11 +18470,19 @@ var init_custody = __esm({
18140
18470
  else {
18141
18471
  this.reachable();
18142
18472
  this.#kept.clear();
18473
+ this.#clearUsageOwnership();
18143
18474
  }
18144
18475
  }
18145
18476
  /** Discard bearer material when a route is removed, declined or rebound. */
18146
18477
  forget(credentialId) {
18147
18478
  this.#kept.delete(credentialId);
18479
+ this.#usageServed.delete(credentialId);
18480
+ this.#usage.forget(credentialId);
18481
+ }
18482
+ #clearUsageOwnership() {
18483
+ for (const id of this.#usageServed.keys())
18484
+ this.#usage.forget(id);
18485
+ this.#usageServed.clear();
18148
18486
  }
18149
18487
  /** Apply an already-held roster; this never fetches credentials or writes it. */
18150
18488
  retain(identities) {
@@ -18154,6 +18492,11 @@ var init_custody = __esm({
18154
18492
  if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== kept.attempt.credentialType || identity3.accountIdentity !== kept.attempt.expectedAccountIdentity)
18155
18493
  this.forget(id);
18156
18494
  }
18495
+ for (const [id, served] of this.#usageServed) {
18496
+ const identity3 = current.get(id);
18497
+ if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== served.credentialType || identity3.accountIdentity !== served.accountIdentity)
18498
+ this.forget(id);
18499
+ }
18157
18500
  }
18158
18501
  /** A frozen, non-secret summary for a plugin's status display. */
18159
18502
  keptReceiptState() {
@@ -18185,6 +18528,7 @@ var init_custody = __esm({
18185
18528
  token = await this.#token(signal);
18186
18529
  } catch (error) {
18187
18530
  this.#kept.clear();
18531
+ this.#clearUsageOwnership();
18188
18532
  throw error;
18189
18533
  }
18190
18534
  if (this.#outage && kept) {
@@ -18194,6 +18538,7 @@ var init_custody = __esm({
18194
18538
  try {
18195
18539
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
18196
18540
  this.#kept.set(credentialId, { attempt, routeId, since: null });
18541
+ this.#usageServed.set(credentialId, { ...identity3 });
18197
18542
  return attempt;
18198
18543
  } catch (error) {
18199
18544
  this.#check(signal);
@@ -18378,6 +18723,23 @@ var init_custody = __esm({
18378
18723
  }
18379
18724
  };
18380
18725
  }
18726
+ /**
18727
+ * Queue reply quota metadata and return synchronously. Pass rate-limit
18728
+ * headers only, never tokens: the library does not filter header names.
18729
+ * Only credentials served by this custody and retained in its roster report.
18730
+ * Hosts managing their own roster must call retain() when that roster changes.
18731
+ */
18732
+ reportUsage(input) {
18733
+ if (this.#closed)
18734
+ return;
18735
+ try {
18736
+ this.#usage.report(input.credentialId, input.reading);
18737
+ } catch {
18738
+ }
18739
+ }
18740
+ usageReportState() {
18741
+ return this.#usage.state();
18742
+ }
18381
18743
  close() {
18382
18744
  if (this.#closed)
18383
18745
  return;
@@ -18389,12 +18751,23 @@ var init_custody = __esm({
18389
18751
  watch.stop();
18390
18752
  this.#watches.clear();
18391
18753
  this.#kept.clear();
18392
- this.#client.close();
18754
+ const usage = this.#usage.close();
18755
+ if (usage) {
18756
+ this.#tokenReads.add(usage);
18757
+ void usage.then(() => this.#tokenReads.delete(usage));
18758
+ } else
18759
+ this.#client.close();
18760
+ this.#disposing = drainShutdown(this.#tokenReads, (count3) => (this.#onDrainTimeout ?? this.#warnShutdown)(count3)).finally(() => {
18761
+ this.#usage.drop();
18762
+ this.#usageServed.clear();
18763
+ if (usage)
18764
+ this.#client.close();
18765
+ });
18393
18766
  }
18394
- /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
18767
+ /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
18395
18768
  async dispose(onTimeout = this.#warnShutdown) {
18769
+ this.#onDrainTimeout = onTimeout;
18396
18770
  this.close();
18397
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
18398
18771
  await this.#disposing;
18399
18772
  }
18400
18773
  };
@@ -18635,6 +19008,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
18635
19008
  return {
18636
19009
  version: 1,
18637
19010
  view: inventory.view,
19011
+ ...previous?.limits !== void 0 && { limits: previous.limits },
18638
19012
  complete,
18639
19013
  ...!complete && {
18640
19014
  rejected: inventory.skipped.map((record3) => ({
@@ -18705,6 +19079,7 @@ function decodeRoster(value) {
18705
19079
  // that was used whole, so it reads as complete.
18706
19080
  complete: value.complete !== false,
18707
19081
  ...rejected && { rejected },
19082
+ ...value.limits !== void 0 && { limits: value.limits },
18708
19083
  rows,
18709
19084
  declined
18710
19085
  };
@@ -19916,6 +20291,33 @@ var init_consumer = __esm({
19916
20291
  combined.dispose();
19917
20292
  }
19918
20293
  }
20294
+ /**
20295
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
20296
+ * headers only, never tokens: the library does not filter header names.
20297
+ * The credential must have been served by this host and still belong to the route.
20298
+ */
20299
+ reportUsage(input) {
20300
+ if (this.#shutdown.signal.aborted)
20301
+ return;
20302
+ try {
20303
+ const row = this.#roster?.rows.find((row2) => row2.routeId === input.routeId);
20304
+ if (!row?.enabled || row.state !== "active" || row.credentialId !== input.credentialId && !row.aliases?.includes(input.credentialId))
20305
+ return;
20306
+ if (this.#hub) {
20307
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
20308
+ this.#lease.custody.reportUsage(input);
20309
+ } else
20310
+ this.#custody?.reportUsage(input);
20311
+ } catch {
20312
+ }
20313
+ }
20314
+ usageReportState() {
20315
+ try {
20316
+ return (this.#hub ? this.#lease?.custody : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 };
20317
+ } catch {
20318
+ return { pending: 0, inFlight: false, dropped: 0 };
20319
+ }
20320
+ }
19919
20321
  async reportFailure(attempt, status, source) {
19920
20322
  this.#assertOpen();
19921
20323
  if (this.#hub) {
@@ -20527,6 +20929,14 @@ var init_hub = __esm({
20527
20929
  check();
20528
20930
  return custody.reportFailure(attempt, status, source);
20529
20931
  },
20932
+ reportUsage: (input) => {
20933
+ if (!state.released && !generation.ended)
20934
+ custody.reportUsage(input);
20935
+ },
20936
+ usageReportState: () => {
20937
+ check();
20938
+ return custody.usageReportState();
20939
+ },
20530
20940
  forget: (credentialId) => {
20531
20941
  check();
20532
20942
  custody.forget(credentialId);
@@ -21070,7 +21480,7 @@ __export(claustrum_exports, {
21070
21480
  ChangeNoticeReader: () => ChangeNoticeReader,
21071
21481
  ClaustrumConsumer: () => ClaustrumConsumer,
21072
21482
  ClaustrumConsumerError: () => ClaustrumConsumerError,
21073
- ClaustrumCredentialError: () => ClaustrumCredentialError4,
21483
+ ClaustrumCredentialError: () => ClaustrumCredentialError5,
21074
21484
  ClaustrumDiscoveryHub: () => ClaustrumDiscoveryHub,
21075
21485
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
21076
21486
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
@@ -21127,7 +21537,7 @@ __export(claustrum_exports, {
21127
21537
  vaultRoutingRows: () => vaultRoutingRows
21128
21538
  });
21129
21539
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
21130
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
21540
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
21131
21541
  async function connectClaustrumScopedClient(options) {
21132
21542
  const { connectTimeoutMs, ...client } = options;
21133
21543
  const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
@@ -22907,6 +23317,9 @@ function loadBackend2() {
22907
23317
  });
22908
23318
  return backend2;
22909
23319
  }
23320
+ function isWindowsSharingViolation2(error) {
23321
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
23322
+ }
22910
23323
  async function privateOperation2(path2, stage, operation) {
22911
23324
  try {
22912
23325
  return await operation();
@@ -25162,7 +25575,8 @@ async function removeOldCopies(location, files, present2, layoutLock, input) {
25162
25575
  if (!await unlinkIfIdentical(
25163
25576
  file,
25164
25577
  location.stateHomeDir,
25165
- () => beforeRemove(file.old, layoutLock, input.steps)
25578
+ () => beforeRemove(file.old, layoutLock, input.steps),
25579
+ input.steps?.oldFileIO
25166
25580
  ))
25167
25581
  kept.push(file.old);
25168
25582
  }
@@ -25184,21 +25598,21 @@ async function sameBytes(a, b) {
25184
25598
  return false;
25185
25599
  }
25186
25600
  }
25187
- function isWindowsSharingError(error) {
25601
+ function isWindowsSharingError(error, platform) {
25188
25602
  const code2 = error?.code;
25189
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
25603
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
25190
25604
  }
25191
- async function unlinkIfIdentical(file, stateDir, guard) {
25605
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile10, unlink: unlink10 }) {
25192
25606
  const started = performance.now();
25193
25607
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
25194
25608
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
25195
25609
  let same;
25196
25610
  try {
25197
- same = (await readFile10(file.old)).equals(await readFile10(file.next));
25611
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
25198
25612
  } catch (error) {
25199
25613
  if (error.code === "ENOENT" && !await exists2(file.old))
25200
25614
  return true;
25201
- if (isWindowsSharingError(error)) {
25615
+ if (isWindowsSharingError(error, io.platform)) {
25202
25616
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
25203
25617
  continue;
25204
25618
  }
@@ -25207,11 +25621,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
25207
25621
  if (!same) throw credentialConflict(stateDir, file);
25208
25622
  await guard();
25209
25623
  try {
25210
- await unlink10(file.old);
25624
+ await io.unlink(file.old);
25211
25625
  return true;
25212
25626
  } catch (error) {
25213
25627
  if (error.code === "ENOENT") return true;
25214
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
25628
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
25215
25629
  return false;
25216
25630
  }
25217
25631
  }
@@ -27775,7 +28189,7 @@ import { createHash as createHash12, randomBytes as randomBytes3, randomUUID as
27775
28189
  import { constants as fsConstants2 } from "node:fs";
27776
28190
  import { chmod as chmod5, mkdir as mkdir14, open as open10, readFile as readFile12, realpath as realpath4, rename as rename12, stat as stat11, unlink as unlink11 } from "node:fs/promises";
27777
28191
  import { basename as basename5, dirname as dirname19, extname as extname2, isAbsolute as isAbsolute4, join as join18, resolve as resolve19 } from "node:path";
27778
- import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
28192
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
27779
28193
 
27780
28194
  // src/common-auth-embedded/fs/file-read-cache.js
27781
28195
  import { lstat as lstat7 } from "node:fs/promises";
@@ -28150,37 +28564,83 @@ async function acquireRefreshFileLockWithClock2(options) {
28150
28564
  await rm6(path2, { recursive: true, force: true }).catch(() => {
28151
28565
  });
28152
28566
  }
28153
- async function releaseEvictionMarker() {
28154
- if (await ownsEvictionMarker()) {
28155
- await removeLeaseObject(evictPath);
28156
- }
28567
+ function isRetryableRemoval(error, path2) {
28568
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path2)
28569
+ return false;
28570
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
28157
28571
  }
28158
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
28572
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
28573
+ let original;
28574
+ let delayMs = 5;
28575
+ while (await stillOwned()) {
28576
+ try {
28577
+ await removeLeaseObject(path2);
28578
+ return;
28579
+ } catch (error) {
28580
+ if (!isRetryableRemoval(error, path2))
28581
+ throw error;
28582
+ original ??= error;
28583
+ }
28584
+ const remainingMs = deadline - performance.now();
28585
+ if (remainingMs <= 0)
28586
+ throw original;
28587
+ await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
28588
+ if (performance.now() >= deadline)
28589
+ throw original;
28590
+ delayMs = Math.min(delayMs * 2, 50);
28591
+ }
28592
+ }
28593
+ async function releaseEvictionMarker(deadline) {
28594
+ let ownedDirectory;
28595
+ await removeOwnedLeaseObject(evictPath, async () => {
28596
+ if (!windowsPrivateFiles2)
28597
+ return ownsEvictionMarker();
28598
+ const current = await lstat8(evictPath).catch((error) => {
28599
+ if (error.code !== "ENOENT")
28600
+ throw error;
28601
+ return void 0;
28602
+ });
28603
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
28604
+ return false;
28605
+ if (await ownsEvictionMarker()) {
28606
+ ownedDirectory = current;
28607
+ return true;
28608
+ }
28609
+ if (!ownedDirectory)
28610
+ return false;
28611
+ try {
28612
+ await stat10(evictOwnerPath);
28613
+ return false;
28614
+ } catch (error) {
28615
+ if (error.code !== "ENOENT")
28616
+ throw error;
28617
+ return true;
28618
+ }
28619
+ }, deadline);
28620
+ }
28621
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
28159
28622
  if (!created)
28160
28623
  return false;
28161
- let current;
28624
+ let stillOurs = false;
28162
28625
  try {
28163
- const st = await lstat8(evictPath);
28164
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
28165
- } catch {
28166
- return false;
28167
- }
28168
- if (!sameMarkerDirectory2(created, current))
28169
- return false;
28170
- try {
28171
- await stat10(evictOwnerPath);
28172
- return true;
28173
- } catch (error) {
28174
- if (error.code !== "ENOENT")
28175
- return true;
28176
- }
28177
- try {
28178
- await removeLeaseObject(evictPath);
28626
+ await removeOwnedLeaseObject(evictPath, async () => {
28627
+ stillOurs = false;
28628
+ const st = await lstat8(evictPath).catch(() => void 0);
28629
+ if (!st || !sameMarkerDirectory2(created, st))
28630
+ return false;
28631
+ stillOurs = true;
28632
+ try {
28633
+ await stat10(evictOwnerPath);
28634
+ return false;
28635
+ } catch (error) {
28636
+ return error.code === "ENOENT";
28637
+ }
28638
+ }, deadline);
28179
28639
  } catch {
28180
28640
  }
28181
- return true;
28641
+ return stillOurs;
28182
28642
  }
28183
- async function tryAcquireEvictionMarker() {
28643
+ async function tryAcquireEvictionMarker(deadline) {
28184
28644
  if (windowsPrivateFiles2)
28185
28645
  await createPrivateDirectoryExclusive2(evictPath);
28186
28646
  else
@@ -28204,11 +28664,11 @@ async function acquireRefreshFileLockWithClock2(options) {
28204
28664
  else
28205
28665
  await createExclusiveText2(evictOwnerPath, bytes);
28206
28666
  } catch (error) {
28207
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
28667
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
28208
28668
  if (isLostMarkerRaceError2(error) && !stillOurs)
28209
28669
  return false;
28210
28670
  try {
28211
- await releaseEvictionMarker();
28671
+ await releaseEvictionMarker(deadline);
28212
28672
  } catch {
28213
28673
  }
28214
28674
  throw error;
@@ -28217,7 +28677,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28217
28677
  await options.onStep("eviction-marker-acquired");
28218
28678
  return true;
28219
28679
  }
28220
- async function recoverStaleEvictionMarker() {
28680
+ async function recoverStaleEvictionMarker(deadline) {
28221
28681
  let evictStat;
28222
28682
  try {
28223
28683
  evictStat = await stat10(evictPath);
@@ -28262,12 +28722,22 @@ async function acquireRefreshFileLockWithClock2(options) {
28262
28722
  }
28263
28723
  if (options.onStep)
28264
28724
  await options.onStep("stale-marker-claimed");
28265
- await removeLeaseObject(claimedPath);
28725
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
28726
+ await removeOwnedLeaseObject(claimedPath, async () => {
28727
+ if (!claimedIdentity)
28728
+ return true;
28729
+ const current = await lstat8(claimedPath).catch((error) => {
28730
+ if (error.code !== "ENOENT")
28731
+ throw error;
28732
+ return void 0;
28733
+ });
28734
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
28735
+ }, deadline);
28266
28736
  return "recovered";
28267
28737
  }
28268
- async function withEvictionMarker(action) {
28738
+ async function withEvictionMarker(action, deadline) {
28269
28739
  try {
28270
- if (!await tryAcquireEvictionMarker())
28740
+ if (!await tryAcquireEvictionMarker(deadline))
28271
28741
  return false;
28272
28742
  } catch (error) {
28273
28743
  if (error.code === "EEXIST") {
@@ -28284,11 +28754,23 @@ async function acquireRefreshFileLockWithClock2(options) {
28284
28754
  }
28285
28755
  throw error;
28286
28756
  }
28757
+ let actionFailed = false;
28758
+ let actionError;
28287
28759
  try {
28288
28760
  await action();
28289
- } finally {
28290
- await releaseEvictionMarker();
28761
+ } catch (error) {
28762
+ actionFailed = true;
28763
+ actionError = error;
28291
28764
  }
28765
+ try {
28766
+ await releaseEvictionMarker(deadline);
28767
+ } catch (error) {
28768
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
28769
+ throw actionError;
28770
+ throw error;
28771
+ }
28772
+ if (actionFailed)
28773
+ throw actionError;
28292
28774
  return true;
28293
28775
  }
28294
28776
  async function relinquishLockAfterMarkerLoss() {
@@ -28525,6 +29007,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28525
29007
  await renewalInFlight;
28526
29008
  const deadline = performance.now() + EVICT_TTL + 1e3;
28527
29009
  let delayMs = 5;
29010
+ let removalError;
28528
29011
  for (; ; ) {
28529
29012
  try {
28530
29013
  let removalConfirmed = false;
@@ -28549,7 +29032,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28549
29032
  return;
28550
29033
  await removeLeaseObject(lockPath);
28551
29034
  removalConfirmed = true;
28552
- });
29035
+ }, deadline);
28553
29036
  if (markerAcquired) {
28554
29037
  if (windowsPrivateFiles2 && !removalConfirmed)
28555
29038
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -28560,20 +29043,25 @@ async function acquireRefreshFileLockWithClock2(options) {
28560
29043
  }
28561
29044
  if (signal?.aborted)
28562
29045
  return;
28563
- await recoverStaleEvictionMarker();
29046
+ await recoverStaleEvictionMarker(deadline);
28564
29047
  } catch (error) {
28565
- if (windowsPrivateFiles2)
28566
- throw error;
28567
- return;
29048
+ if (!isRetryableRemoval(error, lockPath)) {
29049
+ if (windowsPrivateFiles2)
29050
+ throw error;
29051
+ return;
29052
+ }
29053
+ removalError ??= error;
28568
29054
  }
28569
29055
  const remainingMs = deadline - performance.now();
28570
29056
  if (remainingMs <= 0)
28571
29057
  break;
28572
29058
  await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
29059
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
29060
+ break;
28573
29061
  delayMs = Math.min(delayMs * 2, 50);
28574
29062
  }
28575
29063
  if (windowsPrivateFiles2)
28576
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
29064
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
28577
29065
  code: "ETIMEDOUT"
28578
29066
  });
28579
29067
  }
@@ -28616,7 +29104,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
28616
29104
  "pending_queue_full"
28617
29105
  ]);
28618
29106
  function classifyEnrollmentError2(error) {
28619
- if (!(error instanceof ClaustrumCredentialError5))
29107
+ if (!(error instanceof ClaustrumCredentialError6))
28620
29108
  return void 0;
28621
29109
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
28622
29110
  return { code: error.code, disposition: "terminal" };
@@ -30766,7 +31254,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30766
31254
  }
30767
31255
  };
30768
31256
  let openCodeLogin;
30769
- let hasLocalPool = false;
31257
+ const nativeNextStep = (label) => {
31258
+ deps.stdout.write(
31259
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
31260
+ Setup has not completed the OpenCode 2 native Google connection.
31261
+ `
31262
+ );
31263
+ };
30770
31264
  const manifest = JSON.parse(
30771
31265
  await readFile13(new URL("../package.json", import.meta.url), "utf8")
30772
31266
  );
@@ -30824,18 +31318,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30824
31318
  await assertLocal(host, context);
30825
31319
  if (host === "opencode" && context.opencodeGeneration === "2") {
30826
31320
  if (!forceLogin) {
30827
- try {
30828
- const source2 = await deps.accountStore.read(
30829
- deps.accountStore.legacyPath()
30830
- );
30831
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
30832
- if (candidateAccounts.some(
30833
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
30834
- )) {
30835
- hasLocalPool = true;
30836
- }
30837
- } catch {
30838
- }
31321
+ const source2 = await deps.accountStore.read(
31322
+ deps.accountStore.legacyPath()
31323
+ );
31324
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
30839
31325
  }
30840
31326
  return;
30841
31327
  }
@@ -30850,11 +31336,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30850
31336
  `Using existing local Antigravity login for ${host}.
30851
31337
  `
30852
31338
  );
30853
- if (host === "opencode" && accounts.some(
30854
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
30855
- )) {
30856
- hasLocalPool = true;
30857
- }
30858
31339
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
30859
31340
  const account = accounts[0];
30860
31341
  await writeNativeSlot(
@@ -30887,18 +31368,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30887
31368
  );
30888
31369
  if (host === "opencode") {
30889
31370
  openCodeLogin = result;
30890
- hasLocalPool = true;
30891
31371
  }
30892
31372
  },
30893
31373
  beforeRegister: async (host, mode, context) => {
30894
31374
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
30895
- const nativeNextStep = (label) => {
30896
- deps.stdout.write(
30897
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
30898
- Setup has not completed the OpenCode 2 native Google connection.
30899
- `
30900
- );
30901
- };
30902
31375
  if (mode === "local") {
30903
31376
  await assertLocal(host, context);
30904
31377
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -30912,10 +31385,6 @@ Setup has not completed the OpenCode 2 native Google connection.
30912
31385
  },
30913
31386
  context
30914
31387
  );
30915
- if (needsOpenCode2)
30916
- nativeNextStep(
30917
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
30918
- );
30919
31388
  return;
30920
31389
  }
30921
31390
  if (await authority(host) !== "vault")
@@ -30986,11 +31455,28 @@ Setup has not completed the OpenCode 2 native Google connection.
30986
31455
  await publishedGeneration(stateAnchor),
30987
31456
  stateAnchor
30988
31457
  );
30989
- return;
31458
+ } else {
31459
+ if (await migrateOpenCode() !== 0)
31460
+ throw new Error("Offline Antigravity account migration failed.");
31461
+ await deps.prepareVaultFolder?.();
31462
+ }
31463
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
31464
+ let reconnectReady = false;
31465
+ if (!forceLogin || context.opencodeGeneration !== "2") {
31466
+ if (source.kind === "store") {
31467
+ reconnectReady = source.reconnectReady;
31468
+ } else if (source.kind === "legacy") {
31469
+ const post = await deps.accountStore.read(
31470
+ deps.accountStore.legacyPath()
31471
+ );
31472
+ if (post.kind === "unavailable") throw new Error(post.reason);
31473
+ reconnectReady = post.kind === "store" && post.reconnectReady;
31474
+ }
31475
+ }
31476
+ nativeNextStep(
31477
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
31478
+ );
30990
31479
  }
30991
- if (await migrateOpenCode() !== 0)
30992
- throw new Error("Offline Antigravity account migration failed.");
30993
- await deps.prepareVaultFolder?.();
30994
31480
  } else {
30995
31481
  deps.stdout.write(
30996
31482
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -31582,6 +32068,7 @@ async function readAccountStore(legacyPath) {
31582
32068
  case "bound":
31583
32069
  break;
31584
32070
  }
32071
+ const generationId = admission.receipt.id;
31585
32072
  const repository = createAccountRepositoryFactory(modules)({
31586
32073
  paths: admission.paths,
31587
32074
  now: Date.now,
@@ -31595,6 +32082,12 @@ async function readAccountStore(legacyPath) {
31595
32082
  }
31596
32083
  });
31597
32084
  try {
32085
+ const servingBefore = await readAccountStoreAdmission(
32086
+ legacyPath,
32087
+ modules,
32088
+ Date.now,
32089
+ generationId
32090
+ );
31598
32091
  const read = await repository.read();
31599
32092
  if (read.status !== "ready") {
31600
32093
  return {
@@ -31602,7 +32095,20 @@ async function readAccountStore(legacyPath) {
31602
32095
  reason: `the account store is ${read.status}`
31603
32096
  };
31604
32097
  }
31605
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
32098
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
32099
+ legacyPath,
32100
+ modules,
32101
+ Date.now,
32102
+ generationId
32103
+ ) : servingBefore;
32104
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
32105
+ (row) => row.enabled && row.usable && row.credential !== void 0 && !row.torn && !row.unbound && row.invalid === void 0 && row.metadata.status === "present" && row.metadata.metadata.verificationRequired !== true && row.metadata.metadata.accountIneligible !== true
32106
+ );
32107
+ return {
32108
+ kind: "store",
32109
+ accounts: read.rows.map(cliAccountOf),
32110
+ reconnectReady
32111
+ };
31606
32112
  } finally {
31607
32113
  await repository.dispose();
31608
32114
  }