@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.31

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 (188) hide show
  1. package/dist/cli.js +783 -254
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +145 -77
  4. package/dist/index.js +842 -297
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +177 -85
  7. package/dist/server.js +842 -300
  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 +4 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +34 -8
  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/file-read-cache.js +10 -5
  28. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  29. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  30. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  31. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  32. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  33. package/dist/src/common-auth-embedded/limits/axes.d.ts +69 -0
  34. package/dist/src/common-auth-embedded/limits/decide.d.ts +146 -0
  35. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  36. package/dist/src/common-auth-embedded/limits/families.d.ts +59 -0
  37. package/dist/src/common-auth-embedded/limits/marker.d.ts +69 -0
  38. package/dist/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  39. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  40. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  41. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  42. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  43. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  44. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  45. package/dist/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  46. package/dist/src/common-auth-embedded/opencode2/install.js +219 -27
  47. package/dist/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  48. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  49. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  50. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  51. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  52. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  53. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  54. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  55. package/dist/src/common-auth-embedded/setup/enroll.js +7 -1
  56. package/dist/src/common-auth-embedded/source-output.json +260 -124
  57. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  58. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  59. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  60. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  61. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  62. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  63. package/dist/src/common-auth-embedded/store/limits-namespace.js +46 -0
  64. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  65. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  66. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  67. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  68. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  69. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  70. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  71. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  72. package/dist/src/plugin/__fixtures__/release-model-ids.js +0 -1
  73. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  74. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  75. package/dist/src/plugin/account-access.js +1 -1
  76. package/dist/src/plugin/request.d.ts.map +1 -1
  77. package/dist/src/plugin/request.js +3 -2
  78. package/dist/src/plugin/request.js.map +1 -1
  79. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  80. package/dist/src/plugin/shared/request-services.js +1 -1
  81. package/dist/src/runtime-layout.d.ts +9 -2
  82. package/dist/src/runtime-layout.d.ts.map +1 -1
  83. package/dist/src/runtime-layout.js +8 -8
  84. package/dist/src/runtime-layout.js.map +1 -1
  85. package/dist/src/setup.d.ts.map +1 -1
  86. package/dist/src/setup.js +29 -40
  87. package/dist/src/setup.js.map +1 -1
  88. package/dist/tui-build-map.json +9 -9
  89. package/dist/tui-ga-build-map.json +1 -1
  90. package/dist/types/src/cli.d.ts +1 -0
  91. package/dist/types/src/cli.d.ts.map +1 -1
  92. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  93. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  94. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  95. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  96. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  97. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  98. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  99. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  100. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +69 -0
  101. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +146 -0
  102. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  103. package/dist/types/src/common-auth-embedded/limits/families.d.ts +59 -0
  104. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +69 -0
  105. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  106. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  107. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  108. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  109. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  110. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  111. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  112. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  113. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  114. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  115. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  116. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  117. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  118. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  119. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  120. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  121. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  122. package/dist/types/src/plugin/request.d.ts.map +1 -1
  123. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  124. package/dist/types/src/runtime-layout.d.ts +9 -2
  125. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  126. package/dist/types/src/setup.d.ts.map +1 -1
  127. package/package.json +3 -3
  128. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  129. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  130. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  131. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  132. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  133. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  134. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  135. package/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  136. package/src/common-auth-embedded/claustrum/roster.js +34 -8
  137. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  138. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  139. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  140. package/src/common-auth-embedded/commands/builtins.js +38 -0
  141. package/src/common-auth-embedded/fs/file-read-cache.js +10 -5
  142. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  143. package/src/common-auth-embedded/fs/private-files.js +7 -0
  144. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  145. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  146. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  147. package/src/common-auth-embedded/limits/axes.d.ts +69 -0
  148. package/src/common-auth-embedded/limits/decide.d.ts +146 -0
  149. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  150. package/src/common-auth-embedded/limits/families.d.ts +59 -0
  151. package/src/common-auth-embedded/limits/marker.d.ts +69 -0
  152. package/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  153. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  154. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  155. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  156. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  157. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  158. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  159. package/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  160. package/src/common-auth-embedded/opencode2/install.js +219 -27
  161. package/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  162. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  163. package/src/common-auth-embedded/routing/admission.js +17 -7
  164. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  165. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  166. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  167. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  168. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  169. package/src/common-auth-embedded/setup/enroll.js +7 -1
  170. package/src/common-auth-embedded/source-output.json +260 -124
  171. package/src/common-auth-embedded/store/attribution.js +3 -2
  172. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  173. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  174. package/src/common-auth-embedded/store/hooks.js +20 -5
  175. package/src/common-auth-embedded/store/index.d.ts +1 -0
  176. package/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  177. package/src/common-auth-embedded/store/limits-namespace.js +46 -0
  178. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  179. package/src/common-auth-embedded/store/pool.js +2 -0
  180. package/src/common-auth-embedded/store/provider-state.js +5 -5
  181. package/src/common-auth-embedded/store/refresh.js +1 -1
  182. package/src/common-auth-embedded/store/schema.js +9 -4
  183. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  184. package/src/common-auth-embedded/store/settings.js +11 -4
  185. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  186. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  187. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  188. 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();
@@ -1626,10 +1629,10 @@ async function privateDirectory(path2) {
1626
1629
  if (errno(error) !== "EEXIST")
1627
1630
  throw error;
1628
1631
  }
1629
- const stat14 = await lstat2(path2);
1630
- if (!stat14.isDirectory() || stat14.isSymbolicLink())
1632
+ const stat16 = await lstat2(path2);
1633
+ if (!stat16.isDirectory() || stat16.isSymbolicLink())
1631
1634
  throw new AccountMigrationError("successor directory is not a regular directory");
1632
- privateMode(stat14.mode, 448);
1635
+ privateMode(stat16.mode, 448);
1633
1636
  if (windowsPrivateFiles)
1634
1637
  await verifySafeDirectory(path2);
1635
1638
  if (!sameFilesystemPath(await realpath(path2), path2))
@@ -5863,17 +5866,6 @@ var init_model_registry = __esm({
5863
5866
  high: { thinkingLevel: "high" }
5864
5867
  }
5865
5868
  }),
5866
- "antigravity-gemini-3.5-flash": defineModel("antigravity-gemini-3.5-flash", {
5867
- name: "Gemini 3.5 Flash (Antigravity)",
5868
- reasoning: true,
5869
- limit: { context: 1048576, output: 65536 },
5870
- modalities: DEFAULT_MODALITIES,
5871
- variants: {
5872
- low: { thinkingLevel: "low" },
5873
- medium: { thinkingLevel: "medium" },
5874
- high: { thinkingLevel: "high" }
5875
- }
5876
- }),
5877
5869
  "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
5878
5870
  name: "Gemini 3.1 Flash Image (Antigravity)",
5879
5871
  reasoning: false,
@@ -5929,7 +5921,6 @@ var init_model_registry = __esm({
5929
5921
  "gemini-3-flash-low": "gemini-3-flash",
5930
5922
  "gemini-3-flash-medium": "gemini-3-flash",
5931
5923
  "gemini-3-flash-high": "gemini-3-flash",
5932
- "gemini-3.5-flash-low": "gemini-3.5-flash",
5933
5924
  "gemini-3.5-flash-medium": "gemini-3.5-flash",
5934
5925
  "gemini-3.5-flash-high": "gemini-3.5-flash",
5935
5926
  "gemini-3.6-flash-low": "gemini-3.6-flash",
@@ -5965,9 +5956,6 @@ var init_model_registry = __esm({
5965
5956
  "gemini-3.1-pro-low": "gemini",
5966
5957
  "gemini-3.1-pro-high": "gemini",
5967
5958
  "gemini-3-flash": "gemini",
5968
- "gemini-3-flash-agent": "gemini",
5969
- "gemini-3.5-flash-low": "gemini",
5970
- "gemini-3.5-flash-extra-low": "gemini",
5971
5959
  "gemini-3.6-flash-low": "gemini",
5972
5960
  "gemini-3.6-flash-medium": "gemini",
5973
5961
  "gemini-3.6-flash-high": "gemini",
@@ -5987,7 +5975,6 @@ var init_model_registry = __esm({
5987
5975
  ANTIGRAVITY_OPENCODE_MODEL_IDS = [
5988
5976
  "antigravity-gemini-4-argon",
5989
5977
  "antigravity-gemini-3.8-flash",
5990
- "antigravity-gemini-3.5-flash",
5991
5978
  "antigravity-gemini-3.1-flash-image",
5992
5979
  "antigravity-claude-sonnet-5-5",
5993
5980
  "antigravity-claude-opus-5-5",
@@ -8566,6 +8553,48 @@ var init_identity = __esm({
8566
8553
  }
8567
8554
  });
8568
8555
 
8556
+ // ../core/dist/common-auth-embedded/store/hooks.js
8557
+ import { AsyncLocalStorage } from "node:async_hooks";
8558
+ function assertNotInsideHook(operation) {
8559
+ if (insideHook.getStore() !== void 0)
8560
+ throw new PoolReentryError(operation);
8561
+ }
8562
+ function assertLimitsWriteAllowed() {
8563
+ if (insideHook.getStore()?.storeLocksReleased === false || insideCodec.getStore())
8564
+ throw new PoolReentryError("updateLimitsNamespace");
8565
+ }
8566
+ function runInsideCodec(fn) {
8567
+ return insideCodec.run(true, fn);
8568
+ }
8569
+ function runInsideHook(operation, fn, storeLocksReleased = false) {
8570
+ return insideHook.run({
8571
+ operation,
8572
+ storeLocksReleased: storeLocksReleased && insideHook.getStore()?.storeLocksReleased !== false
8573
+ }, async () => await fn());
8574
+ }
8575
+ async function callFailureHook(operation, hook, rowId2, error, logger2) {
8576
+ if (!hook)
8577
+ return;
8578
+ try {
8579
+ await runInsideHook(operation, () => hook(rowId2, error), true);
8580
+ } catch (hookError) {
8581
+ logger2?.warn("store failure hook threw; the original failure stands", {
8582
+ operation,
8583
+ rowId: rowId2,
8584
+ error: hookError instanceof Error ? hookError.message : String(hookError)
8585
+ });
8586
+ }
8587
+ }
8588
+ var insideHook, insideCodec;
8589
+ var init_hooks = __esm({
8590
+ "../core/dist/common-auth-embedded/store/hooks.js"() {
8591
+ "use strict";
8592
+ init_errors();
8593
+ insideHook = new AsyncLocalStorage();
8594
+ insideCodec = new AsyncLocalStorage();
8595
+ }
8596
+ });
8597
+
8569
8598
  // ../core/dist/common-auth-embedded/fs/atomic-write.js
8570
8599
  import { randomUUID as randomUUID6 } from "node:crypto";
8571
8600
  import { mkdir as mkdir6, open as open3, rename as rename5, rm as rm3 } from "node:fs/promises";
@@ -8947,37 +8976,83 @@ async function acquireRefreshFileLockWithClock(options) {
8947
8976
  await rm4(path2, { recursive: true, force: true }).catch(() => {
8948
8977
  });
8949
8978
  }
8950
- async function releaseEvictionMarker() {
8951
- if (await ownsEvictionMarker()) {
8952
- await removeLeaseObject(evictPath);
8953
- }
8979
+ function isRetryableRemoval(error, path2) {
8980
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path2)
8981
+ return false;
8982
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
8954
8983
  }
8955
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
8984
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
8985
+ let original;
8986
+ let delayMs = 5;
8987
+ while (await stillOwned()) {
8988
+ try {
8989
+ await removeLeaseObject(path2);
8990
+ return;
8991
+ } catch (error) {
8992
+ if (!isRetryableRemoval(error, path2))
8993
+ throw error;
8994
+ original ??= error;
8995
+ }
8996
+ const remainingMs = deadline - performance.now();
8997
+ if (remainingMs <= 0)
8998
+ throw original;
8999
+ await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9000
+ if (performance.now() >= deadline)
9001
+ throw original;
9002
+ delayMs = Math.min(delayMs * 2, 50);
9003
+ }
9004
+ }
9005
+ async function releaseEvictionMarker(deadline) {
9006
+ let ownedDirectory;
9007
+ await removeOwnedLeaseObject(evictPath, async () => {
9008
+ if (!windowsPrivateFiles)
9009
+ return ownsEvictionMarker();
9010
+ const current = await lstat3(evictPath).catch((error) => {
9011
+ if (error.code !== "ENOENT")
9012
+ throw error;
9013
+ return void 0;
9014
+ });
9015
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
9016
+ return false;
9017
+ if (await ownsEvictionMarker()) {
9018
+ ownedDirectory = current;
9019
+ return true;
9020
+ }
9021
+ if (!ownedDirectory)
9022
+ return false;
9023
+ try {
9024
+ await stat3(evictOwnerPath);
9025
+ return false;
9026
+ } catch (error) {
9027
+ if (error.code !== "ENOENT")
9028
+ throw error;
9029
+ return true;
9030
+ }
9031
+ }, deadline);
9032
+ }
9033
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
8956
9034
  if (!created)
8957
9035
  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;
9036
+ let stillOurs = false;
8967
9037
  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);
9038
+ await removeOwnedLeaseObject(evictPath, async () => {
9039
+ stillOurs = false;
9040
+ const st = await lstat3(evictPath).catch(() => void 0);
9041
+ if (!st || !sameMarkerDirectory(created, st))
9042
+ return false;
9043
+ stillOurs = true;
9044
+ try {
9045
+ await stat3(evictOwnerPath);
9046
+ return false;
9047
+ } catch (error) {
9048
+ return error.code === "ENOENT";
9049
+ }
9050
+ }, deadline);
8976
9051
  } catch {
8977
9052
  }
8978
- return true;
9053
+ return stillOurs;
8979
9054
  }
8980
- async function tryAcquireEvictionMarker() {
9055
+ async function tryAcquireEvictionMarker(deadline) {
8981
9056
  if (windowsPrivateFiles)
8982
9057
  await createPrivateDirectoryExclusive(evictPath);
8983
9058
  else
@@ -9001,11 +9076,11 @@ async function acquireRefreshFileLockWithClock(options) {
9001
9076
  else
9002
9077
  await createExclusiveText(evictOwnerPath, bytes);
9003
9078
  } catch (error) {
9004
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
9079
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
9005
9080
  if (isLostMarkerRaceError(error) && !stillOurs)
9006
9081
  return false;
9007
9082
  try {
9008
- await releaseEvictionMarker();
9083
+ await releaseEvictionMarker(deadline);
9009
9084
  } catch {
9010
9085
  }
9011
9086
  throw error;
@@ -9014,7 +9089,7 @@ async function acquireRefreshFileLockWithClock(options) {
9014
9089
  await options.onStep("eviction-marker-acquired");
9015
9090
  return true;
9016
9091
  }
9017
- async function recoverStaleEvictionMarker() {
9092
+ async function recoverStaleEvictionMarker(deadline) {
9018
9093
  let evictStat;
9019
9094
  try {
9020
9095
  evictStat = await stat3(evictPath);
@@ -9059,12 +9134,22 @@ async function acquireRefreshFileLockWithClock(options) {
9059
9134
  }
9060
9135
  if (options.onStep)
9061
9136
  await options.onStep("stale-marker-claimed");
9062
- await removeLeaseObject(claimedPath);
9137
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
9138
+ await removeOwnedLeaseObject(claimedPath, async () => {
9139
+ if (!claimedIdentity)
9140
+ return true;
9141
+ const current = await lstat3(claimedPath).catch((error) => {
9142
+ if (error.code !== "ENOENT")
9143
+ throw error;
9144
+ return void 0;
9145
+ });
9146
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
9147
+ }, deadline);
9063
9148
  return "recovered";
9064
9149
  }
9065
- async function withEvictionMarker(action) {
9150
+ async function withEvictionMarker(action, deadline) {
9066
9151
  try {
9067
- if (!await tryAcquireEvictionMarker())
9152
+ if (!await tryAcquireEvictionMarker(deadline))
9068
9153
  return false;
9069
9154
  } catch (error) {
9070
9155
  if (error.code === "EEXIST") {
@@ -9081,11 +9166,23 @@ async function acquireRefreshFileLockWithClock(options) {
9081
9166
  }
9082
9167
  throw error;
9083
9168
  }
9169
+ let actionFailed = false;
9170
+ let actionError;
9084
9171
  try {
9085
9172
  await action();
9086
- } finally {
9087
- await releaseEvictionMarker();
9173
+ } catch (error) {
9174
+ actionFailed = true;
9175
+ actionError = error;
9176
+ }
9177
+ try {
9178
+ await releaseEvictionMarker(deadline);
9179
+ } catch (error) {
9180
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
9181
+ throw actionError;
9182
+ throw error;
9088
9183
  }
9184
+ if (actionFailed)
9185
+ throw actionError;
9089
9186
  return true;
9090
9187
  }
9091
9188
  async function relinquishLockAfterMarkerLoss() {
@@ -9322,6 +9419,7 @@ async function acquireRefreshFileLockWithClock(options) {
9322
9419
  await renewalInFlight;
9323
9420
  const deadline = performance.now() + EVICT_TTL + 1e3;
9324
9421
  let delayMs = 5;
9422
+ let removalError;
9325
9423
  for (; ; ) {
9326
9424
  try {
9327
9425
  let removalConfirmed = false;
@@ -9346,7 +9444,7 @@ async function acquireRefreshFileLockWithClock(options) {
9346
9444
  return;
9347
9445
  await removeLeaseObject(lockPath);
9348
9446
  removalConfirmed = true;
9349
- });
9447
+ }, deadline);
9350
9448
  if (markerAcquired) {
9351
9449
  if (windowsPrivateFiles && !removalConfirmed)
9352
9450
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -9357,20 +9455,25 @@ async function acquireRefreshFileLockWithClock(options) {
9357
9455
  }
9358
9456
  if (signal?.aborted)
9359
9457
  return;
9360
- await recoverStaleEvictionMarker();
9458
+ await recoverStaleEvictionMarker(deadline);
9361
9459
  } catch (error) {
9362
- if (windowsPrivateFiles)
9363
- throw error;
9364
- return;
9460
+ if (!isRetryableRemoval(error, lockPath)) {
9461
+ if (windowsPrivateFiles)
9462
+ throw error;
9463
+ return;
9464
+ }
9465
+ removalError ??= error;
9365
9466
  }
9366
9467
  const remainingMs = deadline - performance.now();
9367
9468
  if (remainingMs <= 0)
9368
9469
  break;
9369
9470
  await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9471
+ if (windowsPrivateFiles && performance.now() >= deadline)
9472
+ break;
9370
9473
  delayMs = Math.min(delayMs * 2, 50);
9371
9474
  }
9372
9475
  if (windowsPrivateFiles)
9373
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
9476
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9374
9477
  code: "ETIMEDOUT"
9375
9478
  });
9376
9479
  }
@@ -9394,7 +9497,7 @@ function lockPathFor(target, name) {
9394
9497
  return `${target}.${name}.lock`;
9395
9498
  }
9396
9499
  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")
9500
+ if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
9398
9501
  return false;
9399
9502
  const path2 = resolve3(lockPathFor(target, name));
9400
9503
  return error.path === path2 || error.path === join6(path2, "owner.json");
@@ -9466,37 +9569,6 @@ var init_with_lock = __esm({
9466
9569
  }
9467
9570
  });
9468
9571
 
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
9572
  // ../core/dist/common-auth-embedded/store/refresh-lock.js
9501
9573
  async function acquirePoolLock(spec, defaults, env3) {
9502
9574
  const emit = (type) => {
@@ -9728,7 +9800,7 @@ function stampFor(credential, credentialEpoch2, binding, options = {}) {
9728
9800
  };
9729
9801
  }
9730
9802
  function providerStateDigest(codec, value) {
9731
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
9803
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
9732
9804
  return createHash4("sha256").update(`provider-state\0${JSON.stringify(bound ?? null)}`).digest("hex");
9733
9805
  }
9734
9806
  function boundProviderStateDigest(account, credential, credentialEpoch2, identity3) {
@@ -9895,8 +9967,8 @@ function parseEntry(raw, codec) {
9895
9967
  return void 0;
9896
9968
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
9897
9969
  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))
9970
+ const quota = "quota" in raw && codec.decode ? runInsideCodec(() => codec.decode?.(raw.quota)) : raw.quota;
9971
+ if ("quota" in raw && !runInsideCodec(() => codec.validate(quota)))
9900
9972
  return void 0;
9901
9973
  if ("staged" in raw && !parseReservation(raw.staged))
9902
9974
  return void 0;
@@ -10068,7 +10140,7 @@ function providerStateFields(account, credential, credentialEpoch2, identity3, c
10068
10140
  if (digest3 === void 0)
10069
10141
  return { providerStateDropped: "uncovered" };
10070
10142
  const value = account[PROVIDER_STATE_KEY];
10071
- if (!codec?.validate(value))
10143
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
10072
10144
  return { providerStateDropped: "invalid" };
10073
10145
  if (providerStateDigest(codec, value) !== digest3)
10074
10146
  return { providerStateDropped: "uncovered" };
@@ -10145,6 +10217,7 @@ var POOL_KEY, POOL_SCHEMA_VERSION, POOL_ROWS_KEY, POOL_RETIRED_EPOCHS_KEY, LEGAC
10145
10217
  var init_schema = __esm({
10146
10218
  "../core/dist/common-auth-embedded/store/schema.js"() {
10147
10219
  "use strict";
10220
+ init_hooks();
10148
10221
  POOL_KEY = "commonAuthPool";
10149
10222
  POOL_SCHEMA_VERSION = 1;
10150
10223
  POOL_ROWS_KEY = "rows";
@@ -10845,8 +10918,8 @@ function assertQuotaRow(id, attribution, row) {
10845
10918
  });
10846
10919
  }
10847
10920
  function mergedQuota(ctx, id, stored, observation) {
10848
- const merged = ctx.codec.merge(stored, observation);
10849
- if (!ctx.codec.validate(merged))
10921
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
10922
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
10850
10923
  throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
10851
10924
  return merged;
10852
10925
  }
@@ -10886,6 +10959,7 @@ var init_attribution = __esm({
10886
10959
  "../core/dist/common-auth-embedded/store/attribution.js"() {
10887
10960
  "use strict";
10888
10961
  init_errors();
10962
+ init_hooks();
10889
10963
  init_mutate();
10890
10964
  init_refresh_lock();
10891
10965
  init_runtime();
@@ -10893,6 +10967,54 @@ var init_attribution = __esm({
10893
10967
  }
10894
10968
  });
10895
10969
 
10970
+ // ../core/dist/common-auth-embedded/store/limits-namespace.js
10971
+ async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
10972
+ assertLimitsWriteAllowed();
10973
+ const { ctx } = rt;
10974
+ await runOperation(ctx, "updateLimitsNamespace", void 0, void 0, async (locks, progress) => {
10975
+ for (const spec of ctx.storeLocks)
10976
+ await locks.acquire(spec);
10977
+ const result = await readPool(ctx);
10978
+ if (result.status !== "ready")
10979
+ throw notReadyError(result, "updateLimitsNamespace", void 0);
10980
+ const rows = result.rows.map(({ id, credentialEpoch: credentialEpoch2, identity: identity3 }) => ({
10981
+ id,
10982
+ credentialEpoch: credentialEpoch2,
10983
+ identity: identity3
10984
+ }));
10985
+ const envelope = await runInsideHook("updateLimitsNamespace", () => mutator(structuredClone(result.config.commonAuthLimits), rows));
10986
+ const config = { ...result.config, commonAuthLimits: envelope };
10987
+ const info = {
10988
+ operation: "updateLimitsNamespace",
10989
+ rowId: void 0
10990
+ };
10991
+ try {
10992
+ await writeJsonAtomic2(ctx.configPath, config, {
10993
+ beforeRename: async () => {
10994
+ await ctx.onStep?.("before-config-write", info);
10995
+ await locks.assertAll();
10996
+ options.beforePublish?.();
10997
+ }
10998
+ });
10999
+ } catch (error) {
11000
+ if (error && typeof error === "object" && "published" in error && error.published === true)
11001
+ options.onPublished?.();
11002
+ throw error;
11003
+ }
11004
+ progress.writes++;
11005
+ options.onPublished?.();
11006
+ await ctx.onStep?.("after-config-write", info);
11007
+ });
11008
+ }
11009
+ var init_limits_namespace = __esm({
11010
+ "../core/dist/common-auth-embedded/store/limits-namespace.js"() {
11011
+ "use strict";
11012
+ init_atomic_write2();
11013
+ init_hooks();
11014
+ init_mutate();
11015
+ }
11016
+ });
11017
+
10896
11018
  // ../core/dist/common-auth-embedded/store/provider-state.js
10897
11019
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
10898
11020
  if (!codec)
@@ -10906,7 +11028,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
10906
11028
  }
10907
11029
  if (normalized === void 0)
10908
11030
  throw refusal2(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
10909
- if (!codec.validate(normalized))
11031
+ if (!runInsideCodec(() => codec.validate(normalized)))
10910
11032
  throw refusal2(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
10911
11033
  return normalized;
10912
11034
  }
@@ -10915,18 +11037,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
10915
11037
  return { kind: "set", value: incoming };
10916
11038
  return {
10917
11039
  kind: "set",
10918
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), "the merged provider state")
11040
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), "the merged provider state")
10919
11041
  };
10920
11042
  }
10921
11043
  function replacementProviderState(codec, row, credentialEpoch2, identity3, incoming) {
10922
11044
  const hook = codec?.onReplace;
10923
- const next = hook ? hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
11045
+ const next = hook ? runInsideCodec(() => hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
10924
11046
  id: row.id,
10925
11047
  credentialEpoch: credentialEpoch2,
10926
11048
  ...row.identity !== void 0 ? { previousIdentity: row.identity } : {},
10927
11049
  ...identity3 !== void 0 ? { identity: identity3 } : {},
10928
11050
  ...incoming !== void 0 ? { incoming: structuredClone(incoming) } : {}
10929
- }) : incoming;
11051
+ })) : incoming;
10930
11052
  if (next === void 0)
10931
11053
  return { kind: "clear" };
10932
11054
  if (!hook)
@@ -13186,7 +13308,7 @@ async function refreshRow(rt, id, provider2, options = {}) {
13186
13308
  if (options.onPersisted) {
13187
13309
  try {
13188
13310
  const persisted = options.onPersisted;
13189
- await runInsideHook("refresh", () => persisted(id, commit.stored));
13311
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
13190
13312
  } catch (cause) {
13191
13313
  throw new PoolOperationError({
13192
13314
  operation: "refresh",
@@ -13225,11 +13347,11 @@ var init_refresh = __esm({
13225
13347
  });
13226
13348
 
13227
13349
  // ../core/dist/common-auth-embedded/fs/file-read-cache.js
13228
- import { lstat as lstat4 } from "node:fs/promises";
13350
+ import { lstat as lstat4, stat as stat4 } from "node:fs/promises";
13229
13351
  import { resolve as resolve5 } from "node:path";
13230
- async function identity(path2) {
13352
+ async function identity(path2, followSymlinks) {
13231
13353
  try {
13232
- const metadata = await lstat4(path2);
13354
+ const metadata = await (followSymlinks ? stat4(path2) : lstat4(path2));
13233
13355
  return metadata.isFile() ? metadata : void 0;
13234
13356
  } catch (error) {
13235
13357
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -13245,11 +13367,15 @@ var init_file_read_cache = __esm({
13245
13367
  "../core/dist/common-auth-embedded/fs/file-read-cache.js"() {
13246
13368
  "use strict";
13247
13369
  FileReadCache = class {
13370
+ #followSymlinks;
13248
13371
  #entries = /* @__PURE__ */ new Map();
13372
+ constructor(options = {}) {
13373
+ this.#followSymlinks = options.followSymlinks ?? false;
13374
+ }
13249
13375
  async read(paths, read, validateHit) {
13250
13376
  const resolvedPaths = paths.map((path2) => resolve5(path2));
13251
13377
  const key = JSON.stringify(resolvedPaths);
13252
- const probed = await Promise.all(resolvedPaths.map(identity));
13378
+ const probed = await Promise.all(resolvedPaths.map((path2) => identity(path2, this.#followSymlinks)));
13253
13379
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
13254
13380
  const cached = this.#entries.get(key);
13255
13381
  if (identities && cached && identities.every((entry, index) => {
@@ -13295,7 +13421,7 @@ function defineKey(target, key, value) {
13295
13421
  function composeConfig(config, next) {
13296
13422
  const out = {};
13297
13423
  for (const [key, value] of Object.entries(config)) {
13298
- if (POOL_OWNED_KEYS.includes(key))
13424
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
13299
13425
  defineKey(out, key, value);
13300
13426
  else if (Object.hasOwn(next, key))
13301
13427
  defineKey(out, key, next[key]);
@@ -13347,9 +13473,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
13347
13473
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
13348
13474
  if (owned.length > 0)
13349
13475
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
13350
- if (isDeepStrictEqual3(next, current))
13351
- return { settings: current, outcome: "unchanged" };
13476
+ if (Object.hasOwn(next, "commonAuthLimits") && (!Object.hasOwn(current, "commonAuthLimits") || !isDeepStrictEqual3(next.commonAuthLimits, current.commonAuthLimits)))
13477
+ throw settingsRefusal("settings cannot alter commonAuthLimits; use updateLimitsNamespace");
13352
13478
  const config = composeConfig(result.config, next);
13479
+ if (isDeepStrictEqual3(settingsOf2(config), current))
13480
+ return { settings: current, outcome: "unchanged" };
13353
13481
  const info = { operation: "updateSettings", rowId: void 0 };
13354
13482
  await writeJsonAtomic2(ctx.configPath, config, {
13355
13483
  beforeRename: async () => {
@@ -13484,6 +13612,7 @@ function openPoolStore(options) {
13484
13612
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
13485
13613
  readSettings: () => readPoolSettings(rt),
13486
13614
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
13615
+ updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
13487
13616
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
13488
13617
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
13489
13618
  recordQuota: record3,
@@ -13498,6 +13627,7 @@ var init_pool = __esm({
13498
13627
  "../core/dist/common-auth-embedded/store/pool.js"() {
13499
13628
  "use strict";
13500
13629
  init_attribution();
13630
+ init_limits_namespace();
13501
13631
  init_mutate();
13502
13632
  init_provider_state();
13503
13633
  init_publication();
@@ -13603,7 +13733,7 @@ function exclusionFor(id, inputs, now) {
13603
13733
  }
13604
13734
  return void 0;
13605
13735
  }
13606
- function judgeStageOne(id, projection, requiredLabels, now) {
13736
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
13607
13737
  if (projection.limits.length === 0) {
13608
13738
  return {
13609
13739
  id,
@@ -13627,7 +13757,7 @@ function judgeStageOne(id, projection, requiredLabels, now) {
13627
13757
  }
13628
13758
  const exhausted = projection.limits.filter(readsExhausted);
13629
13759
  for (const limit of exhausted) {
13630
- if (futureResetAt(limit, now) === void 0) {
13760
+ if (futureResetAt(limit, now) === void 0 && !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
13631
13761
  return {
13632
13762
  id,
13633
13763
  stage: 1,
@@ -13660,6 +13790,7 @@ function admit(input) {
13660
13790
  const excluded = [];
13661
13791
  const refused2 = [];
13662
13792
  const survivors = [];
13793
+ const needsPull = /* @__PURE__ */ new Set();
13663
13794
  for (const row of input.rows) {
13664
13795
  const exclusion = exclusionFor(row.id, input, input.now);
13665
13796
  if (exclusion) {
@@ -13671,7 +13802,10 @@ function admit(input) {
13671
13802
  continue;
13672
13803
  }
13673
13804
  const projection = projectQuota(row.quota, scope);
13674
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
13805
+ const lifted = input.liftedWindows?.get(row.id) ?? [];
13806
+ if (projection.limits.some((limit) => readsExhausted(limit) && futureResetAt(limit, input.now) === void 0 && lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
13807
+ needsPull.add(row.id);
13808
+ const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now, lifted);
13675
13809
  if (refusal3) {
13676
13810
  refused2.push(refusal3);
13677
13811
  continue;
@@ -13697,7 +13831,10 @@ function admit(input) {
13697
13831
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
13698
13832
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
13699
13833
  refused2.sort(byInput);
13700
- const pulls = refused2.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
13834
+ for (const refusal3 of refused2)
13835
+ if ("pullRequested" in refusal3)
13836
+ needsPull.add(refusal3.id);
13837
+ const pulls = input.rows.filter((row) => needsPull.has(row.id)).map((row) => row.id);
13701
13838
  for (const id of pulls)
13702
13839
  input.requestPull?.(id);
13703
13840
  return { admitted, refused: refused2, excluded, pulls };
@@ -14668,6 +14805,44 @@ function routingSection(options, snap) {
14668
14805
  return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
14669
14806
  }
14670
14807
  });
14808
+ if (options.routing?.sameAccountWait) {
14809
+ const waitLabel = "Longest wait on the same account";
14810
+ const waitChoices = [
14811
+ { value: "0", label: "Don't wait" },
14812
+ { value: "15", label: "15 minutes" },
14813
+ { value: "max", label: "Until the cache expires" }
14814
+ ];
14815
+ const rawWait = record(snap.settings.routing).maxSameAccountWait;
14816
+ const wait2 = String(rawWait === 0 || rawWait === "max" ? rawWait : 15);
14817
+ const waitName = (value) => waitChoices.find((choice) => choice.value === value)?.label ?? value;
14818
+ lines.push(`${waitLabel}: ${waitName(wait2)}`);
14819
+ actions.push({
14820
+ id: "maxSameAccountWait",
14821
+ label: waitLabel,
14822
+ group: ACTIONS_GROUP,
14823
+ knobs: [
14824
+ {
14825
+ kind: "choice",
14826
+ id: "maxSameAccountWait",
14827
+ label: waitLabel,
14828
+ choices: waitChoices,
14829
+ value: wait2
14830
+ }
14831
+ ],
14832
+ run: async ({ values }) => {
14833
+ const value = String(values.maxSameAccountWait);
14834
+ const maxSameAccountWait = value === "max" ? "max" : Number(value);
14835
+ await store.updateSettings((settings) => {
14836
+ settings.routing = {
14837
+ ...record(settings.routing),
14838
+ maxSameAccountWait
14839
+ };
14840
+ return void 0;
14841
+ }, locks);
14842
+ return `${waitLabel} set to ${waitName(value)}.`;
14843
+ }
14844
+ });
14845
+ }
14671
14846
  return {
14672
14847
  id: "routing",
14673
14848
  slot: "routing",
@@ -16948,7 +17123,7 @@ var init_any_signal = __esm({
16948
17123
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
16949
17124
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
16950
17125
  import { constants as fsConstants } from "node:fs";
16951
- import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat4, unlink as unlink6 } from "node:fs/promises";
17126
+ import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat5, unlink as unlink6 } from "node:fs/promises";
16952
17127
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve7 } from "node:path";
16953
17128
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
16954
17129
  function classifyEnrollmentError(error) {
@@ -17168,7 +17343,7 @@ async function refuseWritableAncestor(parent, options = {}) {
17168
17343
  }
17169
17344
  let privateGroup;
17170
17345
  for (; ; ) {
17171
- const metadata = await stat4(component).catch(() => void 0);
17346
+ const metadata = await stat5(component).catch(() => void 0);
17172
17347
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
17173
17348
  if (privateGroup === void 0) {
17174
17349
  privateGroup = gid !== void 0 && await isPrivateGroup(uid, gid, options);
@@ -17197,7 +17372,7 @@ async function ensureClaustrumPrivateDirectory(directory, options = {}, what = "
17197
17372
  return;
17198
17373
  }
17199
17374
  await mkdir8(directory, { recursive: true, mode: 448 });
17200
- const metadata = await stat4(directory);
17375
+ const metadata = await stat5(directory);
17201
17376
  const uid = process.geteuid?.();
17202
17377
  if (uid !== void 0 && metadata.uid !== uid) {
17203
17378
  throw new ClaustrumConsumerError("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -17732,9 +17907,144 @@ var init_shutdown = __esm({
17732
17907
  }
17733
17908
  });
17734
17909
 
17910
+ // ../core/dist/common-auth-embedded/claustrum/usage.js
17911
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
17912
+ function plain(value) {
17913
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
17914
+ }
17915
+ var ScopedUsageReporter;
17916
+ var init_usage = __esm({
17917
+ "../core/dist/common-auth-embedded/claustrum/usage.js"() {
17918
+ "use strict";
17919
+ ScopedUsageReporter = class {
17920
+ options;
17921
+ #queue = /* @__PURE__ */ new Map();
17922
+ #latest = /* @__PURE__ */ new Map();
17923
+ #errors = /* @__PURE__ */ new Set();
17924
+ #timer;
17925
+ #running;
17926
+ #closing = false;
17927
+ #stopped = false;
17928
+ #dropped = 0;
17929
+ constructor(options) {
17930
+ this.options = options;
17931
+ }
17932
+ state() {
17933
+ return {
17934
+ pending: this.#queue.size,
17935
+ inFlight: this.#running !== void 0,
17936
+ dropped: this.#dropped
17937
+ };
17938
+ }
17939
+ report(credentialId, reading) {
17940
+ if (this.#closing || !this.options.client.reportUsageScoped)
17941
+ return;
17942
+ try {
17943
+ if (!this.options.owns(credentialId)) {
17944
+ this.#dropped++;
17945
+ return;
17946
+ }
17947
+ if (!plain(reading) || "credentialId" in reading || "vouched" in reading)
17948
+ throw new Error("invalid reading");
17949
+ const json = JSON.stringify(reading);
17950
+ if (Buffer.byteLength(json, "utf8") > 15360)
17951
+ throw new Error("oversized reading");
17952
+ const copy = JSON.parse(json);
17953
+ if (!plain(copy) || "credentialId" in copy || "vouched" in copy || typeof copy.observedAtMs !== "number" || !Number.isFinite(copy.observedAtMs))
17954
+ throw new Error("invalid reading");
17955
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
17956
+ this.#dropped++;
17957
+ return;
17958
+ }
17959
+ if (this.#queue.has(credentialId))
17960
+ this.#dropped++;
17961
+ this.#latest.set(credentialId, copy.observedAtMs);
17962
+ this.#queue.set(credentialId, copy);
17963
+ if (!this.#timer && !this.#running) {
17964
+ this.#timer = this.options.setTimeout(() => {
17965
+ this.#timer = void 0;
17966
+ this.#flush();
17967
+ }, 1e3);
17968
+ this.#timer.unref?.();
17969
+ }
17970
+ } catch {
17971
+ this.#dropped++;
17972
+ }
17973
+ }
17974
+ forget(credentialId) {
17975
+ if (this.#queue.delete(credentialId))
17976
+ this.#dropped++;
17977
+ this.#latest.delete(credentialId);
17978
+ }
17979
+ #flush() {
17980
+ if (this.#running || !this.#queue.size || this.#stopped)
17981
+ return this.#running;
17982
+ const running = Promise.resolve().then(async () => {
17983
+ while (!this.#stopped && this.#queue.size) {
17984
+ const entry = this.#queue.entries().next().value;
17985
+ if (!entry)
17986
+ break;
17987
+ const [credentialId, reading] = entry;
17988
+ this.#queue.delete(credentialId);
17989
+ try {
17990
+ const enrollmentToken = await this.options.token();
17991
+ if (this.#stopped || !this.options.owns(credentialId)) {
17992
+ if (!this.#stopped)
17993
+ this.#dropped++;
17994
+ continue;
17995
+ }
17996
+ await this.options.client.reportUsageScoped?.({
17997
+ credentialId,
17998
+ reading,
17999
+ enrollmentToken
18000
+ });
18001
+ } catch (error) {
18002
+ if (!this.#stopped)
18003
+ this.#dropped++;
18004
+ this.#log(error);
18005
+ }
18006
+ }
18007
+ });
18008
+ this.#running = running;
18009
+ void running.finally(() => {
18010
+ this.#running = void 0;
18011
+ });
18012
+ return running;
18013
+ }
18014
+ #log(error) {
18015
+ let code2 = "transport_error";
18016
+ try {
18017
+ if (error instanceof ClaustrumCredentialError3)
18018
+ code2 = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code2;
18019
+ if (this.#errors.has(code2))
18020
+ return;
18021
+ this.#errors.add(code2);
18022
+ this.options.logger.debug("claustrum usage report dropped", { code: code2 });
18023
+ } catch {
18024
+ }
18025
+ }
18026
+ /** Start the final flush; the custody's existing shutdown drain bounds it. */
18027
+ close() {
18028
+ this.#closing = true;
18029
+ if (this.#timer)
18030
+ this.options.clearTimeout(this.#timer);
18031
+ this.#timer = void 0;
18032
+ return this.#flush();
18033
+ }
18034
+ drop() {
18035
+ this.#stopped = true;
18036
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
18037
+ this.#running = void 0;
18038
+ this.#queue.clear();
18039
+ this.#latest.clear();
18040
+ }
18041
+ };
18042
+ }
18043
+ });
18044
+
17735
18045
  // ../core/dist/common-auth-embedded/claustrum/custody.js
17736
18046
  import { channel } from "node:diagnostics_channel";
17737
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
18047
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
17738
18048
  function isScopedCredentialRotation(served, current) {
17739
18049
  return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
17740
18050
  }
@@ -17749,6 +18059,12 @@ function scopedRetryReason(served, current) {
17749
18059
  return "version-unchanged";
17750
18060
  return "rotated";
17751
18061
  }
18062
+ function checkedEnrollmentToken(value) {
18063
+ if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
18064
+ throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
18065
+ }
18066
+ return value.token;
18067
+ }
17752
18068
  function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
17753
18069
  const retry = isScopedCredentialRotation(served, current);
17754
18070
  logger2.debug("scoped 401 re-authorized", {
@@ -17857,6 +18173,7 @@ var init_custody = __esm({
17857
18173
  init_errors2();
17858
18174
  init_host_slot();
17859
18175
  init_shutdown();
18176
+ init_usage();
17860
18177
  init_watch();
17861
18178
  defaultLogger = createLogger2("claustrum");
17862
18179
  phaseDiagnostics = channel("common-auth.claustrum.phases");
@@ -17874,6 +18191,8 @@ var init_custody = __esm({
17874
18191
  #reports = /* @__PURE__ */ new WeakMap();
17875
18192
  #kept = /* @__PURE__ */ new Map();
17876
18193
  #keptAttempts = /* @__PURE__ */ new WeakMap();
18194
+ #usage;
18195
+ #usageServed = /* @__PURE__ */ new Map();
17877
18196
  #setTimeout;
17878
18197
  #clearTimeout;
17879
18198
  #outage = false;
@@ -17888,6 +18207,7 @@ var init_custody = __esm({
17888
18207
  #watches = /* @__PURE__ */ new Set();
17889
18208
  #tokenReads = /* @__PURE__ */ new Set();
17890
18209
  #warnShutdown;
18210
+ #onDrainTimeout;
17891
18211
  #disposing;
17892
18212
  constructor(options) {
17893
18213
  const tokenPath = options.tokenPath;
@@ -17907,13 +18227,21 @@ var init_custody = __esm({
17907
18227
  this.#warnShutdown = shutdownWarning(this.#logger);
17908
18228
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
17909
18229
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
18230
+ this.#usage = new ScopedUsageReporter({
18231
+ client: this.#client,
18232
+ owns: (id) => this.#usageServed.has(id),
18233
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
18234
+ logger: this.#logger,
18235
+ setTimeout: this.#setTimeout,
18236
+ clearTimeout: this.#clearTimeout
18237
+ });
17910
18238
  }
17911
18239
  /** A watch losing its transport is the same outage as an unreachable read. */
17912
18240
  transportLost(error) {
17913
18241
  if (this.#closed || this.#outage)
17914
18242
  return;
17915
18243
  this.#outage = true;
17916
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
18244
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError();
17917
18245
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
17918
18246
  this.#scheduleProbe();
17919
18247
  }
@@ -17982,10 +18310,7 @@ var init_custody = __esm({
17982
18310
  });
17983
18311
  }
17984
18312
  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;
18313
+ return checkedEnrollmentToken(value);
17989
18314
  }
17990
18315
  async #call(operation, signal) {
17991
18316
  this.#check(signal);
@@ -18009,7 +18334,7 @@ var init_custody = __esm({
18009
18334
  this.transportLost(error);
18010
18335
  else
18011
18336
  this.reachable();
18012
- if (error instanceof ClaustrumCredentialError3)
18337
+ if (error instanceof ClaustrumCredentialError4)
18013
18338
  throw error;
18014
18339
  if (classifyVaultFailure(error) === "unreachable")
18015
18340
  throw new ClaustrumUnreachableError();
@@ -18039,6 +18364,7 @@ var init_custody = __esm({
18039
18364
  token = await this.#token(signal);
18040
18365
  } catch (error) {
18041
18366
  this.#kept.clear();
18367
+ this.#clearUsageOwnership();
18042
18368
  throw error;
18043
18369
  }
18044
18370
  if (phaseDiagnostics.hasSubscribers)
@@ -18140,11 +18466,19 @@ var init_custody = __esm({
18140
18466
  else {
18141
18467
  this.reachable();
18142
18468
  this.#kept.clear();
18469
+ this.#clearUsageOwnership();
18143
18470
  }
18144
18471
  }
18145
18472
  /** Discard bearer material when a route is removed, declined or rebound. */
18146
18473
  forget(credentialId) {
18147
18474
  this.#kept.delete(credentialId);
18475
+ this.#usageServed.delete(credentialId);
18476
+ this.#usage.forget(credentialId);
18477
+ }
18478
+ #clearUsageOwnership() {
18479
+ for (const id of this.#usageServed.keys())
18480
+ this.#usage.forget(id);
18481
+ this.#usageServed.clear();
18148
18482
  }
18149
18483
  /** Apply an already-held roster; this never fetches credentials or writes it. */
18150
18484
  retain(identities) {
@@ -18154,6 +18488,11 @@ var init_custody = __esm({
18154
18488
  if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== kept.attempt.credentialType || identity3.accountIdentity !== kept.attempt.expectedAccountIdentity)
18155
18489
  this.forget(id);
18156
18490
  }
18491
+ for (const [id, served] of this.#usageServed) {
18492
+ const identity3 = current.get(id);
18493
+ if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== served.credentialType || identity3.accountIdentity !== served.accountIdentity)
18494
+ this.forget(id);
18495
+ }
18157
18496
  }
18158
18497
  /** A frozen, non-secret summary for a plugin's status display. */
18159
18498
  keptReceiptState() {
@@ -18185,6 +18524,7 @@ var init_custody = __esm({
18185
18524
  token = await this.#token(signal);
18186
18525
  } catch (error) {
18187
18526
  this.#kept.clear();
18527
+ this.#clearUsageOwnership();
18188
18528
  throw error;
18189
18529
  }
18190
18530
  if (this.#outage && kept) {
@@ -18194,6 +18534,7 @@ var init_custody = __esm({
18194
18534
  try {
18195
18535
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
18196
18536
  this.#kept.set(credentialId, { attempt, routeId, since: null });
18537
+ this.#usageServed.set(credentialId, { ...identity3 });
18197
18538
  return attempt;
18198
18539
  } catch (error) {
18199
18540
  this.#check(signal);
@@ -18378,6 +18719,23 @@ var init_custody = __esm({
18378
18719
  }
18379
18720
  };
18380
18721
  }
18722
+ /**
18723
+ * Queue reply quota metadata and return synchronously. Pass rate-limit
18724
+ * headers only, never tokens: the library does not filter header names.
18725
+ * Only credentials served by this custody and retained in its roster report.
18726
+ * Hosts managing their own roster must call retain() when that roster changes.
18727
+ */
18728
+ reportUsage(input) {
18729
+ if (this.#closed)
18730
+ return;
18731
+ try {
18732
+ this.#usage.report(input.credentialId, input.reading);
18733
+ } catch {
18734
+ }
18735
+ }
18736
+ usageReportState() {
18737
+ return this.#usage.state();
18738
+ }
18381
18739
  close() {
18382
18740
  if (this.#closed)
18383
18741
  return;
@@ -18389,12 +18747,23 @@ var init_custody = __esm({
18389
18747
  watch.stop();
18390
18748
  this.#watches.clear();
18391
18749
  this.#kept.clear();
18392
- this.#client.close();
18750
+ const usage = this.#usage.close();
18751
+ if (usage) {
18752
+ this.#tokenReads.add(usage);
18753
+ void usage.then(() => this.#tokenReads.delete(usage));
18754
+ } else
18755
+ this.#client.close();
18756
+ this.#disposing = drainShutdown(this.#tokenReads, (count3) => (this.#onDrainTimeout ?? this.#warnShutdown)(count3)).finally(() => {
18757
+ this.#usage.drop();
18758
+ this.#usageServed.clear();
18759
+ if (usage)
18760
+ this.#client.close();
18761
+ });
18393
18762
  }
18394
- /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
18763
+ /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
18395
18764
  async dispose(onTimeout = this.#warnShutdown) {
18765
+ this.#onDrainTimeout = onTimeout;
18396
18766
  this.close();
18397
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
18398
18767
  await this.#disposing;
18399
18768
  }
18400
18769
  };
@@ -18484,7 +18853,7 @@ var init_interlock = __esm({
18484
18853
 
18485
18854
  // ../core/dist/common-auth-embedded/claustrum/roster.js
18486
18855
  import { createHash as createHash6 } from "node:crypto";
18487
- import { stat as stat5 } from "node:fs/promises";
18856
+ import { stat as stat6 } from "node:fs/promises";
18488
18857
  import { resolve as resolve8 } from "node:path";
18489
18858
  function vaultRosterSeed(roster) {
18490
18859
  return {
@@ -18635,6 +19004,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
18635
19004
  return {
18636
19005
  version: 1,
18637
19006
  view: inventory.view,
19007
+ ...previous?.limits !== void 0 && { limits: previous.limits },
18638
19008
  complete,
18639
19009
  ...!complete && {
18640
19010
  rejected: inventory.skipped.map((record3) => ({
@@ -18705,6 +19075,7 @@ function decodeRoster(value) {
18705
19075
  // that was used whole, so it reads as complete.
18706
19076
  complete: value.complete !== false,
18707
19077
  ...rejected && { rejected },
19078
+ ...value.limits !== void 0 && { limits: value.limits },
18708
19079
  rows,
18709
19080
  declined
18710
19081
  };
@@ -18713,6 +19084,12 @@ function decodedVaultRoster(roster) {
18713
19084
  return decodeRoster(JSON.parse(JSON.stringify(roster)));
18714
19085
  }
18715
19086
  async function readVaultRoster(path2) {
19087
+ if (windowsPrivateFiles)
19088
+ return readFreshVaultRoster(path2);
19089
+ const roster = await rosterReadCache.read([path2], ([resolvedPath = path2]) => readFreshVaultRoster(resolvedPath));
19090
+ return structuredClone(roster);
19091
+ }
19092
+ async function readFreshVaultRoster(path2) {
18716
19093
  let text2;
18717
19094
  try {
18718
19095
  text2 = await readPrivateText(path2, windowsPrivateFiles);
@@ -18731,19 +19108,26 @@ async function readVaultRoster(path2) {
18731
19108
  }
18732
19109
  async function mutateVaultRoster(path2, change, options = {}) {
18733
19110
  return withLock(path2, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
18734
- const current = await readVaultRoster(path2);
19111
+ const current = await readFreshVaultRoster(path2);
18735
19112
  const { next, result } = await change(current, {
18736
19113
  assertOwned: () => lock.assertOwned()
18737
19114
  });
18738
19115
  if (next) {
18739
19116
  await lock.assertOwned();
18740
- await writeJsonAtomic2(path2, next, {
18741
- beforeRename: async () => {
18742
- await options.beforePublish?.();
18743
- options.signal?.throwIfAborted();
18744
- await lock.assertOwned();
18745
- }
18746
- });
19117
+ try {
19118
+ await writeJsonAtomic2(path2, next, {
19119
+ beforeRename: async () => {
19120
+ await options.beforePublish?.();
19121
+ options.signal?.throwIfAborted();
19122
+ await lock.assertOwned();
19123
+ }
19124
+ });
19125
+ } catch (error) {
19126
+ if (error && typeof error === "object" && "published" in error && error.published === true)
19127
+ options.onPublished?.();
19128
+ throw error;
19129
+ }
19130
+ options.onPublished?.();
18747
19131
  }
18748
19132
  return result;
18749
19133
  });
@@ -18891,7 +19275,7 @@ function isVaultRosterLockRefusal(path2, error) {
18891
19275
  }
18892
19276
  async function fileStamp(path2) {
18893
19277
  try {
18894
- const { dev, ino, size, mtimeMs } = await stat5(path2);
19278
+ const { dev, ino, size, mtimeMs } = await stat6(path2);
18895
19279
  return { dev, ino, size, mtimeMs };
18896
19280
  } catch {
18897
19281
  return void 0;
@@ -19031,10 +19415,11 @@ function resolveVaultPrimary(input) {
19031
19415
  ...previous && previous.accountIdentity !== identity3 && { replaced: previous }
19032
19416
  };
19033
19417
  }
19034
- var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries, UNLOCKED_READ_ATTEMPTS;
19418
+ var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, rosterReadCache, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries, UNLOCKED_READ_ATTEMPTS;
19035
19419
  var init_roster = __esm({
19036
19420
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
19037
19421
  "use strict";
19422
+ init_file_read_cache();
19038
19423
  init_fs();
19039
19424
  init_private_files();
19040
19425
  init_quota();
@@ -19049,6 +19434,9 @@ var init_roster = __esm({
19049
19434
  "blank account identity",
19050
19435
  "empty state"
19051
19436
  ]);
19437
+ rosterReadCache = new FileReadCache({
19438
+ followSymlinks: true
19439
+ });
19052
19440
  WRITE_LOCK = {
19053
19441
  name: "claustrum-roster-write",
19054
19442
  ttlMs: 1e4,
@@ -19916,6 +20304,33 @@ var init_consumer = __esm({
19916
20304
  combined.dispose();
19917
20305
  }
19918
20306
  }
20307
+ /**
20308
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
20309
+ * headers only, never tokens: the library does not filter header names.
20310
+ * The credential must have been served by this host and still belong to the route.
20311
+ */
20312
+ reportUsage(input) {
20313
+ if (this.#shutdown.signal.aborted)
20314
+ return;
20315
+ try {
20316
+ const row = this.#roster?.rows.find((row2) => row2.routeId === input.routeId);
20317
+ if (!row?.enabled || row.state !== "active" || row.credentialId !== input.credentialId && !row.aliases?.includes(input.credentialId))
20318
+ return;
20319
+ if (this.#hub) {
20320
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
20321
+ this.#lease.custody.reportUsage(input);
20322
+ } else
20323
+ this.#custody?.reportUsage(input);
20324
+ } catch {
20325
+ }
20326
+ }
20327
+ usageReportState() {
20328
+ try {
20329
+ return (this.#hub ? this.#lease?.custody : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 };
20330
+ } catch {
20331
+ return { pending: 0, inFlight: false, dropped: 0 };
20332
+ }
20333
+ }
19919
20334
  async reportFailure(attempt, status, source) {
19920
20335
  this.#assertOpen();
19921
20336
  if (this.#hub) {
@@ -20077,7 +20492,7 @@ var init_consumer = __esm({
20077
20492
  // ../core/dist/common-auth-embedded/claustrum/hub.js
20078
20493
  import { createHash as createHash7 } from "node:crypto";
20079
20494
  import { channel as channel2 } from "node:diagnostics_channel";
20080
- import { readdir, stat as stat6 } from "node:fs/promises";
20495
+ import { readdir, stat as stat7 } from "node:fs/promises";
20081
20496
  import { dirname as dirname10, join as join8, resolve as resolve10 } from "node:path";
20082
20497
  function canonicalJson3(value, path2 = /* @__PURE__ */ new Set()) {
20083
20498
  if (value === null)
@@ -20527,6 +20942,14 @@ var init_hub = __esm({
20527
20942
  check();
20528
20943
  return custody.reportFailure(attempt, status, source);
20529
20944
  },
20945
+ reportUsage: (input) => {
20946
+ if (!state.released && !generation.ended)
20947
+ custody.reportUsage(input);
20948
+ },
20949
+ usageReportState: () => {
20950
+ check();
20951
+ return custody.usageReportState();
20952
+ },
20530
20953
  forget: (credentialId) => {
20531
20954
  check();
20532
20955
  custody.forget(credentialId);
@@ -20810,7 +21233,7 @@ var init_hub = __esm({
20810
21233
  let newest;
20811
21234
  for (const path2 of candidates) {
20812
21235
  try {
20813
- const modified = (await stat6(path2)).mtimeMs;
21236
+ const modified = (await stat7(path2)).mtimeMs;
20814
21237
  const roster = await readVaultRoster(path2);
20815
21238
  if (roster && (!newest || modified > newest.modified))
20816
21239
  newest = { modified, roster };
@@ -21070,7 +21493,7 @@ __export(claustrum_exports, {
21070
21493
  ChangeNoticeReader: () => ChangeNoticeReader,
21071
21494
  ClaustrumConsumer: () => ClaustrumConsumer,
21072
21495
  ClaustrumConsumerError: () => ClaustrumConsumerError,
21073
- ClaustrumCredentialError: () => ClaustrumCredentialError4,
21496
+ ClaustrumCredentialError: () => ClaustrumCredentialError5,
21074
21497
  ClaustrumDiscoveryHub: () => ClaustrumDiscoveryHub,
21075
21498
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
21076
21499
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
@@ -21127,7 +21550,7 @@ __export(claustrum_exports, {
21127
21550
  vaultRoutingRows: () => vaultRoutingRows
21128
21551
  });
21129
21552
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
21130
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
21553
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
21131
21554
  async function connectClaustrumScopedClient(options) {
21132
21555
  const { connectTimeoutMs, ...client } = options;
21133
21556
  const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
@@ -21177,7 +21600,7 @@ var init_claustrum = __esm({
21177
21600
 
21178
21601
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
21179
21602
  import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
21180
- import { mkdir as mkdir9, rmdir, stat as stat7, utimes } from "node:fs/promises";
21603
+ import { mkdir as mkdir9, rmdir, stat as stat8, utimes } from "node:fs/promises";
21181
21604
  function sameDirectory(observed, identity3) {
21182
21605
  return observed.dev === identity3.dev && observed.ino === identity3.ino;
21183
21606
  }
@@ -21205,7 +21628,7 @@ async function acquire(path2, stale) {
21205
21628
  throw held();
21206
21629
  let mtime;
21207
21630
  try {
21208
- mtime = (await stat7(path2)).mtime.getTime();
21631
+ mtime = (await stat8(path2)).mtime.getTime();
21209
21632
  } catch (error2) {
21210
21633
  if (errorCode(error2) === "ENOENT")
21211
21634
  return acquire(path2, 0);
@@ -21218,7 +21641,7 @@ async function acquire(path2, stale) {
21218
21641
  }
21219
21642
  let created;
21220
21643
  try {
21221
- const st = await stat7(path2);
21644
+ const st = await stat8(path2);
21222
21645
  created = { dev: st.dev, ino: st.ino };
21223
21646
  } catch {
21224
21647
  created = void 0;
@@ -21228,14 +21651,14 @@ async function acquire(path2, stale) {
21228
21651
  const probe = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
21229
21652
  await utimes(path2, probe, probe);
21230
21653
  }
21231
- const observed = await stat7(path2);
21654
+ const observed = await stat8(path2);
21232
21655
  const mtime = observed.mtime.getTime();
21233
21656
  precision ??= mtime % 1e3 === 0 ? "s" : "ms";
21234
21657
  return { dev: observed.dev, ino: observed.ino, mtime };
21235
21658
  } catch (error) {
21236
21659
  try {
21237
21660
  if (created) {
21238
- const current = await stat7(path2).catch(() => void 0);
21661
+ const current = await stat8(path2).catch(() => void 0);
21239
21662
  if (current && current.dev === created.dev && current.ino === created.ino)
21240
21663
  await remove(path2).catch(() => {
21241
21664
  });
@@ -21335,7 +21758,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
21335
21758
  }
21336
21759
  let observed;
21337
21760
  try {
21338
- observed = await stat7(path2);
21761
+ observed = await stat8(path2);
21339
21762
  } catch (error) {
21340
21763
  if (errorCode(error) !== "ENOENT")
21341
21764
  throw error;
@@ -21474,13 +21897,13 @@ async function safeRead(path2, privateFile = false, afterReadCheck) {
21474
21897
  let file;
21475
21898
  try {
21476
21899
  file = await open7(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
21477
- const stat14 = await file.stat();
21478
- if (!stat14.isFile() || privateFile && (stat14.mode & 511) !== 384) {
21900
+ const stat16 = await file.stat();
21901
+ if (!stat16.isFile() || privateFile && (stat16.mode & 511) !== 384) {
21479
21902
  throw new PiSlotError("unsafe-path");
21480
21903
  }
21481
21904
  await afterReadCheck?.(path2);
21482
21905
  const current = await lstat5(path2);
21483
- if (!current.isFile() || current.dev !== stat14.dev || current.ino !== stat14.ino) {
21906
+ if (!current.isFile() || current.dev !== stat16.dev || current.ino !== stat16.ino) {
21484
21907
  throw new PiSlotError("unsafe-path");
21485
21908
  }
21486
21909
  const bytes = await file.readFile();
@@ -22907,6 +23330,9 @@ function loadBackend2() {
22907
23330
  });
22908
23331
  return backend2;
22909
23332
  }
23333
+ function isWindowsSharingViolation2(error) {
23334
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
23335
+ }
22910
23336
  async function privateOperation2(path2, stage, operation) {
22911
23337
  try {
22912
23338
  return await operation();
@@ -23853,7 +24279,7 @@ var init_process_heartbeat = __esm({
23853
24279
  });
23854
24280
 
23855
24281
  // src/version-fence.ts
23856
- import { readdir as readdir2, readFile as readFile9, stat as stat8, unlink as unlink9 } from "node:fs/promises";
24282
+ import { readdir as readdir2, readFile as readFile9, stat as stat9, unlink as unlink9 } from "node:fs/promises";
23857
24283
  import { homedir as homedir3, uptime } from "node:os";
23858
24284
  import { join as join12 } from "node:path";
23859
24285
  function defaultStateHome() {
@@ -23973,7 +24399,7 @@ async function staleRecord(path2, record3, boot, heartbeat) {
23973
24399
  let start = heartbeat ? record3.startedAt : void 0;
23974
24400
  if (start === void 0) {
23975
24401
  try {
23976
- start = (await stat8(path2)).mtimeMs;
24402
+ start = (await stat9(path2)).mtimeMs;
23977
24403
  } catch {
23978
24404
  return false;
23979
24405
  }
@@ -24198,7 +24624,7 @@ import {
24198
24624
  readFile as readFile10,
24199
24625
  rename as rename10,
24200
24626
  rmdir as rmdir2,
24201
- stat as stat9,
24627
+ stat as stat10,
24202
24628
  unlink as unlink10
24203
24629
  } from "node:fs/promises";
24204
24630
  import { basename as basename4, dirname as dirname15, join as join13, resolve as resolve15 } from "node:path";
@@ -25117,7 +25543,7 @@ async function physicalAliases(location, files) {
25117
25543
  async function samePhysical(a, b) {
25118
25544
  const id = async (path2) => {
25119
25545
  try {
25120
- const info = await stat9(path2, { bigint: true });
25546
+ const info = await stat10(path2, { bigint: true });
25121
25547
  return info.ino === 0n ? void 0 : `${info.dev}:${info.ino}`;
25122
25548
  } catch (error) {
25123
25549
  const code2 = error.code;
@@ -25162,7 +25588,8 @@ async function removeOldCopies(location, files, present2, layoutLock, input) {
25162
25588
  if (!await unlinkIfIdentical(
25163
25589
  file,
25164
25590
  location.stateHomeDir,
25165
- () => beforeRemove(file.old, layoutLock, input.steps)
25591
+ () => beforeRemove(file.old, layoutLock, input.steps),
25592
+ input.steps?.oldFileIO
25166
25593
  ))
25167
25594
  kept.push(file.old);
25168
25595
  }
@@ -25184,21 +25611,21 @@ async function sameBytes(a, b) {
25184
25611
  return false;
25185
25612
  }
25186
25613
  }
25187
- function isWindowsSharingError(error) {
25614
+ function isWindowsSharingError(error, platform) {
25188
25615
  const code2 = error?.code;
25189
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
25616
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
25190
25617
  }
25191
- async function unlinkIfIdentical(file, stateDir, guard) {
25618
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile10, unlink: unlink10 }) {
25192
25619
  const started = performance.now();
25193
25620
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
25194
25621
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
25195
25622
  let same;
25196
25623
  try {
25197
- same = (await readFile10(file.old)).equals(await readFile10(file.next));
25624
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
25198
25625
  } catch (error) {
25199
25626
  if (error.code === "ENOENT" && !await exists2(file.old))
25200
25627
  return true;
25201
- if (isWindowsSharingError(error)) {
25628
+ if (isWindowsSharingError(error, io.platform)) {
25202
25629
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
25203
25630
  continue;
25204
25631
  }
@@ -25207,11 +25634,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
25207
25634
  if (!same) throw credentialConflict(stateDir, file);
25208
25635
  await guard();
25209
25636
  try {
25210
- await unlink10(file.old);
25637
+ await io.unlink(file.old);
25211
25638
  return true;
25212
25639
  } catch (error) {
25213
25640
  if (error.code === "ENOENT") return true;
25214
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
25641
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
25215
25642
  return false;
25216
25643
  }
25217
25644
  }
@@ -25382,7 +25809,7 @@ function lockHolderText(name) {
25382
25809
  }
25383
25810
  async function exists2(path2) {
25384
25811
  try {
25385
- await stat9(path2);
25812
+ await stat10(path2);
25386
25813
  return true;
25387
25814
  } catch (error) {
25388
25815
  const code2 = error.code;
@@ -27773,16 +28200,16 @@ async function select2(terminal, items, options) {
27773
28200
  // src/common-auth-embedded/claustrum/enrollment.js
27774
28201
  import { createHash as createHash12, randomBytes as randomBytes3, randomUUID as randomUUID15 } from "node:crypto";
27775
28202
  import { constants as fsConstants2 } from "node:fs";
27776
- 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";
28203
+ import { chmod as chmod5, mkdir as mkdir14, open as open10, readFile as readFile12, realpath as realpath4, rename as rename12, stat as stat13, unlink as unlink11 } from "node:fs/promises";
27777
28204
  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";
28205
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
27779
28206
 
27780
28207
  // src/common-auth-embedded/fs/file-read-cache.js
27781
- import { lstat as lstat7 } from "node:fs/promises";
28208
+ import { lstat as lstat7, stat as stat11 } from "node:fs/promises";
27782
28209
  import { resolve as resolve18 } from "node:path";
27783
- async function identity2(path2) {
28210
+ async function identity2(path2, followSymlinks) {
27784
28211
  try {
27785
- const metadata = await lstat7(path2);
28212
+ const metadata = await (followSymlinks ? stat11(path2) : lstat7(path2));
27786
28213
  return metadata.isFile() ? metadata : void 0;
27787
28214
  } catch (error) {
27788
28215
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -27794,11 +28221,15 @@ function sameIdentity2(left, right) {
27794
28221
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
27795
28222
  }
27796
28223
  var FileReadCache2 = class {
28224
+ #followSymlinks;
27797
28225
  #entries = /* @__PURE__ */ new Map();
28226
+ constructor(options = {}) {
28227
+ this.#followSymlinks = options.followSymlinks ?? false;
28228
+ }
27798
28229
  async read(paths, read, validateHit) {
27799
28230
  const resolvedPaths = paths.map((path2) => resolve18(path2));
27800
28231
  const key = JSON.stringify(resolvedPaths);
27801
- const probed = await Promise.all(resolvedPaths.map(identity2));
28232
+ const probed = await Promise.all(resolvedPaths.map((path2) => identity2(path2, this.#followSymlinks)));
27802
28233
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
27803
28234
  const cached = this.#entries.get(key);
27804
28235
  if (identities && cached && identities.every((entry, index) => {
@@ -27847,7 +28278,7 @@ init_private_files2();
27847
28278
  // src/common-auth-embedded/fs/refresh-file-lock.js
27848
28279
  init_private_files2();
27849
28280
  import { randomUUID as randomUUID14 } from "node:crypto";
27850
- import { lstat as lstat8, mkdir as mkdir13, open as open9, readFile as readFile11, rename as rename11, rm as rm6, stat as stat10 } from "node:fs/promises";
28281
+ import { lstat as lstat8, mkdir as mkdir13, open as open9, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12 } from "node:fs/promises";
27851
28282
  import { dirname as dirname18, join as join17 } from "node:path";
27852
28283
 
27853
28284
  // src/common-auth-embedded/fs/with-lock.js
@@ -28101,7 +28532,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28101
28532
  };
28102
28533
  }
28103
28534
  try {
28104
- const current = await stat10(lockPath);
28535
+ const current = await stat12(lockPath);
28105
28536
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
28106
28537
  if (legacyExpiry > now())
28107
28538
  return { status: "live" };
@@ -28150,37 +28581,83 @@ async function acquireRefreshFileLockWithClock2(options) {
28150
28581
  await rm6(path2, { recursive: true, force: true }).catch(() => {
28151
28582
  });
28152
28583
  }
28153
- async function releaseEvictionMarker() {
28154
- if (await ownsEvictionMarker()) {
28155
- await removeLeaseObject(evictPath);
28156
- }
28584
+ function isRetryableRemoval(error, path2) {
28585
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path2)
28586
+ return false;
28587
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
28588
+ }
28589
+ async function removeOwnedLeaseObject(path2, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
28590
+ let original;
28591
+ let delayMs = 5;
28592
+ while (await stillOwned()) {
28593
+ try {
28594
+ await removeLeaseObject(path2);
28595
+ return;
28596
+ } catch (error) {
28597
+ if (!isRetryableRemoval(error, path2))
28598
+ throw error;
28599
+ original ??= error;
28600
+ }
28601
+ const remainingMs = deadline - performance.now();
28602
+ if (remainingMs <= 0)
28603
+ throw original;
28604
+ await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
28605
+ if (performance.now() >= deadline)
28606
+ throw original;
28607
+ delayMs = Math.min(delayMs * 2, 50);
28608
+ }
28609
+ }
28610
+ async function releaseEvictionMarker(deadline) {
28611
+ let ownedDirectory;
28612
+ await removeOwnedLeaseObject(evictPath, async () => {
28613
+ if (!windowsPrivateFiles2)
28614
+ return ownsEvictionMarker();
28615
+ const current = await lstat8(evictPath).catch((error) => {
28616
+ if (error.code !== "ENOENT")
28617
+ throw error;
28618
+ return void 0;
28619
+ });
28620
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
28621
+ return false;
28622
+ if (await ownsEvictionMarker()) {
28623
+ ownedDirectory = current;
28624
+ return true;
28625
+ }
28626
+ if (!ownedDirectory)
28627
+ return false;
28628
+ try {
28629
+ await stat12(evictOwnerPath);
28630
+ return false;
28631
+ } catch (error) {
28632
+ if (error.code !== "ENOENT")
28633
+ throw error;
28634
+ return true;
28635
+ }
28636
+ }, deadline);
28157
28637
  }
28158
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
28638
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
28159
28639
  if (!created)
28160
28640
  return false;
28161
- let current;
28641
+ let stillOurs = false;
28162
28642
  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);
28643
+ await removeOwnedLeaseObject(evictPath, async () => {
28644
+ stillOurs = false;
28645
+ const st = await lstat8(evictPath).catch(() => void 0);
28646
+ if (!st || !sameMarkerDirectory2(created, st))
28647
+ return false;
28648
+ stillOurs = true;
28649
+ try {
28650
+ await stat12(evictOwnerPath);
28651
+ return false;
28652
+ } catch (error) {
28653
+ return error.code === "ENOENT";
28654
+ }
28655
+ }, deadline);
28179
28656
  } catch {
28180
28657
  }
28181
- return true;
28658
+ return stillOurs;
28182
28659
  }
28183
- async function tryAcquireEvictionMarker() {
28660
+ async function tryAcquireEvictionMarker(deadline) {
28184
28661
  if (windowsPrivateFiles2)
28185
28662
  await createPrivateDirectoryExclusive2(evictPath);
28186
28663
  else
@@ -28204,11 +28681,11 @@ async function acquireRefreshFileLockWithClock2(options) {
28204
28681
  else
28205
28682
  await createExclusiveText2(evictOwnerPath, bytes);
28206
28683
  } catch (error) {
28207
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
28684
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
28208
28685
  if (isLostMarkerRaceError2(error) && !stillOurs)
28209
28686
  return false;
28210
28687
  try {
28211
- await releaseEvictionMarker();
28688
+ await releaseEvictionMarker(deadline);
28212
28689
  } catch {
28213
28690
  }
28214
28691
  throw error;
@@ -28217,10 +28694,10 @@ async function acquireRefreshFileLockWithClock2(options) {
28217
28694
  await options.onStep("eviction-marker-acquired");
28218
28695
  return true;
28219
28696
  }
28220
- async function recoverStaleEvictionMarker() {
28697
+ async function recoverStaleEvictionMarker(deadline) {
28221
28698
  let evictStat;
28222
28699
  try {
28223
- evictStat = await stat10(evictPath);
28700
+ evictStat = await stat12(evictPath);
28224
28701
  } catch (error) {
28225
28702
  if (error.code === "ENOENT")
28226
28703
  return "missing";
@@ -28238,7 +28715,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28238
28715
  if (evictStat.mtimeMs + EVICT_TTL > now()) {
28239
28716
  let hasOwner = true;
28240
28717
  try {
28241
- await stat10(evictOwnerPath);
28718
+ await stat12(evictOwnerPath);
28242
28719
  } catch (error) {
28243
28720
  if (error.code === "ENOENT")
28244
28721
  hasOwner = false;
@@ -28262,12 +28739,22 @@ async function acquireRefreshFileLockWithClock2(options) {
28262
28739
  }
28263
28740
  if (options.onStep)
28264
28741
  await options.onStep("stale-marker-claimed");
28265
- await removeLeaseObject(claimedPath);
28742
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
28743
+ await removeOwnedLeaseObject(claimedPath, async () => {
28744
+ if (!claimedIdentity)
28745
+ return true;
28746
+ const current = await lstat8(claimedPath).catch((error) => {
28747
+ if (error.code !== "ENOENT")
28748
+ throw error;
28749
+ return void 0;
28750
+ });
28751
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
28752
+ }, deadline);
28266
28753
  return "recovered";
28267
28754
  }
28268
- async function withEvictionMarker(action) {
28755
+ async function withEvictionMarker(action, deadline) {
28269
28756
  try {
28270
- if (!await tryAcquireEvictionMarker())
28757
+ if (!await tryAcquireEvictionMarker(deadline))
28271
28758
  return false;
28272
28759
  } catch (error) {
28273
28760
  if (error.code === "EEXIST") {
@@ -28284,11 +28771,23 @@ async function acquireRefreshFileLockWithClock2(options) {
28284
28771
  }
28285
28772
  throw error;
28286
28773
  }
28774
+ let actionFailed = false;
28775
+ let actionError;
28287
28776
  try {
28288
28777
  await action();
28289
- } finally {
28290
- await releaseEvictionMarker();
28778
+ } catch (error) {
28779
+ actionFailed = true;
28780
+ actionError = error;
28291
28781
  }
28782
+ try {
28783
+ await releaseEvictionMarker(deadline);
28784
+ } catch (error) {
28785
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
28786
+ throw actionError;
28787
+ throw error;
28788
+ }
28789
+ if (actionFailed)
28790
+ throw actionError;
28292
28791
  return true;
28293
28792
  }
28294
28793
  async function relinquishLockAfterMarkerLoss() {
@@ -28525,6 +29024,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28525
29024
  await renewalInFlight;
28526
29025
  const deadline = performance.now() + EVICT_TTL + 1e3;
28527
29026
  let delayMs = 5;
29027
+ let removalError;
28528
29028
  for (; ; ) {
28529
29029
  try {
28530
29030
  let removalConfirmed = false;
@@ -28549,7 +29049,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28549
29049
  return;
28550
29050
  await removeLeaseObject(lockPath);
28551
29051
  removalConfirmed = true;
28552
- });
29052
+ }, deadline);
28553
29053
  if (markerAcquired) {
28554
29054
  if (windowsPrivateFiles2 && !removalConfirmed)
28555
29055
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -28560,20 +29060,25 @@ async function acquireRefreshFileLockWithClock2(options) {
28560
29060
  }
28561
29061
  if (signal?.aborted)
28562
29062
  return;
28563
- await recoverStaleEvictionMarker();
29063
+ await recoverStaleEvictionMarker(deadline);
28564
29064
  } catch (error) {
28565
- if (windowsPrivateFiles2)
28566
- throw error;
28567
- return;
29065
+ if (!isRetryableRemoval(error, lockPath)) {
29066
+ if (windowsPrivateFiles2)
29067
+ throw error;
29068
+ return;
29069
+ }
29070
+ removalError ??= error;
28568
29071
  }
28569
29072
  const remainingMs = deadline - performance.now();
28570
29073
  if (remainingMs <= 0)
28571
29074
  break;
28572
29075
  await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
29076
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
29077
+ break;
28573
29078
  delayMs = Math.min(delayMs * 2, 50);
28574
29079
  }
28575
29080
  if (windowsPrivateFiles2)
28576
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
29081
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
28577
29082
  code: "ETIMEDOUT"
28578
29083
  });
28579
29084
  }
@@ -28616,7 +29121,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
28616
29121
  "pending_queue_full"
28617
29122
  ]);
28618
29123
  function classifyEnrollmentError2(error) {
28619
- if (!(error instanceof ClaustrumCredentialError5))
29124
+ if (!(error instanceof ClaustrumCredentialError6))
28620
29125
  return void 0;
28621
29126
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
28622
29127
  return { code: error.code, disposition: "terminal" };
@@ -28827,7 +29332,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
28827
29332
  }
28828
29333
  let privateGroup;
28829
29334
  for (; ; ) {
28830
- const metadata = await stat11(component).catch(() => void 0);
29335
+ const metadata = await stat13(component).catch(() => void 0);
28831
29336
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
28832
29337
  if (privateGroup === void 0) {
28833
29338
  privateGroup = gid !== void 0 && await isPrivateGroup2(uid, gid, options);
@@ -28856,7 +29361,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
28856
29361
  return;
28857
29362
  }
28858
29363
  await mkdir14(directory, { recursive: true, mode: 448 });
28859
- const metadata = await stat11(directory);
29364
+ const metadata = await stat13(directory);
28860
29365
  const uid = process.geteuid?.();
28861
29366
  if (uid !== void 0 && metadata.uid !== uid) {
28862
29367
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -29445,7 +29950,7 @@ function setupPaths(io = {}) {
29445
29950
  }
29446
29951
 
29447
29952
  // src/common-auth-embedded/setup/detect.js
29448
- function stat12(path2, kind) {
29953
+ function stat14(path2, kind) {
29449
29954
  try {
29450
29955
  return statSync5(path2)[kind]();
29451
29956
  } catch {
@@ -29454,12 +29959,12 @@ function stat12(path2, kind) {
29454
29959
  }
29455
29960
  var defaultSetupFileSystem = {
29456
29961
  exists: existsSync6,
29457
- isFile: (path2) => stat12(path2, "isFile"),
29458
- isDirectory: (path2) => stat12(path2, "isDirectory"),
29962
+ isFile: (path2) => stat14(path2, "isFile"),
29963
+ isDirectory: (path2) => stat14(path2, "isDirectory"),
29459
29964
  isExecutable(path2) {
29460
29965
  try {
29461
29966
  accessSync(path2, constants3.X_OK);
29462
- return stat12(path2, "isFile");
29967
+ return stat14(path2, "isFile");
29463
29968
  } catch {
29464
29969
  return false;
29465
29970
  }
@@ -29958,6 +30463,12 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
29958
30463
  await writeEnrollmentTokenFile3(path2, file);
29959
30464
  }
29960
30465
  });
30466
+ await fence();
30467
+ const initial = await manager.status();
30468
+ if (initial.state === "approved") {
30469
+ printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
30470
+ return;
30471
+ }
29961
30472
  printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
29962
30473
  const deadline = now() + ENROLLMENT_WAIT_MS;
29963
30474
  let printedRequest;
@@ -29965,7 +30476,6 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
29965
30476
  let reportedCode;
29966
30477
  let failedProposals = 0;
29967
30478
  for (; ; ) {
29968
- await fence();
29969
30479
  const status = await manager.reconcile();
29970
30480
  if (status.state === "approved") {
29971
30481
  printLine2(terminal, `Connected ${host} to Claustrum.`);
@@ -30011,6 +30521,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
30011
30521
  if (remaining <= 0)
30012
30522
  break;
30013
30523
  await wait2(Math.min(pause, remaining));
30524
+ await fence();
30014
30525
  }
30015
30526
  if (printedRequest)
30016
30527
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -30165,7 +30676,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
30165
30676
 
30166
30677
  // src/common-auth-embedded/setup/config-write.js
30167
30678
  import { randomUUID as randomUUID16 } from "node:crypto";
30168
- import { mkdir as mkdir15, open as open11, rename as rename13, stat as stat13, unlink as unlink12 } from "node:fs/promises";
30679
+ import { mkdir as mkdir15, open as open11, rename as rename13, stat as stat15, unlink as unlink12 } from "node:fs/promises";
30169
30680
  import { basename as basename6, dirname as dirname20, join as join20 } from "node:path";
30170
30681
  import { setTimeout as delay2 } from "node:timers/promises";
30171
30682
  async function writeHostConfigAtomic(file, content, options = {}) {
@@ -30175,7 +30686,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
30175
30686
  let mode;
30176
30687
  if (!windows) {
30177
30688
  try {
30178
- mode = (await stat13(file)).mode & 4095;
30689
+ mode = (await stat15(file)).mode & 4095;
30179
30690
  } catch (error) {
30180
30691
  if (error.code !== "ENOENT")
30181
30692
  throw error;
@@ -30766,7 +31277,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30766
31277
  }
30767
31278
  };
30768
31279
  let openCodeLogin;
30769
- let hasLocalPool = false;
31280
+ const nativeNextStep = (label) => {
31281
+ deps.stdout.write(
31282
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
31283
+ Setup has not completed the OpenCode 2 native Google connection.
31284
+ `
31285
+ );
31286
+ };
30770
31287
  const manifest = JSON.parse(
30771
31288
  await readFile13(new URL("../package.json", import.meta.url), "utf8")
30772
31289
  );
@@ -30824,18 +31341,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30824
31341
  await assertLocal(host, context);
30825
31342
  if (host === "opencode" && context.opencodeGeneration === "2") {
30826
31343
  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
- }
31344
+ const source2 = await deps.accountStore.read(
31345
+ deps.accountStore.legacyPath()
31346
+ );
31347
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
30839
31348
  }
30840
31349
  return;
30841
31350
  }
@@ -30850,11 +31359,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30850
31359
  `Using existing local Antigravity login for ${host}.
30851
31360
  `
30852
31361
  );
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
31362
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
30859
31363
  const account = accounts[0];
30860
31364
  await writeNativeSlot(
@@ -30887,18 +31391,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
30887
31391
  );
30888
31392
  if (host === "opencode") {
30889
31393
  openCodeLogin = result;
30890
- hasLocalPool = true;
30891
31394
  }
30892
31395
  },
30893
31396
  beforeRegister: async (host, mode, context) => {
30894
31397
  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
31398
  if (mode === "local") {
30903
31399
  await assertLocal(host, context);
30904
31400
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -30912,10 +31408,6 @@ Setup has not completed the OpenCode 2 native Google connection.
30912
31408
  },
30913
31409
  context
30914
31410
  );
30915
- if (needsOpenCode2)
30916
- nativeNextStep(
30917
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
30918
- );
30919
31411
  return;
30920
31412
  }
30921
31413
  if (await authority(host) !== "vault")
@@ -30986,11 +31478,28 @@ Setup has not completed the OpenCode 2 native Google connection.
30986
31478
  await publishedGeneration(stateAnchor),
30987
31479
  stateAnchor
30988
31480
  );
30989
- return;
31481
+ } else {
31482
+ if (await migrateOpenCode() !== 0)
31483
+ throw new Error("Offline Antigravity account migration failed.");
31484
+ await deps.prepareVaultFolder?.();
31485
+ }
31486
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
31487
+ let reconnectReady = false;
31488
+ if (!forceLogin || context.opencodeGeneration !== "2") {
31489
+ if (source.kind === "store") {
31490
+ reconnectReady = source.reconnectReady;
31491
+ } else if (source.kind === "legacy") {
31492
+ const post = await deps.accountStore.read(
31493
+ deps.accountStore.legacyPath()
31494
+ );
31495
+ if (post.kind === "unavailable") throw new Error(post.reason);
31496
+ reconnectReady = post.kind === "store" && post.reconnectReady;
31497
+ }
31498
+ }
31499
+ nativeNextStep(
31500
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
31501
+ );
30990
31502
  }
30991
- if (await migrateOpenCode() !== 0)
30992
- throw new Error("Offline Antigravity account migration failed.");
30993
- await deps.prepareVaultFolder?.();
30994
31503
  } else {
30995
31504
  deps.stdout.write(
30996
31505
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -31582,6 +32091,7 @@ async function readAccountStore(legacyPath) {
31582
32091
  case "bound":
31583
32092
  break;
31584
32093
  }
32094
+ const generationId = admission.receipt.id;
31585
32095
  const repository = createAccountRepositoryFactory(modules)({
31586
32096
  paths: admission.paths,
31587
32097
  now: Date.now,
@@ -31595,6 +32105,12 @@ async function readAccountStore(legacyPath) {
31595
32105
  }
31596
32106
  });
31597
32107
  try {
32108
+ const servingBefore = await readAccountStoreAdmission(
32109
+ legacyPath,
32110
+ modules,
32111
+ Date.now,
32112
+ generationId
32113
+ );
31598
32114
  const read = await repository.read();
31599
32115
  if (read.status !== "ready") {
31600
32116
  return {
@@ -31602,7 +32118,20 @@ async function readAccountStore(legacyPath) {
31602
32118
  reason: `the account store is ${read.status}`
31603
32119
  };
31604
32120
  }
31605
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
32121
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
32122
+ legacyPath,
32123
+ modules,
32124
+ Date.now,
32125
+ generationId
32126
+ ) : servingBefore;
32127
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
32128
+ (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
32129
+ );
32130
+ return {
32131
+ kind: "store",
32132
+ accounts: read.rows.map(cliAccountOf),
32133
+ reconnectReady
32134
+ };
31606
32135
  } finally {
31607
32136
  await repository.dispose();
31608
32137
  }