@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/dist/cli.js +689 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +130 -67
  4. package/dist/index.js +734 -191
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +159 -72
  7. package/dist/server.js +734 -194
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +1 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +22 -2
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +36 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +74 -9
  18. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  19. package/dist/src/common-auth-embedded/claustrum/hub.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  21. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +2 -0
  23. package/dist/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  24. package/dist/src/common-auth-embedded/claustrum/usage.js +145 -0
  25. package/dist/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  26. package/dist/src/common-auth-embedded/commands/builtins.js +38 -0
  27. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  28. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  29. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  30. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  31. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  32. package/dist/src/common-auth-embedded/limits/axes.d.ts +63 -0
  33. package/dist/src/common-auth-embedded/limits/decide.d.ts +141 -0
  34. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  35. package/dist/src/common-auth-embedded/limits/families.d.ts +57 -0
  36. package/dist/src/common-auth-embedded/limits/marker.d.ts +64 -0
  37. package/dist/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  38. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  39. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  40. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  41. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  42. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  43. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  44. package/dist/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  45. package/dist/src/common-auth-embedded/opencode2/install.js +161 -18
  46. package/dist/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  47. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  48. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  49. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  50. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  51. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  52. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  53. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  54. package/dist/src/common-auth-embedded/source-output.json +254 -118
  55. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  56. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  57. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  58. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  59. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  60. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  61. package/dist/src/common-auth-embedded/store/limits-namespace.js +34 -0
  62. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  63. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  64. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  65. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  66. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  67. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  68. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  69. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  70. package/dist/src/runtime-layout.d.ts +9 -2
  71. package/dist/src/runtime-layout.d.ts.map +1 -1
  72. package/dist/src/runtime-layout.js +8 -8
  73. package/dist/src/runtime-layout.js.map +1 -1
  74. package/dist/src/setup.d.ts.map +1 -1
  75. package/dist/src/setup.js +29 -40
  76. package/dist/src/setup.js.map +1 -1
  77. package/dist/tui-build-map.json +9 -9
  78. package/dist/tui-ga-build-map.json +1 -1
  79. package/dist/types/src/cli.d.ts +1 -0
  80. package/dist/types/src/cli.d.ts.map +1 -1
  81. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  82. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  83. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  84. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  85. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  86. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  87. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  88. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  89. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +63 -0
  90. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +141 -0
  91. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  92. package/dist/types/src/common-auth-embedded/limits/families.d.ts +57 -0
  93. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +64 -0
  94. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  95. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  96. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  97. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  98. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  99. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  100. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  101. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  102. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  103. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  104. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  105. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  106. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  107. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  108. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  109. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  110. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  111. package/dist/types/src/runtime-layout.d.ts +9 -2
  112. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  113. package/dist/types/src/setup.d.ts.map +1 -1
  114. package/package.json +2 -2
  115. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  116. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  117. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  118. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  119. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  120. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  121. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  122. package/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  123. package/src/common-auth-embedded/claustrum/roster.js +2 -0
  124. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  125. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  126. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  127. package/src/common-auth-embedded/commands/builtins.js +38 -0
  128. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  129. package/src/common-auth-embedded/fs/private-files.js +7 -0
  130. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  131. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  132. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  133. package/src/common-auth-embedded/limits/axes.d.ts +63 -0
  134. package/src/common-auth-embedded/limits/decide.d.ts +141 -0
  135. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  136. package/src/common-auth-embedded/limits/families.d.ts +57 -0
  137. package/src/common-auth-embedded/limits/marker.d.ts +64 -0
  138. package/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  139. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  140. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  141. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  142. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  143. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  144. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  145. package/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  146. package/src/common-auth-embedded/opencode2/install.js +161 -18
  147. package/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  148. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  149. package/src/common-auth-embedded/routing/admission.js +17 -7
  150. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  151. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  152. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  153. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  154. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  155. package/src/common-auth-embedded/source-output.json +254 -118
  156. package/src/common-auth-embedded/store/attribution.js +3 -2
  157. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  158. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  159. package/src/common-auth-embedded/store/hooks.js +20 -5
  160. package/src/common-auth-embedded/store/index.d.ts +1 -0
  161. package/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  162. package/src/common-auth-embedded/store/limits-namespace.js +34 -0
  163. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  164. package/src/common-auth-embedded/store/pool.js +2 -0
  165. package/src/common-auth-embedded/store/provider-state.js +5 -5
  166. package/src/common-auth-embedded/store/refresh.js +1 -1
  167. package/src/common-auth-embedded/store/schema.js +9 -4
  168. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  169. package/src/common-auth-embedded/store/settings.js +11 -4
  170. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  171. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  172. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  173. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
package/dist/index.js CHANGED
@@ -636,6 +636,9 @@ function loadBackend() {
636
636
  });
637
637
  return backend;
638
638
  }
639
+ function isWindowsSharingViolation(error) {
640
+ return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
641
+ }
639
642
  async function privateOperation(path5, stage, operation) {
640
643
  try {
641
644
  return await operation();
@@ -12533,6 +12536,48 @@ var init_identity = __esm({
12533
12536
  }
12534
12537
  });
12535
12538
 
12539
+ // ../core/dist/common-auth-embedded/store/hooks.js
12540
+ import { AsyncLocalStorage } from "node:async_hooks";
12541
+ function assertNotInsideHook(operation) {
12542
+ if (insideHook.getStore() !== void 0)
12543
+ throw new PoolReentryError(operation);
12544
+ }
12545
+ function assertLimitsWriteAllowed() {
12546
+ if (insideHook.getStore()?.storeLocksReleased === false || insideCodec.getStore())
12547
+ throw new PoolReentryError("updateLimitsNamespace");
12548
+ }
12549
+ function runInsideCodec(fn) {
12550
+ return insideCodec.run(true, fn);
12551
+ }
12552
+ function runInsideHook(operation, fn, storeLocksReleased = false) {
12553
+ return insideHook.run({
12554
+ operation,
12555
+ storeLocksReleased: storeLocksReleased && insideHook.getStore()?.storeLocksReleased !== false
12556
+ }, async () => await fn());
12557
+ }
12558
+ async function callFailureHook(operation, hook, rowId2, error, logger3) {
12559
+ if (!hook)
12560
+ return;
12561
+ try {
12562
+ await runInsideHook(operation, () => hook(rowId2, error), true);
12563
+ } catch (hookError) {
12564
+ logger3?.warn("store failure hook threw; the original failure stands", {
12565
+ operation,
12566
+ rowId: rowId2,
12567
+ error: hookError instanceof Error ? hookError.message : String(hookError)
12568
+ });
12569
+ }
12570
+ }
12571
+ var insideHook, insideCodec;
12572
+ var init_hooks = __esm({
12573
+ "../core/dist/common-auth-embedded/store/hooks.js"() {
12574
+ "use strict";
12575
+ init_errors();
12576
+ insideHook = new AsyncLocalStorage();
12577
+ insideCodec = new AsyncLocalStorage();
12578
+ }
12579
+ });
12580
+
12536
12581
  // ../core/dist/common-auth-embedded/fs/atomic-write.js
12537
12582
  import { randomUUID as randomUUID8 } from "node:crypto";
12538
12583
  import { mkdir as mkdir6, open as open3, rename as rename5, rm as rm3 } from "node:fs/promises";
@@ -12914,37 +12959,83 @@ async function acquireRefreshFileLockWithClock(options) {
12914
12959
  await rm4(path5, { recursive: true, force: true }).catch(() => {
12915
12960
  });
12916
12961
  }
12917
- async function releaseEvictionMarker() {
12918
- if (await ownsEvictionMarker()) {
12919
- await removeLeaseObject(evictPath);
12920
- }
12962
+ function isRetryableRemoval(error, path5) {
12963
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path5)
12964
+ return false;
12965
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
12921
12966
  }
12922
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
12967
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
12968
+ let original;
12969
+ let delayMs = 5;
12970
+ while (await stillOwned()) {
12971
+ try {
12972
+ await removeLeaseObject(path5);
12973
+ return;
12974
+ } catch (error) {
12975
+ if (!isRetryableRemoval(error, path5))
12976
+ throw error;
12977
+ original ??= error;
12978
+ }
12979
+ const remainingMs = deadline - performance.now();
12980
+ if (remainingMs <= 0)
12981
+ throw original;
12982
+ await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
12983
+ if (performance.now() >= deadline)
12984
+ throw original;
12985
+ delayMs = Math.min(delayMs * 2, 50);
12986
+ }
12987
+ }
12988
+ async function releaseEvictionMarker(deadline) {
12989
+ let ownedDirectory;
12990
+ await removeOwnedLeaseObject(evictPath, async () => {
12991
+ if (!windowsPrivateFiles)
12992
+ return ownsEvictionMarker();
12993
+ const current = await lstat3(evictPath).catch((error) => {
12994
+ if (error.code !== "ENOENT")
12995
+ throw error;
12996
+ return void 0;
12997
+ });
12998
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
12999
+ return false;
13000
+ if (await ownsEvictionMarker()) {
13001
+ ownedDirectory = current;
13002
+ return true;
13003
+ }
13004
+ if (!ownedDirectory)
13005
+ return false;
13006
+ try {
13007
+ await stat3(evictOwnerPath);
13008
+ return false;
13009
+ } catch (error) {
13010
+ if (error.code !== "ENOENT")
13011
+ throw error;
13012
+ return true;
13013
+ }
13014
+ }, deadline);
13015
+ }
13016
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
12923
13017
  if (!created)
12924
13018
  return false;
12925
- let current;
12926
- try {
12927
- const st = await lstat3(evictPath);
12928
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
12929
- } catch {
12930
- return false;
12931
- }
12932
- if (!sameMarkerDirectory(created, current))
12933
- return false;
13019
+ let stillOurs = false;
12934
13020
  try {
12935
- await stat3(evictOwnerPath);
12936
- return true;
12937
- } catch (error) {
12938
- if (error.code !== "ENOENT")
12939
- return true;
12940
- }
12941
- try {
12942
- await removeLeaseObject(evictPath);
13021
+ await removeOwnedLeaseObject(evictPath, async () => {
13022
+ stillOurs = false;
13023
+ const st = await lstat3(evictPath).catch(() => void 0);
13024
+ if (!st || !sameMarkerDirectory(created, st))
13025
+ return false;
13026
+ stillOurs = true;
13027
+ try {
13028
+ await stat3(evictOwnerPath);
13029
+ return false;
13030
+ } catch (error) {
13031
+ return error.code === "ENOENT";
13032
+ }
13033
+ }, deadline);
12943
13034
  } catch {
12944
13035
  }
12945
- return true;
13036
+ return stillOurs;
12946
13037
  }
12947
- async function tryAcquireEvictionMarker() {
13038
+ async function tryAcquireEvictionMarker(deadline) {
12948
13039
  if (windowsPrivateFiles)
12949
13040
  await createPrivateDirectoryExclusive(evictPath);
12950
13041
  else
@@ -12968,11 +13059,11 @@ async function acquireRefreshFileLockWithClock(options) {
12968
13059
  else
12969
13060
  await createExclusiveText(evictOwnerPath, bytes);
12970
13061
  } catch (error) {
12971
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
13062
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
12972
13063
  if (isLostMarkerRaceError(error) && !stillOurs)
12973
13064
  return false;
12974
13065
  try {
12975
- await releaseEvictionMarker();
13066
+ await releaseEvictionMarker(deadline);
12976
13067
  } catch {
12977
13068
  }
12978
13069
  throw error;
@@ -12981,7 +13072,7 @@ async function acquireRefreshFileLockWithClock(options) {
12981
13072
  await options.onStep("eviction-marker-acquired");
12982
13073
  return true;
12983
13074
  }
12984
- async function recoverStaleEvictionMarker() {
13075
+ async function recoverStaleEvictionMarker(deadline) {
12985
13076
  let evictStat;
12986
13077
  try {
12987
13078
  evictStat = await stat3(evictPath);
@@ -13026,12 +13117,22 @@ async function acquireRefreshFileLockWithClock(options) {
13026
13117
  }
13027
13118
  if (options.onStep)
13028
13119
  await options.onStep("stale-marker-claimed");
13029
- await removeLeaseObject(claimedPath);
13120
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
13121
+ await removeOwnedLeaseObject(claimedPath, async () => {
13122
+ if (!claimedIdentity)
13123
+ return true;
13124
+ const current = await lstat3(claimedPath).catch((error) => {
13125
+ if (error.code !== "ENOENT")
13126
+ throw error;
13127
+ return void 0;
13128
+ });
13129
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
13130
+ }, deadline);
13030
13131
  return "recovered";
13031
13132
  }
13032
- async function withEvictionMarker(action) {
13133
+ async function withEvictionMarker(action, deadline) {
13033
13134
  try {
13034
- if (!await tryAcquireEvictionMarker())
13135
+ if (!await tryAcquireEvictionMarker(deadline))
13035
13136
  return false;
13036
13137
  } catch (error) {
13037
13138
  if (error.code === "EEXIST") {
@@ -13048,11 +13149,23 @@ async function acquireRefreshFileLockWithClock(options) {
13048
13149
  }
13049
13150
  throw error;
13050
13151
  }
13152
+ let actionFailed = false;
13153
+ let actionError;
13051
13154
  try {
13052
13155
  await action();
13053
- } finally {
13054
- await releaseEvictionMarker();
13156
+ } catch (error) {
13157
+ actionFailed = true;
13158
+ actionError = error;
13159
+ }
13160
+ try {
13161
+ await releaseEvictionMarker(deadline);
13162
+ } catch (error) {
13163
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
13164
+ throw actionError;
13165
+ throw error;
13055
13166
  }
13167
+ if (actionFailed)
13168
+ throw actionError;
13056
13169
  return true;
13057
13170
  }
13058
13171
  async function relinquishLockAfterMarkerLoss() {
@@ -13289,6 +13402,7 @@ async function acquireRefreshFileLockWithClock(options) {
13289
13402
  await renewalInFlight;
13290
13403
  const deadline = performance.now() + EVICT_TTL + 1e3;
13291
13404
  let delayMs = 5;
13405
+ let removalError;
13292
13406
  for (; ; ) {
13293
13407
  try {
13294
13408
  let removalConfirmed = false;
@@ -13313,7 +13427,7 @@ async function acquireRefreshFileLockWithClock(options) {
13313
13427
  return;
13314
13428
  await removeLeaseObject(lockPath);
13315
13429
  removalConfirmed = true;
13316
- });
13430
+ }, deadline);
13317
13431
  if (markerAcquired) {
13318
13432
  if (windowsPrivateFiles && !removalConfirmed)
13319
13433
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -13324,20 +13438,25 @@ async function acquireRefreshFileLockWithClock(options) {
13324
13438
  }
13325
13439
  if (signal?.aborted)
13326
13440
  return;
13327
- await recoverStaleEvictionMarker();
13441
+ await recoverStaleEvictionMarker(deadline);
13328
13442
  } catch (error) {
13329
- if (windowsPrivateFiles)
13330
- throw error;
13331
- return;
13443
+ if (!isRetryableRemoval(error, lockPath)) {
13444
+ if (windowsPrivateFiles)
13445
+ throw error;
13446
+ return;
13447
+ }
13448
+ removalError ??= error;
13332
13449
  }
13333
13450
  const remainingMs = deadline - performance.now();
13334
13451
  if (remainingMs <= 0)
13335
13452
  break;
13336
13453
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
13454
+ if (windowsPrivateFiles && performance.now() >= deadline)
13455
+ break;
13337
13456
  delayMs = Math.min(delayMs * 2, 50);
13338
13457
  }
13339
13458
  if (windowsPrivateFiles)
13340
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
13459
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
13341
13460
  code: "ETIMEDOUT"
13342
13461
  });
13343
13462
  }
@@ -13361,7 +13480,7 @@ function lockPathFor(target, name) {
13361
13480
  return `${target}.${name}.lock`;
13362
13481
  }
13363
13482
  function isChangingLockRead(error, target, name) {
13364
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.reason !== "io-error" || error.win32Code !== 32 && error.win32Code !== 303 || error.stage !== "read" && error.stage !== "verify")
13483
+ if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
13365
13484
  return false;
13366
13485
  const path5 = resolve3(lockPathFor(target, name));
13367
13486
  return error.path === path5 || error.path === join6(path5, "owner.json");
@@ -13433,37 +13552,6 @@ var init_with_lock = __esm({
13433
13552
  }
13434
13553
  });
13435
13554
 
13436
- // ../core/dist/common-auth-embedded/store/hooks.js
13437
- import { AsyncLocalStorage } from "node:async_hooks";
13438
- function assertNotInsideHook(operation) {
13439
- if (insideHook.getStore() !== void 0)
13440
- throw new PoolReentryError(operation);
13441
- }
13442
- function runInsideHook(operation, fn) {
13443
- return insideHook.run(operation, async () => await fn());
13444
- }
13445
- async function callFailureHook(operation, hook, rowId2, error, logger3) {
13446
- if (!hook)
13447
- return;
13448
- try {
13449
- await runInsideHook(operation, () => hook(rowId2, error));
13450
- } catch (hookError) {
13451
- logger3?.warn("store failure hook threw; the original failure stands", {
13452
- operation,
13453
- rowId: rowId2,
13454
- error: hookError instanceof Error ? hookError.message : String(hookError)
13455
- });
13456
- }
13457
- }
13458
- var insideHook;
13459
- var init_hooks = __esm({
13460
- "../core/dist/common-auth-embedded/store/hooks.js"() {
13461
- "use strict";
13462
- init_errors();
13463
- insideHook = new AsyncLocalStorage();
13464
- }
13465
- });
13466
-
13467
13555
  // ../core/dist/common-auth-embedded/store/refresh-lock.js
13468
13556
  async function acquirePoolLock(spec, defaults, env3) {
13469
13557
  const emit = (type) => {
@@ -13695,7 +13783,7 @@ function stampFor(credential, credentialEpoch2, binding, options = {}) {
13695
13783
  };
13696
13784
  }
13697
13785
  function providerStateDigest(codec, value) {
13698
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
13786
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
13699
13787
  return createHash5("sha256").update(`provider-state\0${JSON.stringify(bound ?? null)}`).digest("hex");
13700
13788
  }
13701
13789
  function boundProviderStateDigest(account, credential, credentialEpoch2, identity3) {
@@ -13862,8 +13950,8 @@ function parseEntry(raw, codec) {
13862
13950
  return void 0;
13863
13951
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
13864
13952
  return void 0;
13865
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
13866
- if ("quota" in raw && !codec.validate(quota))
13953
+ const quota = "quota" in raw && codec.decode ? runInsideCodec(() => codec.decode?.(raw.quota)) : raw.quota;
13954
+ if ("quota" in raw && !runInsideCodec(() => codec.validate(quota)))
13867
13955
  return void 0;
13868
13956
  if ("staged" in raw && !parseReservation(raw.staged))
13869
13957
  return void 0;
@@ -14035,7 +14123,7 @@ function providerStateFields(account, credential, credentialEpoch2, identity3, c
14035
14123
  if (digest3 === void 0)
14036
14124
  return { providerStateDropped: "uncovered" };
14037
14125
  const value = account[PROVIDER_STATE_KEY];
14038
- if (!codec?.validate(value))
14126
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
14039
14127
  return { providerStateDropped: "invalid" };
14040
14128
  if (providerStateDigest(codec, value) !== digest3)
14041
14129
  return { providerStateDropped: "uncovered" };
@@ -14112,6 +14200,7 @@ var POOL_KEY, POOL_SCHEMA_VERSION, POOL_ROWS_KEY, POOL_RETIRED_EPOCHS_KEY, LEGAC
14112
14200
  var init_schema = __esm({
14113
14201
  "../core/dist/common-auth-embedded/store/schema.js"() {
14114
14202
  "use strict";
14203
+ init_hooks();
14115
14204
  POOL_KEY = "commonAuthPool";
14116
14205
  POOL_SCHEMA_VERSION = 1;
14117
14206
  POOL_ROWS_KEY = "rows";
@@ -14812,8 +14901,8 @@ function assertQuotaRow(id, attribution, row) {
14812
14901
  });
14813
14902
  }
14814
14903
  function mergedQuota(ctx, id, stored, observation) {
14815
- const merged = ctx.codec.merge(stored, observation);
14816
- if (!ctx.codec.validate(merged))
14904
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
14905
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
14817
14906
  throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
14818
14907
  return merged;
14819
14908
  }
@@ -14853,6 +14942,7 @@ var init_attribution = __esm({
14853
14942
  "../core/dist/common-auth-embedded/store/attribution.js"() {
14854
14943
  "use strict";
14855
14944
  init_errors();
14945
+ init_hooks();
14856
14946
  init_mutate();
14857
14947
  init_refresh_lock();
14858
14948
  init_runtime();
@@ -14860,6 +14950,46 @@ var init_attribution = __esm({
14860
14950
  }
14861
14951
  });
14862
14952
 
14953
+ // ../core/dist/common-auth-embedded/store/limits-namespace.js
14954
+ async function updatePoolLimitsNamespace(rt, mutator) {
14955
+ assertLimitsWriteAllowed();
14956
+ const { ctx } = rt;
14957
+ await runOperation(ctx, "updateLimitsNamespace", void 0, void 0, async (locks, progress) => {
14958
+ for (const spec of ctx.storeLocks)
14959
+ await locks.acquire(spec);
14960
+ const result = await readPool(ctx);
14961
+ if (result.status !== "ready")
14962
+ throw notReadyError(result, "updateLimitsNamespace", void 0);
14963
+ const rows = result.rows.map(({ id, credentialEpoch: credentialEpoch2, identity: identity3 }) => ({
14964
+ id,
14965
+ credentialEpoch: credentialEpoch2,
14966
+ identity: identity3
14967
+ }));
14968
+ const envelope = await runInsideHook("updateLimitsNamespace", () => mutator(structuredClone(result.config.commonAuthLimits), rows));
14969
+ const config = { ...result.config, commonAuthLimits: envelope };
14970
+ const info = {
14971
+ operation: "updateLimitsNamespace",
14972
+ rowId: void 0
14973
+ };
14974
+ await writeJsonAtomic2(ctx.configPath, config, {
14975
+ beforeRename: async () => {
14976
+ await ctx.onStep?.("before-config-write", info);
14977
+ await locks.assertAll();
14978
+ }
14979
+ });
14980
+ progress.writes++;
14981
+ await ctx.onStep?.("after-config-write", info);
14982
+ });
14983
+ }
14984
+ var init_limits_namespace = __esm({
14985
+ "../core/dist/common-auth-embedded/store/limits-namespace.js"() {
14986
+ "use strict";
14987
+ init_atomic_write2();
14988
+ init_hooks();
14989
+ init_mutate();
14990
+ }
14991
+ });
14992
+
14863
14993
  // ../core/dist/common-auth-embedded/store/provider-state.js
14864
14994
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
14865
14995
  if (!codec)
@@ -14873,7 +15003,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
14873
15003
  }
14874
15004
  if (normalized === void 0)
14875
15005
  throw refusal2(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
14876
- if (!codec.validate(normalized))
15006
+ if (!runInsideCodec(() => codec.validate(normalized)))
14877
15007
  throw refusal2(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
14878
15008
  return normalized;
14879
15009
  }
@@ -14882,18 +15012,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
14882
15012
  return { kind: "set", value: incoming };
14883
15013
  return {
14884
15014
  kind: "set",
14885
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), "the merged provider state")
15015
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), "the merged provider state")
14886
15016
  };
14887
15017
  }
14888
15018
  function replacementProviderState(codec, row, credentialEpoch2, identity3, incoming) {
14889
15019
  const hook = codec?.onReplace;
14890
- const next = hook ? hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
15020
+ const next = hook ? runInsideCodec(() => hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
14891
15021
  id: row.id,
14892
15022
  credentialEpoch: credentialEpoch2,
14893
15023
  ...row.identity !== void 0 ? { previousIdentity: row.identity } : {},
14894
15024
  ...identity3 !== void 0 ? { identity: identity3 } : {},
14895
15025
  ...incoming !== void 0 ? { incoming: structuredClone(incoming) } : {}
14896
- }) : incoming;
15026
+ })) : incoming;
14897
15027
  if (next === void 0)
14898
15028
  return { kind: "clear" };
14899
15029
  if (!hook)
@@ -17153,7 +17283,7 @@ async function refreshRow(rt, id, provider2, options = {}) {
17153
17283
  if (options.onPersisted) {
17154
17284
  try {
17155
17285
  const persisted = options.onPersisted;
17156
- await runInsideHook("refresh", () => persisted(id, commit.stored));
17286
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
17157
17287
  } catch (cause) {
17158
17288
  throw new PoolOperationError({
17159
17289
  operation: "refresh",
@@ -17262,7 +17392,7 @@ function defineKey(target, key, value) {
17262
17392
  function composeConfig(config, next) {
17263
17393
  const out = {};
17264
17394
  for (const [key, value] of Object.entries(config)) {
17265
- if (POOL_OWNED_KEYS.includes(key))
17395
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
17266
17396
  defineKey(out, key, value);
17267
17397
  else if (Object.hasOwn(next, key))
17268
17398
  defineKey(out, key, next[key]);
@@ -17314,9 +17444,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
17314
17444
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
17315
17445
  if (owned.length > 0)
17316
17446
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
17317
- if (isDeepStrictEqual3(next, current))
17318
- return { settings: current, outcome: "unchanged" };
17447
+ if (Object.hasOwn(next, "commonAuthLimits") && (!Object.hasOwn(current, "commonAuthLimits") || !isDeepStrictEqual3(next.commonAuthLimits, current.commonAuthLimits)))
17448
+ throw settingsRefusal("settings cannot alter commonAuthLimits; use updateLimitsNamespace");
17319
17449
  const config = composeConfig(result.config, next);
17450
+ if (isDeepStrictEqual3(settingsOf2(config), current))
17451
+ return { settings: current, outcome: "unchanged" };
17320
17452
  const info = { operation: "updateSettings", rowId: void 0 };
17321
17453
  await writeJsonAtomic2(ctx.configPath, config, {
17322
17454
  beforeRename: async () => {
@@ -17451,6 +17583,7 @@ function openPoolStore(options) {
17451
17583
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
17452
17584
  readSettings: () => readPoolSettings(rt),
17453
17585
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
17586
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
17454
17587
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
17455
17588
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
17456
17589
  recordQuota: record3,
@@ -17465,6 +17598,7 @@ var init_pool = __esm({
17465
17598
  "../core/dist/common-auth-embedded/store/pool.js"() {
17466
17599
  "use strict";
17467
17600
  init_attribution();
17601
+ init_limits_namespace();
17468
17602
  init_mutate();
17469
17603
  init_provider_state();
17470
17604
  init_publication();
@@ -17570,7 +17704,7 @@ function exclusionFor(id, inputs, now) {
17570
17704
  }
17571
17705
  return void 0;
17572
17706
  }
17573
- function judgeStageOne(id, projection, requiredLabels, now) {
17707
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
17574
17708
  if (projection.limits.length === 0) {
17575
17709
  return {
17576
17710
  id,
@@ -17594,7 +17728,7 @@ function judgeStageOne(id, projection, requiredLabels, now) {
17594
17728
  }
17595
17729
  const exhausted = projection.limits.filter(readsExhausted);
17596
17730
  for (const limit of exhausted) {
17597
- if (futureResetAt(limit, now) === void 0) {
17731
+ if (futureResetAt(limit, now) === void 0 && !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
17598
17732
  return {
17599
17733
  id,
17600
17734
  stage: 1,
@@ -17627,6 +17761,7 @@ function admit(input2) {
17627
17761
  const excluded = [];
17628
17762
  const refused2 = [];
17629
17763
  const survivors = [];
17764
+ const needsPull = /* @__PURE__ */ new Set();
17630
17765
  for (const row of input2.rows) {
17631
17766
  const exclusion = exclusionFor(row.id, input2, input2.now);
17632
17767
  if (exclusion) {
@@ -17638,7 +17773,10 @@ function admit(input2) {
17638
17773
  continue;
17639
17774
  }
17640
17775
  const projection = projectQuota(row.quota, scope);
17641
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input2.now);
17776
+ const lifted = input2.liftedWindows?.get(row.id) ?? [];
17777
+ if (projection.limits.some((limit) => readsExhausted(limit) && futureResetAt(limit, input2.now) === void 0 && lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
17778
+ needsPull.add(row.id);
17779
+ const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input2.now, lifted);
17642
17780
  if (refusal3) {
17643
17781
  refused2.push(refusal3);
17644
17782
  continue;
@@ -17664,7 +17802,10 @@ function admit(input2) {
17664
17802
  const order = new Map(input2.rows.map((row, index) => [row.id, index]));
17665
17803
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
17666
17804
  refused2.sort(byInput);
17667
- const pulls = refused2.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
17805
+ for (const refusal3 of refused2)
17806
+ if ("pullRequested" in refusal3)
17807
+ needsPull.add(refusal3.id);
17808
+ const pulls = input2.rows.filter((row) => needsPull.has(row.id)).map((row) => row.id);
17668
17809
  for (const id of pulls)
17669
17810
  input2.requestPull?.(id);
17670
17811
  return { admitted, refused: refused2, excluded, pulls };
@@ -18635,6 +18776,44 @@ function routingSection2(options, snap) {
18635
18776
  return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
18636
18777
  }
18637
18778
  });
18779
+ if (options.routing?.sameAccountWait) {
18780
+ const waitLabel = "Longest wait on the same account";
18781
+ const waitChoices = [
18782
+ { value: "0", label: "Don't wait" },
18783
+ { value: "15", label: "15 minutes" },
18784
+ { value: "max", label: "Until the cache expires" }
18785
+ ];
18786
+ const rawWait = record(snap.settings.routing).maxSameAccountWait;
18787
+ const wait2 = String(rawWait === 0 || rawWait === "max" ? rawWait : 15);
18788
+ const waitName = (value) => waitChoices.find((choice) => choice.value === value)?.label ?? value;
18789
+ lines.push(`${waitLabel}: ${waitName(wait2)}`);
18790
+ actions.push({
18791
+ id: "maxSameAccountWait",
18792
+ label: waitLabel,
18793
+ group: ACTIONS_GROUP,
18794
+ knobs: [
18795
+ {
18796
+ kind: "choice",
18797
+ id: "maxSameAccountWait",
18798
+ label: waitLabel,
18799
+ choices: waitChoices,
18800
+ value: wait2
18801
+ }
18802
+ ],
18803
+ run: async ({ values }) => {
18804
+ const value = String(values.maxSameAccountWait);
18805
+ const maxSameAccountWait = value === "max" ? "max" : Number(value);
18806
+ await store.updateSettings((settings) => {
18807
+ settings.routing = {
18808
+ ...record(settings.routing),
18809
+ maxSameAccountWait
18810
+ };
18811
+ return void 0;
18812
+ }, locks);
18813
+ return `${waitLabel} set to ${waitName(value)}.`;
18814
+ }
18815
+ });
18816
+ }
18638
18817
  return {
18639
18818
  id: "routing",
18640
18819
  slot: "routing",
@@ -21699,9 +21878,144 @@ var init_shutdown = __esm({
21699
21878
  }
21700
21879
  });
21701
21880
 
21881
+ // ../core/dist/common-auth-embedded/claustrum/usage.js
21882
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
21883
+ function plain(value) {
21884
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
21885
+ }
21886
+ var ScopedUsageReporter;
21887
+ var init_usage = __esm({
21888
+ "../core/dist/common-auth-embedded/claustrum/usage.js"() {
21889
+ "use strict";
21890
+ ScopedUsageReporter = class {
21891
+ options;
21892
+ #queue = /* @__PURE__ */ new Map();
21893
+ #latest = /* @__PURE__ */ new Map();
21894
+ #errors = /* @__PURE__ */ new Set();
21895
+ #timer;
21896
+ #running;
21897
+ #closing = false;
21898
+ #stopped = false;
21899
+ #dropped = 0;
21900
+ constructor(options) {
21901
+ this.options = options;
21902
+ }
21903
+ state() {
21904
+ return {
21905
+ pending: this.#queue.size,
21906
+ inFlight: this.#running !== void 0,
21907
+ dropped: this.#dropped
21908
+ };
21909
+ }
21910
+ report(credentialId, reading) {
21911
+ if (this.#closing || !this.options.client.reportUsageScoped)
21912
+ return;
21913
+ try {
21914
+ if (!this.options.owns(credentialId)) {
21915
+ this.#dropped++;
21916
+ return;
21917
+ }
21918
+ if (!plain(reading) || "credentialId" in reading || "vouched" in reading)
21919
+ throw new Error("invalid reading");
21920
+ const json = JSON.stringify(reading);
21921
+ if (Buffer.byteLength(json, "utf8") > 15360)
21922
+ throw new Error("oversized reading");
21923
+ const copy = JSON.parse(json);
21924
+ if (!plain(copy) || "credentialId" in copy || "vouched" in copy || typeof copy.observedAtMs !== "number" || !Number.isFinite(copy.observedAtMs))
21925
+ throw new Error("invalid reading");
21926
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
21927
+ this.#dropped++;
21928
+ return;
21929
+ }
21930
+ if (this.#queue.has(credentialId))
21931
+ this.#dropped++;
21932
+ this.#latest.set(credentialId, copy.observedAtMs);
21933
+ this.#queue.set(credentialId, copy);
21934
+ if (!this.#timer && !this.#running) {
21935
+ this.#timer = this.options.setTimeout(() => {
21936
+ this.#timer = void 0;
21937
+ this.#flush();
21938
+ }, 1e3);
21939
+ this.#timer.unref?.();
21940
+ }
21941
+ } catch {
21942
+ this.#dropped++;
21943
+ }
21944
+ }
21945
+ forget(credentialId) {
21946
+ if (this.#queue.delete(credentialId))
21947
+ this.#dropped++;
21948
+ this.#latest.delete(credentialId);
21949
+ }
21950
+ #flush() {
21951
+ if (this.#running || !this.#queue.size || this.#stopped)
21952
+ return this.#running;
21953
+ const running = Promise.resolve().then(async () => {
21954
+ while (!this.#stopped && this.#queue.size) {
21955
+ const entry = this.#queue.entries().next().value;
21956
+ if (!entry)
21957
+ break;
21958
+ const [credentialId, reading] = entry;
21959
+ this.#queue.delete(credentialId);
21960
+ try {
21961
+ const enrollmentToken = await this.options.token();
21962
+ if (this.#stopped || !this.options.owns(credentialId)) {
21963
+ if (!this.#stopped)
21964
+ this.#dropped++;
21965
+ continue;
21966
+ }
21967
+ await this.options.client.reportUsageScoped?.({
21968
+ credentialId,
21969
+ reading,
21970
+ enrollmentToken
21971
+ });
21972
+ } catch (error) {
21973
+ if (!this.#stopped)
21974
+ this.#dropped++;
21975
+ this.#log(error);
21976
+ }
21977
+ }
21978
+ });
21979
+ this.#running = running;
21980
+ void running.finally(() => {
21981
+ this.#running = void 0;
21982
+ });
21983
+ return running;
21984
+ }
21985
+ #log(error) {
21986
+ let code2 = "transport_error";
21987
+ try {
21988
+ if (error instanceof ClaustrumCredentialError3)
21989
+ code2 = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code2;
21990
+ if (this.#errors.has(code2))
21991
+ return;
21992
+ this.#errors.add(code2);
21993
+ this.options.logger.debug("claustrum usage report dropped", { code: code2 });
21994
+ } catch {
21995
+ }
21996
+ }
21997
+ /** Start the final flush; the custody's existing shutdown drain bounds it. */
21998
+ close() {
21999
+ this.#closing = true;
22000
+ if (this.#timer)
22001
+ this.options.clearTimeout(this.#timer);
22002
+ this.#timer = void 0;
22003
+ return this.#flush();
22004
+ }
22005
+ drop() {
22006
+ this.#stopped = true;
22007
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
22008
+ this.#running = void 0;
22009
+ this.#queue.clear();
22010
+ this.#latest.clear();
22011
+ }
22012
+ };
22013
+ }
22014
+ });
22015
+
21702
22016
  // ../core/dist/common-auth-embedded/claustrum/custody.js
21703
22017
  import { channel } from "node:diagnostics_channel";
21704
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
22018
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
21705
22019
  function isScopedCredentialRotation(served, current) {
21706
22020
  return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
21707
22021
  }
@@ -21716,6 +22030,12 @@ function scopedRetryReason(served, current) {
21716
22030
  return "version-unchanged";
21717
22031
  return "rotated";
21718
22032
  }
22033
+ function checkedEnrollmentToken(value) {
22034
+ if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
22035
+ throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
22036
+ }
22037
+ return value.token;
22038
+ }
21719
22039
  function decideScopedRetryAfter401(site, served, current, logger3 = defaultLogger) {
21720
22040
  const retry = isScopedCredentialRotation(served, current);
21721
22041
  logger3.debug("scoped 401 re-authorized", {
@@ -21824,6 +22144,7 @@ var init_custody = __esm({
21824
22144
  init_errors2();
21825
22145
  init_host_slot();
21826
22146
  init_shutdown();
22147
+ init_usage();
21827
22148
  init_watch();
21828
22149
  defaultLogger = createLogger2("claustrum");
21829
22150
  phaseDiagnostics = channel("common-auth.claustrum.phases");
@@ -21841,6 +22162,8 @@ var init_custody = __esm({
21841
22162
  #reports = /* @__PURE__ */ new WeakMap();
21842
22163
  #kept = /* @__PURE__ */ new Map();
21843
22164
  #keptAttempts = /* @__PURE__ */ new WeakMap();
22165
+ #usage;
22166
+ #usageServed = /* @__PURE__ */ new Map();
21844
22167
  #setTimeout;
21845
22168
  #clearTimeout;
21846
22169
  #outage = false;
@@ -21855,6 +22178,7 @@ var init_custody = __esm({
21855
22178
  #watches = /* @__PURE__ */ new Set();
21856
22179
  #tokenReads = /* @__PURE__ */ new Set();
21857
22180
  #warnShutdown;
22181
+ #onDrainTimeout;
21858
22182
  #disposing;
21859
22183
  constructor(options) {
21860
22184
  const tokenPath = options.tokenPath;
@@ -21874,13 +22198,21 @@ var init_custody = __esm({
21874
22198
  this.#warnShutdown = shutdownWarning(this.#logger);
21875
22199
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
21876
22200
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
22201
+ this.#usage = new ScopedUsageReporter({
22202
+ client: this.#client,
22203
+ owns: (id) => this.#usageServed.has(id),
22204
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
22205
+ logger: this.#logger,
22206
+ setTimeout: this.#setTimeout,
22207
+ clearTimeout: this.#clearTimeout
22208
+ });
21877
22209
  }
21878
22210
  /** A watch losing its transport is the same outage as an unreachable read. */
21879
22211
  transportLost(error) {
21880
22212
  if (this.#closed || this.#outage)
21881
22213
  return;
21882
22214
  this.#outage = true;
21883
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
22215
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError();
21884
22216
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
21885
22217
  this.#scheduleProbe();
21886
22218
  }
@@ -21949,10 +22281,7 @@ var init_custody = __esm({
21949
22281
  });
21950
22282
  }
21951
22283
  this.#check(signal);
21952
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
21953
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
21954
- }
21955
- return value.token;
22284
+ return checkedEnrollmentToken(value);
21956
22285
  }
21957
22286
  async #call(operation, signal) {
21958
22287
  this.#check(signal);
@@ -21976,7 +22305,7 @@ var init_custody = __esm({
21976
22305
  this.transportLost(error);
21977
22306
  else
21978
22307
  this.reachable();
21979
- if (error instanceof ClaustrumCredentialError3)
22308
+ if (error instanceof ClaustrumCredentialError4)
21980
22309
  throw error;
21981
22310
  if (classifyVaultFailure(error) === "unreachable")
21982
22311
  throw new ClaustrumUnreachableError();
@@ -22006,6 +22335,7 @@ var init_custody = __esm({
22006
22335
  token = await this.#token(signal);
22007
22336
  } catch (error) {
22008
22337
  this.#kept.clear();
22338
+ this.#clearUsageOwnership();
22009
22339
  throw error;
22010
22340
  }
22011
22341
  if (phaseDiagnostics.hasSubscribers)
@@ -22107,11 +22437,19 @@ var init_custody = __esm({
22107
22437
  else {
22108
22438
  this.reachable();
22109
22439
  this.#kept.clear();
22440
+ this.#clearUsageOwnership();
22110
22441
  }
22111
22442
  }
22112
22443
  /** Discard bearer material when a route is removed, declined or rebound. */
22113
22444
  forget(credentialId) {
22114
22445
  this.#kept.delete(credentialId);
22446
+ this.#usageServed.delete(credentialId);
22447
+ this.#usage.forget(credentialId);
22448
+ }
22449
+ #clearUsageOwnership() {
22450
+ for (const id of this.#usageServed.keys())
22451
+ this.#usage.forget(id);
22452
+ this.#usageServed.clear();
22115
22453
  }
22116
22454
  /** Apply an already-held roster; this never fetches credentials or writes it. */
22117
22455
  retain(identities) {
@@ -22121,6 +22459,11 @@ var init_custody = __esm({
22121
22459
  if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== kept.attempt.credentialType || identity3.accountIdentity !== kept.attempt.expectedAccountIdentity)
22122
22460
  this.forget(id);
22123
22461
  }
22462
+ for (const [id, served] of this.#usageServed) {
22463
+ const identity3 = current.get(id);
22464
+ if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== served.credentialType || identity3.accountIdentity !== served.accountIdentity)
22465
+ this.forget(id);
22466
+ }
22124
22467
  }
22125
22468
  /** A frozen, non-secret summary for a plugin's status display. */
22126
22469
  keptReceiptState() {
@@ -22152,6 +22495,7 @@ var init_custody = __esm({
22152
22495
  token = await this.#token(signal);
22153
22496
  } catch (error) {
22154
22497
  this.#kept.clear();
22498
+ this.#clearUsageOwnership();
22155
22499
  throw error;
22156
22500
  }
22157
22501
  if (this.#outage && kept) {
@@ -22161,6 +22505,7 @@ var init_custody = __esm({
22161
22505
  try {
22162
22506
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
22163
22507
  this.#kept.set(credentialId, { attempt, routeId, since: null });
22508
+ this.#usageServed.set(credentialId, { ...identity3 });
22164
22509
  return attempt;
22165
22510
  } catch (error) {
22166
22511
  this.#check(signal);
@@ -22345,6 +22690,23 @@ var init_custody = __esm({
22345
22690
  }
22346
22691
  };
22347
22692
  }
22693
+ /**
22694
+ * Queue reply quota metadata and return synchronously. Pass rate-limit
22695
+ * headers only, never tokens: the library does not filter header names.
22696
+ * Only credentials served by this custody and retained in its roster report.
22697
+ * Hosts managing their own roster must call retain() when that roster changes.
22698
+ */
22699
+ reportUsage(input2) {
22700
+ if (this.#closed)
22701
+ return;
22702
+ try {
22703
+ this.#usage.report(input2.credentialId, input2.reading);
22704
+ } catch {
22705
+ }
22706
+ }
22707
+ usageReportState() {
22708
+ return this.#usage.state();
22709
+ }
22348
22710
  close() {
22349
22711
  if (this.#closed)
22350
22712
  return;
@@ -22356,12 +22718,23 @@ var init_custody = __esm({
22356
22718
  watch.stop();
22357
22719
  this.#watches.clear();
22358
22720
  this.#kept.clear();
22359
- this.#client.close();
22721
+ const usage = this.#usage.close();
22722
+ if (usage) {
22723
+ this.#tokenReads.add(usage);
22724
+ void usage.then(() => this.#tokenReads.delete(usage));
22725
+ } else
22726
+ this.#client.close();
22727
+ this.#disposing = drainShutdown(this.#tokenReads, (count3) => (this.#onDrainTimeout ?? this.#warnShutdown)(count3)).finally(() => {
22728
+ this.#usage.drop();
22729
+ this.#usageServed.clear();
22730
+ if (usage)
22731
+ this.#client.close();
22732
+ });
22360
22733
  }
22361
- /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
22734
+ /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
22362
22735
  async dispose(onTimeout = this.#warnShutdown) {
22736
+ this.#onDrainTimeout = onTimeout;
22363
22737
  this.close();
22364
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
22365
22738
  await this.#disposing;
22366
22739
  }
22367
22740
  };
@@ -22602,6 +22975,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
22602
22975
  return {
22603
22976
  version: 1,
22604
22977
  view: inventory.view,
22978
+ ...previous?.limits !== void 0 && { limits: previous.limits },
22605
22979
  complete,
22606
22980
  ...!complete && {
22607
22981
  rejected: inventory.skipped.map((record3) => ({
@@ -22672,6 +23046,7 @@ function decodeRoster(value) {
22672
23046
  // that was used whole, so it reads as complete.
22673
23047
  complete: value.complete !== false,
22674
23048
  ...rejected && { rejected },
23049
+ ...value.limits !== void 0 && { limits: value.limits },
22675
23050
  rows,
22676
23051
  declined
22677
23052
  };
@@ -23883,6 +24258,33 @@ var init_consumer = __esm({
23883
24258
  combined.dispose();
23884
24259
  }
23885
24260
  }
24261
+ /**
24262
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
24263
+ * headers only, never tokens: the library does not filter header names.
24264
+ * The credential must have been served by this host and still belong to the route.
24265
+ */
24266
+ reportUsage(input2) {
24267
+ if (this.#shutdown.signal.aborted)
24268
+ return;
24269
+ try {
24270
+ const row = this.#roster?.rows.find((row2) => row2.routeId === input2.routeId);
24271
+ if (!row?.enabled || row.state !== "active" || row.credentialId !== input2.credentialId && !row.aliases?.includes(input2.credentialId))
24272
+ return;
24273
+ if (this.#hub) {
24274
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
24275
+ this.#lease.custody.reportUsage(input2);
24276
+ } else
24277
+ this.#custody?.reportUsage(input2);
24278
+ } catch {
24279
+ }
24280
+ }
24281
+ usageReportState() {
24282
+ try {
24283
+ return (this.#hub ? this.#lease?.custody : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 };
24284
+ } catch {
24285
+ return { pending: 0, inFlight: false, dropped: 0 };
24286
+ }
24287
+ }
23886
24288
  async reportFailure(attempt, status, source) {
23887
24289
  this.#assertOpen();
23888
24290
  if (this.#hub) {
@@ -24494,6 +24896,14 @@ var init_hub = __esm({
24494
24896
  check();
24495
24897
  return custody.reportFailure(attempt, status, source);
24496
24898
  },
24899
+ reportUsage: (input2) => {
24900
+ if (!state.released && !generation.ended)
24901
+ custody.reportUsage(input2);
24902
+ },
24903
+ usageReportState: () => {
24904
+ check();
24905
+ return custody.usageReportState();
24906
+ },
24497
24907
  forget: (credentialId) => {
24498
24908
  check();
24499
24909
  custody.forget(credentialId);
@@ -25037,7 +25447,7 @@ __export(claustrum_exports, {
25037
25447
  ChangeNoticeReader: () => ChangeNoticeReader,
25038
25448
  ClaustrumConsumer: () => ClaustrumConsumer,
25039
25449
  ClaustrumConsumerError: () => ClaustrumConsumerError,
25040
- ClaustrumCredentialError: () => ClaustrumCredentialError4,
25450
+ ClaustrumCredentialError: () => ClaustrumCredentialError5,
25041
25451
  ClaustrumDiscoveryHub: () => ClaustrumDiscoveryHub,
25042
25452
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
25043
25453
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
@@ -25094,7 +25504,7 @@ __export(claustrum_exports, {
25094
25504
  vaultRoutingRows: () => vaultRoutingRows
25095
25505
  });
25096
25506
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
25097
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
25507
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
25098
25508
  async function connectClaustrumScopedClient(options) {
25099
25509
  const { connectTimeoutMs, ...client } = options;
25100
25510
  const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
@@ -29008,6 +29418,9 @@ function loadBackend2() {
29008
29418
  });
29009
29419
  return backend2;
29010
29420
  }
29421
+ function isWindowsSharingViolation2(error) {
29422
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
29423
+ }
29011
29424
  async function privateOperation2(path5, stage, operation) {
29012
29425
  try {
29013
29426
  return await operation();
@@ -32435,7 +32848,8 @@ async function removeOldCopies(location, files, present5, layoutLock, input2) {
32435
32848
  if (!await unlinkIfIdentical(
32436
32849
  file,
32437
32850
  location.stateHomeDir,
32438
- () => beforeRemove(file.old, layoutLock, input2.steps)
32851
+ () => beforeRemove(file.old, layoutLock, input2.steps),
32852
+ input2.steps?.oldFileIO
32439
32853
  ))
32440
32854
  kept.push(file.old);
32441
32855
  }
@@ -32457,21 +32871,21 @@ async function sameBytes(a, b) {
32457
32871
  return false;
32458
32872
  }
32459
32873
  }
32460
- function isWindowsSharingError(error) {
32874
+ function isWindowsSharingError(error, platform) {
32461
32875
  const code2 = error?.code;
32462
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32876
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32463
32877
  }
32464
- async function unlinkIfIdentical(file, stateDir, guard) {
32878
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink10 }) {
32465
32879
  const started = performance.now();
32466
32880
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
32467
32881
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
32468
32882
  let same;
32469
32883
  try {
32470
- same = (await readFile12(file.old)).equals(await readFile12(file.next));
32884
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
32471
32885
  } catch (error) {
32472
32886
  if (error.code === "ENOENT" && !await exists2(file.old))
32473
32887
  return true;
32474
- if (isWindowsSharingError(error)) {
32888
+ if (isWindowsSharingError(error, io.platform)) {
32475
32889
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
32476
32890
  continue;
32477
32891
  }
@@ -32480,11 +32894,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32480
32894
  if (!same) throw credentialConflict(stateDir, file);
32481
32895
  await guard();
32482
32896
  try {
32483
- await unlink10(file.old);
32897
+ await io.unlink(file.old);
32484
32898
  return true;
32485
32899
  } catch (error) {
32486
32900
  if (error.code === "ENOENT") return true;
32487
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32901
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32488
32902
  return false;
32489
32903
  }
32490
32904
  }
@@ -36647,7 +37061,7 @@ import { createHash as createHash13, randomBytes as randomBytes5, randomUUID as
36647
37061
  import { constants as fsConstants2 } from "node:fs";
36648
37062
  import { chmod as chmod6, mkdir as mkdir15, open as open10, readFile as readFile14, realpath as realpath4, rename as rename12, stat as stat12, unlink as unlink11 } from "node:fs/promises";
36649
37063
  import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute4, join as join20, resolve as resolve19 } from "node:path";
36650
- import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
37064
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
36651
37065
 
36652
37066
  // src/common-auth-embedded/fs/file-read-cache.js
36653
37067
  import { lstat as lstat7 } from "node:fs/promises";
@@ -37022,37 +37436,83 @@ async function acquireRefreshFileLockWithClock2(options) {
37022
37436
  await rm6(path5, { recursive: true, force: true }).catch(() => {
37023
37437
  });
37024
37438
  }
37025
- async function releaseEvictionMarker() {
37026
- if (await ownsEvictionMarker()) {
37027
- await removeLeaseObject(evictPath);
37028
- }
37439
+ function isRetryableRemoval(error, path5) {
37440
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path5)
37441
+ return false;
37442
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
37443
+ }
37444
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
37445
+ let original;
37446
+ let delayMs = 5;
37447
+ while (await stillOwned()) {
37448
+ try {
37449
+ await removeLeaseObject(path5);
37450
+ return;
37451
+ } catch (error) {
37452
+ if (!isRetryableRemoval(error, path5))
37453
+ throw error;
37454
+ original ??= error;
37455
+ }
37456
+ const remainingMs = deadline - performance.now();
37457
+ if (remainingMs <= 0)
37458
+ throw original;
37459
+ await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
37460
+ if (performance.now() >= deadline)
37461
+ throw original;
37462
+ delayMs = Math.min(delayMs * 2, 50);
37463
+ }
37464
+ }
37465
+ async function releaseEvictionMarker(deadline) {
37466
+ let ownedDirectory;
37467
+ await removeOwnedLeaseObject(evictPath, async () => {
37468
+ if (!windowsPrivateFiles2)
37469
+ return ownsEvictionMarker();
37470
+ const current = await lstat8(evictPath).catch((error) => {
37471
+ if (error.code !== "ENOENT")
37472
+ throw error;
37473
+ return void 0;
37474
+ });
37475
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
37476
+ return false;
37477
+ if (await ownsEvictionMarker()) {
37478
+ ownedDirectory = current;
37479
+ return true;
37480
+ }
37481
+ if (!ownedDirectory)
37482
+ return false;
37483
+ try {
37484
+ await stat11(evictOwnerPath);
37485
+ return false;
37486
+ } catch (error) {
37487
+ if (error.code !== "ENOENT")
37488
+ throw error;
37489
+ return true;
37490
+ }
37491
+ }, deadline);
37029
37492
  }
37030
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
37493
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
37031
37494
  if (!created)
37032
37495
  return false;
37033
- let current;
37034
- try {
37035
- const st = await lstat8(evictPath);
37036
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
37037
- } catch {
37038
- return false;
37039
- }
37040
- if (!sameMarkerDirectory2(created, current))
37041
- return false;
37496
+ let stillOurs = false;
37042
37497
  try {
37043
- await stat11(evictOwnerPath);
37044
- return true;
37045
- } catch (error) {
37046
- if (error.code !== "ENOENT")
37047
- return true;
37048
- }
37049
- try {
37050
- await removeLeaseObject(evictPath);
37498
+ await removeOwnedLeaseObject(evictPath, async () => {
37499
+ stillOurs = false;
37500
+ const st = await lstat8(evictPath).catch(() => void 0);
37501
+ if (!st || !sameMarkerDirectory2(created, st))
37502
+ return false;
37503
+ stillOurs = true;
37504
+ try {
37505
+ await stat11(evictOwnerPath);
37506
+ return false;
37507
+ } catch (error) {
37508
+ return error.code === "ENOENT";
37509
+ }
37510
+ }, deadline);
37051
37511
  } catch {
37052
37512
  }
37053
- return true;
37513
+ return stillOurs;
37054
37514
  }
37055
- async function tryAcquireEvictionMarker() {
37515
+ async function tryAcquireEvictionMarker(deadline) {
37056
37516
  if (windowsPrivateFiles2)
37057
37517
  await createPrivateDirectoryExclusive2(evictPath);
37058
37518
  else
@@ -37076,11 +37536,11 @@ async function acquireRefreshFileLockWithClock2(options) {
37076
37536
  else
37077
37537
  await createExclusiveText2(evictOwnerPath, bytes);
37078
37538
  } catch (error) {
37079
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
37539
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
37080
37540
  if (isLostMarkerRaceError2(error) && !stillOurs)
37081
37541
  return false;
37082
37542
  try {
37083
- await releaseEvictionMarker();
37543
+ await releaseEvictionMarker(deadline);
37084
37544
  } catch {
37085
37545
  }
37086
37546
  throw error;
@@ -37089,7 +37549,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37089
37549
  await options.onStep("eviction-marker-acquired");
37090
37550
  return true;
37091
37551
  }
37092
- async function recoverStaleEvictionMarker() {
37552
+ async function recoverStaleEvictionMarker(deadline) {
37093
37553
  let evictStat;
37094
37554
  try {
37095
37555
  evictStat = await stat11(evictPath);
@@ -37134,12 +37594,22 @@ async function acquireRefreshFileLockWithClock2(options) {
37134
37594
  }
37135
37595
  if (options.onStep)
37136
37596
  await options.onStep("stale-marker-claimed");
37137
- await removeLeaseObject(claimedPath);
37597
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
37598
+ await removeOwnedLeaseObject(claimedPath, async () => {
37599
+ if (!claimedIdentity)
37600
+ return true;
37601
+ const current = await lstat8(claimedPath).catch((error) => {
37602
+ if (error.code !== "ENOENT")
37603
+ throw error;
37604
+ return void 0;
37605
+ });
37606
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
37607
+ }, deadline);
37138
37608
  return "recovered";
37139
37609
  }
37140
- async function withEvictionMarker(action) {
37610
+ async function withEvictionMarker(action, deadline) {
37141
37611
  try {
37142
- if (!await tryAcquireEvictionMarker())
37612
+ if (!await tryAcquireEvictionMarker(deadline))
37143
37613
  return false;
37144
37614
  } catch (error) {
37145
37615
  if (error.code === "EEXIST") {
@@ -37156,11 +37626,23 @@ async function acquireRefreshFileLockWithClock2(options) {
37156
37626
  }
37157
37627
  throw error;
37158
37628
  }
37629
+ let actionFailed = false;
37630
+ let actionError;
37159
37631
  try {
37160
37632
  await action();
37161
- } finally {
37162
- await releaseEvictionMarker();
37633
+ } catch (error) {
37634
+ actionFailed = true;
37635
+ actionError = error;
37636
+ }
37637
+ try {
37638
+ await releaseEvictionMarker(deadline);
37639
+ } catch (error) {
37640
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
37641
+ throw actionError;
37642
+ throw error;
37163
37643
  }
37644
+ if (actionFailed)
37645
+ throw actionError;
37164
37646
  return true;
37165
37647
  }
37166
37648
  async function relinquishLockAfterMarkerLoss() {
@@ -37397,6 +37879,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37397
37879
  await renewalInFlight;
37398
37880
  const deadline = performance.now() + EVICT_TTL + 1e3;
37399
37881
  let delayMs = 5;
37882
+ let removalError;
37400
37883
  for (; ; ) {
37401
37884
  try {
37402
37885
  let removalConfirmed = false;
@@ -37421,7 +37904,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37421
37904
  return;
37422
37905
  await removeLeaseObject(lockPath);
37423
37906
  removalConfirmed = true;
37424
- });
37907
+ }, deadline);
37425
37908
  if (markerAcquired) {
37426
37909
  if (windowsPrivateFiles2 && !removalConfirmed)
37427
37910
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -37432,20 +37915,25 @@ async function acquireRefreshFileLockWithClock2(options) {
37432
37915
  }
37433
37916
  if (signal?.aborted)
37434
37917
  return;
37435
- await recoverStaleEvictionMarker();
37918
+ await recoverStaleEvictionMarker(deadline);
37436
37919
  } catch (error) {
37437
- if (windowsPrivateFiles2)
37438
- throw error;
37439
- return;
37920
+ if (!isRetryableRemoval(error, lockPath)) {
37921
+ if (windowsPrivateFiles2)
37922
+ throw error;
37923
+ return;
37924
+ }
37925
+ removalError ??= error;
37440
37926
  }
37441
37927
  const remainingMs = deadline - performance.now();
37442
37928
  if (remainingMs <= 0)
37443
37929
  break;
37444
37930
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
37931
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
37932
+ break;
37445
37933
  delayMs = Math.min(delayMs * 2, 50);
37446
37934
  }
37447
37935
  if (windowsPrivateFiles2)
37448
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
37936
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
37449
37937
  code: "ETIMEDOUT"
37450
37938
  });
37451
37939
  }
@@ -37488,7 +37976,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
37488
37976
  "pending_queue_full"
37489
37977
  ]);
37490
37978
  function classifyEnrollmentError2(error) {
37491
- if (!(error instanceof ClaustrumCredentialError5))
37979
+ if (!(error instanceof ClaustrumCredentialError6))
37492
37980
  return void 0;
37493
37981
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
37494
37982
  return { code: error.code, disposition: "terminal" };
@@ -39679,7 +40167,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39679
40167
  }
39680
40168
  };
39681
40169
  let openCodeLogin;
39682
- let hasLocalPool = false;
40170
+ const nativeNextStep = (label) => {
40171
+ deps.stdout.write(
40172
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
40173
+ Setup has not completed the OpenCode 2 native Google connection.
40174
+ `
40175
+ );
40176
+ };
39683
40177
  const manifest = JSON.parse(
39684
40178
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
39685
40179
  );
@@ -39737,18 +40231,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39737
40231
  await assertLocal(host, context);
39738
40232
  if (host === "opencode" && context.opencodeGeneration === "2") {
39739
40233
  if (!forceLogin) {
39740
- try {
39741
- const source2 = await deps.accountStore.read(
39742
- deps.accountStore.legacyPath()
39743
- );
39744
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
39745
- if (candidateAccounts.some(
39746
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39747
- )) {
39748
- hasLocalPool = true;
39749
- }
39750
- } catch {
39751
- }
40234
+ const source2 = await deps.accountStore.read(
40235
+ deps.accountStore.legacyPath()
40236
+ );
40237
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
39752
40238
  }
39753
40239
  return;
39754
40240
  }
@@ -39763,11 +40249,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39763
40249
  `Using existing local Antigravity login for ${host}.
39764
40250
  `
39765
40251
  );
39766
- if (host === "opencode" && accounts.some(
39767
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39768
- )) {
39769
- hasLocalPool = true;
39770
- }
39771
40252
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
39772
40253
  const account = accounts[0];
39773
40254
  await writeNativeSlot(
@@ -39800,18 +40281,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39800
40281
  );
39801
40282
  if (host === "opencode") {
39802
40283
  openCodeLogin = result;
39803
- hasLocalPool = true;
39804
40284
  }
39805
40285
  },
39806
40286
  beforeRegister: async (host, mode, context) => {
39807
40287
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
39808
- const nativeNextStep = (label) => {
39809
- deps.stdout.write(
39810
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
39811
- Setup has not completed the OpenCode 2 native Google connection.
39812
- `
39813
- );
39814
- };
39815
40288
  if (mode === "local") {
39816
40289
  await assertLocal(host, context);
39817
40290
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -39825,10 +40298,6 @@ Setup has not completed the OpenCode 2 native Google connection.
39825
40298
  },
39826
40299
  context
39827
40300
  );
39828
- if (needsOpenCode2)
39829
- nativeNextStep(
39830
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
39831
- );
39832
40301
  return;
39833
40302
  }
39834
40303
  if (await authority(host) !== "vault")
@@ -39899,11 +40368,28 @@ Setup has not completed the OpenCode 2 native Google connection.
39899
40368
  await publishedGeneration(stateAnchor),
39900
40369
  stateAnchor
39901
40370
  );
39902
- return;
40371
+ } else {
40372
+ if (await migrateOpenCode() !== 0)
40373
+ throw new Error("Offline Antigravity account migration failed.");
40374
+ await deps.prepareVaultFolder?.();
40375
+ }
40376
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
40377
+ let reconnectReady = false;
40378
+ if (!forceLogin || context.opencodeGeneration !== "2") {
40379
+ if (source.kind === "store") {
40380
+ reconnectReady = source.reconnectReady;
40381
+ } else if (source.kind === "legacy") {
40382
+ const post = await deps.accountStore.read(
40383
+ deps.accountStore.legacyPath()
40384
+ );
40385
+ if (post.kind === "unavailable") throw new Error(post.reason);
40386
+ reconnectReady = post.kind === "store" && post.reconnectReady;
40387
+ }
40388
+ }
40389
+ nativeNextStep(
40390
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
40391
+ );
39903
40392
  }
39904
- if (await migrateOpenCode() !== 0)
39905
- throw new Error("Offline Antigravity account migration failed.");
39906
- await deps.prepareVaultFolder?.();
39907
40393
  } else {
39908
40394
  deps.stdout.write(
39909
40395
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -40495,6 +40981,7 @@ async function readAccountStore(legacyPath) {
40495
40981
  case "bound":
40496
40982
  break;
40497
40983
  }
40984
+ const generationId = admission.receipt.id;
40498
40985
  const repository = createAccountRepositoryFactory(modules)({
40499
40986
  paths: admission.paths,
40500
40987
  now: Date.now,
@@ -40508,6 +40995,12 @@ async function readAccountStore(legacyPath) {
40508
40995
  }
40509
40996
  });
40510
40997
  try {
40998
+ const servingBefore = await readAccountStoreAdmission(
40999
+ legacyPath,
41000
+ modules,
41001
+ Date.now,
41002
+ generationId
41003
+ );
40511
41004
  const read = await repository.read();
40512
41005
  if (read.status !== "ready") {
40513
41006
  return {
@@ -40515,7 +41008,20 @@ async function readAccountStore(legacyPath) {
40515
41008
  reason: `the account store is ${read.status}`
40516
41009
  };
40517
41010
  }
40518
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
41011
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
41012
+ legacyPath,
41013
+ modules,
41014
+ Date.now,
41015
+ generationId
41016
+ ) : servingBefore;
41017
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
41018
+ (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
41019
+ );
41020
+ return {
41021
+ kind: "store",
41022
+ accounts: read.rows.map(cliAccountOf),
41023
+ reconnectReady
41024
+ };
40519
41025
  } finally {
40520
41026
  await repository.dispose();
40521
41027
  }
@@ -41065,7 +41571,30 @@ function isSessionId(value) {
41065
41571
  init_private_files2();
41066
41572
  import { createHash as createHash15, randomUUID as randomUUID19 } from "node:crypto";
41067
41573
  import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir4, rename as rename14, rmdir as rmdir3, stat as stat15, unlink as unlink13 } from "node:fs/promises";
41574
+ import { uptime as uptime2 } from "node:os";
41068
41575
  import { join as join29, resolve as resolve23 } from "node:path";
41576
+ function staleBefore(clock2) {
41577
+ return (clock2.now ?? Date.now)() - (clock2.uptime ?? uptime2)() * 1e3 - 3e5;
41578
+ }
41579
+ function isStalePortFile(entry, info, cutoff) {
41580
+ const time = entry.startedAt === void 0 ? info?.mtimeMs : entry.startedAt;
41581
+ return typeof time === "number" && Number.isFinite(time) && time < cutoff;
41582
+ }
41583
+ async function removeStalePortFile(path5, raw, info, beforeRemove2) {
41584
+ if (!info)
41585
+ return;
41586
+ await beforeRemove2?.(path5);
41587
+ try {
41588
+ const current = await readPrivateText2(path5);
41589
+ const identity3 = await stat15(path5);
41590
+ if (current === raw && identity3.dev === info.dev && identity3.ino === info.ino && identity3.mtimeMs === info.mtimeMs && identity3.size === info.size)
41591
+ await unlink13(path5).catch(() => {
41592
+ });
41593
+ } catch (error) {
41594
+ if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
41595
+ throw error;
41596
+ }
41597
+ }
41069
41598
  function isProbeablePid(pid) {
41070
41599
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
41071
41600
  }
@@ -41143,7 +41672,8 @@ async function writePortFile(dir, entry, options = {}) {
41143
41672
  throw error;
41144
41673
  }
41145
41674
  }
41146
- async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41675
+ async function sweepRpcState(root, activeDir, isManagedDir, log17, options = {}) {
41676
+ const cutoff = staleBefore(options);
41147
41677
  let projectDirs;
41148
41678
  try {
41149
41679
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -41170,6 +41700,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41170
41700
  if (!name.startsWith("port-") || !name.endsWith(".json"))
41171
41701
  continue;
41172
41702
  const portFile = join29(dir, name);
41703
+ const info = await stat15(portFile).catch(() => void 0);
41173
41704
  let raw;
41174
41705
  try {
41175
41706
  raw = await readPrivateText2(portFile);
@@ -41195,6 +41726,8 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41195
41726
  if (!pidAlive2(entry.pid))
41196
41727
  await unlink13(portFile).catch(() => {
41197
41728
  });
41729
+ else if (isStalePortFile(entry, info, cutoff))
41730
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
41198
41731
  }
41199
41732
  if (resolve23(dir) !== active2)
41200
41733
  await rmdir3(dir).catch(() => {
@@ -53789,16 +54322,18 @@ init_logger4();
53789
54322
  init_dist();
53790
54323
  import { createHash as createHash23 } from "node:crypto";
53791
54324
 
53792
- // src/common-auth-embedded/routing-accessor/index.js
53793
- function isObject2(value) {
53794
- return typeof value === "object" && value !== null;
53795
- }
54325
+ // src/common-auth-embedded/routing-accessor/handle.js
53796
54326
  function routingHandle(sessionId) {
53797
54327
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
53798
54328
  if (typeof routing !== "function")
53799
54329
  return void 0;
53800
54330
  const handle = routing(sessionId);
53801
- return isObject2(handle) ? handle : void 0;
54331
+ return typeof handle === "object" && handle !== null ? handle : void 0;
54332
+ }
54333
+
54334
+ // src/common-auth-embedded/routing-accessor/index.js
54335
+ function isObject2(value) {
54336
+ return typeof value === "object" && value !== null;
53802
54337
  }
53803
54338
  function selectionFor(answer, candidates) {
53804
54339
  if (!isObject2(answer))
@@ -53835,7 +54370,15 @@ async function askRouting(input2) {
53835
54370
  timer = setTimeout(() => resolve27(void 0), deadlineMs);
53836
54371
  timer.unref();
53837
54372
  });
53838
- const pending = accountFor.call(handle, { provider: input2.provider, modelId: input2.modelId }, { deadlineMs });
54373
+ const request = {
54374
+ provider: input2.provider,
54375
+ modelId: input2.modelId
54376
+ };
54377
+ const cap = input2.holdWaitMaxS;
54378
+ if (typeof cap === "number" && Number.isFinite(cap)) {
54379
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
54380
+ }
54381
+ const pending = accountFor.call(handle, request, { deadlineMs });
53839
54382
  if (!isObject2(pending) || typeof pending.then !== "function")
53840
54383
  return void 0;
53841
54384
  const answer = await Promise.race([pending, expired]);
@@ -53867,7 +54410,7 @@ function reportRouting(input2) {
53867
54410
  const { window, pool } = input2;
53868
54411
  if (window !== "5h" && window !== "7d")
53869
54412
  return;
53870
- if (pool !== void 0 && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
54413
+ if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
53871
54414
  return;
53872
54415
  payload = {
53873
54416
  ...identity3,