@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/server.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");
12966
+ }
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((resolve28) => setTimeout(resolve28, 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);
12921
13015
  }
12922
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
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((resolve28) => setTimeout(resolve28, 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;
@@ -29001,6 +29411,9 @@ function loadBackend2() {
29001
29411
  });
29002
29412
  return backend2;
29003
29413
  }
29414
+ function isWindowsSharingViolation2(error) {
29415
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
29416
+ }
29004
29417
  async function privateOperation2(path5, stage, operation) {
29005
29418
  try {
29006
29419
  return await operation();
@@ -32339,7 +32752,8 @@ async function removeOldCopies(location, files, present6, layoutLock, input2) {
32339
32752
  if (!await unlinkIfIdentical(
32340
32753
  file,
32341
32754
  location.stateHomeDir,
32342
- () => beforeRemove(file.old, layoutLock, input2.steps)
32755
+ () => beforeRemove(file.old, layoutLock, input2.steps),
32756
+ input2.steps?.oldFileIO
32343
32757
  ))
32344
32758
  kept.push(file.old);
32345
32759
  }
@@ -32361,21 +32775,21 @@ async function sameBytes(a, b) {
32361
32775
  return false;
32362
32776
  }
32363
32777
  }
32364
- function isWindowsSharingError(error) {
32778
+ function isWindowsSharingError(error, platform) {
32365
32779
  const code2 = error?.code;
32366
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32780
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32367
32781
  }
32368
- async function unlinkIfIdentical(file, stateDir, guard) {
32782
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink10 }) {
32369
32783
  const started = performance.now();
32370
32784
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
32371
32785
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
32372
32786
  let same;
32373
32787
  try {
32374
- same = (await readFile12(file.old)).equals(await readFile12(file.next));
32788
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
32375
32789
  } catch (error) {
32376
32790
  if (error.code === "ENOENT" && !await exists2(file.old))
32377
32791
  return true;
32378
- if (isWindowsSharingError(error)) {
32792
+ if (isWindowsSharingError(error, io.platform)) {
32379
32793
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
32380
32794
  continue;
32381
32795
  }
@@ -32384,11 +32798,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32384
32798
  if (!same) throw credentialConflict(stateDir, file);
32385
32799
  await guard();
32386
32800
  try {
32387
- await unlink10(file.old);
32801
+ await io.unlink(file.old);
32388
32802
  return true;
32389
32803
  } catch (error) {
32390
32804
  if (error.code === "ENOENT") return true;
32391
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32805
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32392
32806
  return false;
32393
32807
  }
32394
32808
  }
@@ -34157,9 +34571,6 @@ async function registerOpenCode2AuthMethods(ctx, options) {
34157
34571
  });
34158
34572
  }
34159
34573
 
34160
- // src/common-auth-embedded/opencode2/install.js
34161
- var MAX_RETRY_HOLD_MS = 20 * 60 * 1e3;
34162
-
34163
34574
  // src/plugin/ga-location-services.ts
34164
34575
  init_dist();
34165
34576
  init_vault_folder();
@@ -44681,16 +45092,18 @@ async function retainResponseLifetime(response, cancellation) {
44681
45092
  init_dist();
44682
45093
  import { createHash as createHash17 } from "node:crypto";
44683
45094
 
44684
- // src/common-auth-embedded/routing-accessor/index.js
44685
- function isObject2(value) {
44686
- return typeof value === "object" && value !== null;
44687
- }
45095
+ // src/common-auth-embedded/routing-accessor/handle.js
44688
45096
  function routingHandle(sessionId) {
44689
45097
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
44690
45098
  if (typeof routing !== "function")
44691
45099
  return void 0;
44692
45100
  const handle = routing(sessionId);
44693
- return isObject2(handle) ? handle : void 0;
45101
+ return typeof handle === "object" && handle !== null ? handle : void 0;
45102
+ }
45103
+
45104
+ // src/common-auth-embedded/routing-accessor/index.js
45105
+ function isObject2(value) {
45106
+ return typeof value === "object" && value !== null;
44694
45107
  }
44695
45108
  function selectionFor(answer, candidates) {
44696
45109
  if (!isObject2(answer))
@@ -44727,7 +45140,15 @@ async function askRouting(input2) {
44727
45140
  timer = setTimeout(() => resolve28(void 0), deadlineMs);
44728
45141
  timer.unref();
44729
45142
  });
44730
- const pending = accountFor.call(handle, { provider: input2.provider, modelId: input2.modelId }, { deadlineMs });
45143
+ const request = {
45144
+ provider: input2.provider,
45145
+ modelId: input2.modelId
45146
+ };
45147
+ const cap = input2.holdWaitMaxS;
45148
+ if (typeof cap === "number" && Number.isFinite(cap)) {
45149
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
45150
+ }
45151
+ const pending = accountFor.call(handle, request, { deadlineMs });
44731
45152
  if (!isObject2(pending) || typeof pending.then !== "function")
44732
45153
  return void 0;
44733
45154
  const answer = await Promise.race([pending, expired]);
@@ -44759,7 +45180,7 @@ function reportRouting(input2) {
44759
45180
  const { window, pool } = input2;
44760
45181
  if (window !== "5h" && window !== "7d")
44761
45182
  return;
44762
- if (pool !== void 0 && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
45183
+ if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
44763
45184
  return;
44764
45185
  payload = {
44765
45186
  ...identity3,
@@ -53219,7 +53640,7 @@ import { createHash as createHash19, randomBytes as randomBytes6, randomUUID as
53219
53640
  import { constants as fsConstants2 } from "node:fs";
53220
53641
  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";
53221
53642
  import { basename as basename6, dirname as dirname22, extname as extname2, isAbsolute as isAbsolute4, join as join26, resolve as resolve22 } from "node:path";
53222
- import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
53643
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
53223
53644
 
53224
53645
  // src/common-auth-embedded/fs/file-read-cache.js
53225
53646
  import { lstat as lstat7 } from "node:fs/promises";
@@ -53594,37 +54015,83 @@ async function acquireRefreshFileLockWithClock2(options) {
53594
54015
  await rm6(path5, { recursive: true, force: true }).catch(() => {
53595
54016
  });
53596
54017
  }
53597
- async function releaseEvictionMarker() {
53598
- if (await ownsEvictionMarker()) {
53599
- await removeLeaseObject(evictPath);
53600
- }
54018
+ function isRetryableRemoval(error, path5) {
54019
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path5)
54020
+ return false;
54021
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
54022
+ }
54023
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
54024
+ let original;
54025
+ let delayMs = 5;
54026
+ while (await stillOwned()) {
54027
+ try {
54028
+ await removeLeaseObject(path5);
54029
+ return;
54030
+ } catch (error) {
54031
+ if (!isRetryableRemoval(error, path5))
54032
+ throw error;
54033
+ original ??= error;
54034
+ }
54035
+ const remainingMs = deadline - performance.now();
54036
+ if (remainingMs <= 0)
54037
+ throw original;
54038
+ await new Promise((resolve28) => setTimeout(resolve28, Math.min(delayMs, remainingMs)));
54039
+ if (performance.now() >= deadline)
54040
+ throw original;
54041
+ delayMs = Math.min(delayMs * 2, 50);
54042
+ }
54043
+ }
54044
+ async function releaseEvictionMarker(deadline) {
54045
+ let ownedDirectory;
54046
+ await removeOwnedLeaseObject(evictPath, async () => {
54047
+ if (!windowsPrivateFiles2)
54048
+ return ownsEvictionMarker();
54049
+ const current = await lstat8(evictPath).catch((error) => {
54050
+ if (error.code !== "ENOENT")
54051
+ throw error;
54052
+ return void 0;
54053
+ });
54054
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
54055
+ return false;
54056
+ if (await ownsEvictionMarker()) {
54057
+ ownedDirectory = current;
54058
+ return true;
54059
+ }
54060
+ if (!ownedDirectory)
54061
+ return false;
54062
+ try {
54063
+ await stat11(evictOwnerPath);
54064
+ return false;
54065
+ } catch (error) {
54066
+ if (error.code !== "ENOENT")
54067
+ throw error;
54068
+ return true;
54069
+ }
54070
+ }, deadline);
53601
54071
  }
53602
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
54072
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
53603
54073
  if (!created)
53604
54074
  return false;
53605
- let current;
53606
- try {
53607
- const st = await lstat8(evictPath);
53608
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
53609
- } catch {
53610
- return false;
53611
- }
53612
- if (!sameMarkerDirectory2(created, current))
53613
- return false;
53614
- try {
53615
- await stat11(evictOwnerPath);
53616
- return true;
53617
- } catch (error) {
53618
- if (error.code !== "ENOENT")
53619
- return true;
53620
- }
54075
+ let stillOurs = false;
53621
54076
  try {
53622
- await removeLeaseObject(evictPath);
54077
+ await removeOwnedLeaseObject(evictPath, async () => {
54078
+ stillOurs = false;
54079
+ const st = await lstat8(evictPath).catch(() => void 0);
54080
+ if (!st || !sameMarkerDirectory2(created, st))
54081
+ return false;
54082
+ stillOurs = true;
54083
+ try {
54084
+ await stat11(evictOwnerPath);
54085
+ return false;
54086
+ } catch (error) {
54087
+ return error.code === "ENOENT";
54088
+ }
54089
+ }, deadline);
53623
54090
  } catch {
53624
54091
  }
53625
- return true;
54092
+ return stillOurs;
53626
54093
  }
53627
- async function tryAcquireEvictionMarker() {
54094
+ async function tryAcquireEvictionMarker(deadline) {
53628
54095
  if (windowsPrivateFiles2)
53629
54096
  await createPrivateDirectoryExclusive2(evictPath);
53630
54097
  else
@@ -53648,11 +54115,11 @@ async function acquireRefreshFileLockWithClock2(options) {
53648
54115
  else
53649
54116
  await createExclusiveText2(evictOwnerPath, bytes);
53650
54117
  } catch (error) {
53651
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
54118
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
53652
54119
  if (isLostMarkerRaceError2(error) && !stillOurs)
53653
54120
  return false;
53654
54121
  try {
53655
- await releaseEvictionMarker();
54122
+ await releaseEvictionMarker(deadline);
53656
54123
  } catch {
53657
54124
  }
53658
54125
  throw error;
@@ -53661,7 +54128,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53661
54128
  await options.onStep("eviction-marker-acquired");
53662
54129
  return true;
53663
54130
  }
53664
- async function recoverStaleEvictionMarker() {
54131
+ async function recoverStaleEvictionMarker(deadline) {
53665
54132
  let evictStat;
53666
54133
  try {
53667
54134
  evictStat = await stat11(evictPath);
@@ -53706,12 +54173,22 @@ async function acquireRefreshFileLockWithClock2(options) {
53706
54173
  }
53707
54174
  if (options.onStep)
53708
54175
  await options.onStep("stale-marker-claimed");
53709
- await removeLeaseObject(claimedPath);
54176
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
54177
+ await removeOwnedLeaseObject(claimedPath, async () => {
54178
+ if (!claimedIdentity)
54179
+ return true;
54180
+ const current = await lstat8(claimedPath).catch((error) => {
54181
+ if (error.code !== "ENOENT")
54182
+ throw error;
54183
+ return void 0;
54184
+ });
54185
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
54186
+ }, deadline);
53710
54187
  return "recovered";
53711
54188
  }
53712
- async function withEvictionMarker(action) {
54189
+ async function withEvictionMarker(action, deadline) {
53713
54190
  try {
53714
- if (!await tryAcquireEvictionMarker())
54191
+ if (!await tryAcquireEvictionMarker(deadline))
53715
54192
  return false;
53716
54193
  } catch (error) {
53717
54194
  if (error.code === "EEXIST") {
@@ -53728,11 +54205,23 @@ async function acquireRefreshFileLockWithClock2(options) {
53728
54205
  }
53729
54206
  throw error;
53730
54207
  }
54208
+ let actionFailed = false;
54209
+ let actionError;
53731
54210
  try {
53732
54211
  await action();
53733
- } finally {
53734
- await releaseEvictionMarker();
54212
+ } catch (error) {
54213
+ actionFailed = true;
54214
+ actionError = error;
53735
54215
  }
54216
+ try {
54217
+ await releaseEvictionMarker(deadline);
54218
+ } catch (error) {
54219
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
54220
+ throw actionError;
54221
+ throw error;
54222
+ }
54223
+ if (actionFailed)
54224
+ throw actionError;
53736
54225
  return true;
53737
54226
  }
53738
54227
  async function relinquishLockAfterMarkerLoss() {
@@ -53969,6 +54458,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53969
54458
  await renewalInFlight;
53970
54459
  const deadline = performance.now() + EVICT_TTL + 1e3;
53971
54460
  let delayMs = 5;
54461
+ let removalError;
53972
54462
  for (; ; ) {
53973
54463
  try {
53974
54464
  let removalConfirmed = false;
@@ -53993,7 +54483,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53993
54483
  return;
53994
54484
  await removeLeaseObject(lockPath);
53995
54485
  removalConfirmed = true;
53996
- });
54486
+ }, deadline);
53997
54487
  if (markerAcquired) {
53998
54488
  if (windowsPrivateFiles2 && !removalConfirmed)
53999
54489
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -54004,20 +54494,25 @@ async function acquireRefreshFileLockWithClock2(options) {
54004
54494
  }
54005
54495
  if (signal?.aborted)
54006
54496
  return;
54007
- await recoverStaleEvictionMarker();
54497
+ await recoverStaleEvictionMarker(deadline);
54008
54498
  } catch (error) {
54009
- if (windowsPrivateFiles2)
54010
- throw error;
54011
- return;
54499
+ if (!isRetryableRemoval(error, lockPath)) {
54500
+ if (windowsPrivateFiles2)
54501
+ throw error;
54502
+ return;
54503
+ }
54504
+ removalError ??= error;
54012
54505
  }
54013
54506
  const remainingMs = deadline - performance.now();
54014
54507
  if (remainingMs <= 0)
54015
54508
  break;
54016
54509
  await new Promise((resolve28) => setTimeout(resolve28, Math.min(delayMs, remainingMs)));
54510
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
54511
+ break;
54017
54512
  delayMs = Math.min(delayMs * 2, 50);
54018
54513
  }
54019
54514
  if (windowsPrivateFiles2)
54020
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
54515
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
54021
54516
  code: "ETIMEDOUT"
54022
54517
  });
54023
54518
  }
@@ -54060,7 +54555,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
54060
54555
  "pending_queue_full"
54061
54556
  ]);
54062
54557
  function classifyEnrollmentError2(error) {
54063
- if (!(error instanceof ClaustrumCredentialError5))
54558
+ if (!(error instanceof ClaustrumCredentialError6))
54064
54559
  return void 0;
54065
54560
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
54066
54561
  return { code: error.code, disposition: "terminal" };
@@ -56251,7 +56746,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56251
56746
  }
56252
56747
  };
56253
56748
  let openCodeLogin;
56254
- let hasLocalPool = false;
56749
+ const nativeNextStep = (label) => {
56750
+ deps.stdout.write(
56751
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
56752
+ Setup has not completed the OpenCode 2 native Google connection.
56753
+ `
56754
+ );
56755
+ };
56255
56756
  const manifest = JSON.parse(
56256
56757
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
56257
56758
  );
@@ -56309,18 +56810,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56309
56810
  await assertLocal(host, context);
56310
56811
  if (host === "opencode" && context.opencodeGeneration === "2") {
56311
56812
  if (!forceLogin) {
56312
- try {
56313
- const source2 = await deps.accountStore.read(
56314
- deps.accountStore.legacyPath()
56315
- );
56316
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
56317
- if (candidateAccounts.some(
56318
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
56319
- )) {
56320
- hasLocalPool = true;
56321
- }
56322
- } catch {
56323
- }
56813
+ const source2 = await deps.accountStore.read(
56814
+ deps.accountStore.legacyPath()
56815
+ );
56816
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
56324
56817
  }
56325
56818
  return;
56326
56819
  }
@@ -56335,11 +56828,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56335
56828
  `Using existing local Antigravity login for ${host}.
56336
56829
  `
56337
56830
  );
56338
- if (host === "opencode" && accounts.some(
56339
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
56340
- )) {
56341
- hasLocalPool = true;
56342
- }
56343
56831
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
56344
56832
  const account = accounts[0];
56345
56833
  await writeNativeSlot(
@@ -56372,18 +56860,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56372
56860
  );
56373
56861
  if (host === "opencode") {
56374
56862
  openCodeLogin = result;
56375
- hasLocalPool = true;
56376
56863
  }
56377
56864
  },
56378
56865
  beforeRegister: async (host, mode, context) => {
56379
56866
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
56380
- const nativeNextStep = (label) => {
56381
- deps.stdout.write(
56382
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
56383
- Setup has not completed the OpenCode 2 native Google connection.
56384
- `
56385
- );
56386
- };
56387
56867
  if (mode === "local") {
56388
56868
  await assertLocal(host, context);
56389
56869
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -56397,10 +56877,6 @@ Setup has not completed the OpenCode 2 native Google connection.
56397
56877
  },
56398
56878
  context
56399
56879
  );
56400
- if (needsOpenCode2)
56401
- nativeNextStep(
56402
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
56403
- );
56404
56880
  return;
56405
56881
  }
56406
56882
  if (await authority(host) !== "vault")
@@ -56471,11 +56947,28 @@ Setup has not completed the OpenCode 2 native Google connection.
56471
56947
  await publishedGeneration(stateAnchor),
56472
56948
  stateAnchor
56473
56949
  );
56474
- return;
56950
+ } else {
56951
+ if (await migrateOpenCode() !== 0)
56952
+ throw new Error("Offline Antigravity account migration failed.");
56953
+ await deps.prepareVaultFolder?.();
56954
+ }
56955
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
56956
+ let reconnectReady = false;
56957
+ if (!forceLogin || context.opencodeGeneration !== "2") {
56958
+ if (source.kind === "store") {
56959
+ reconnectReady = source.reconnectReady;
56960
+ } else if (source.kind === "legacy") {
56961
+ const post = await deps.accountStore.read(
56962
+ deps.accountStore.legacyPath()
56963
+ );
56964
+ if (post.kind === "unavailable") throw new Error(post.reason);
56965
+ reconnectReady = post.kind === "store" && post.reconnectReady;
56966
+ }
56967
+ }
56968
+ nativeNextStep(
56969
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
56970
+ );
56475
56971
  }
56476
- if (await migrateOpenCode() !== 0)
56477
- throw new Error("Offline Antigravity account migration failed.");
56478
- await deps.prepareVaultFolder?.();
56479
56972
  } else {
56480
56973
  deps.stdout.write(
56481
56974
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -57067,6 +57560,7 @@ async function readAccountStore(legacyPath) {
57067
57560
  case "bound":
57068
57561
  break;
57069
57562
  }
57563
+ const generationId = admission.receipt.id;
57070
57564
  const repository = createAccountRepositoryFactory(modules)({
57071
57565
  paths: admission.paths,
57072
57566
  now: Date.now,
@@ -57080,6 +57574,12 @@ async function readAccountStore(legacyPath) {
57080
57574
  }
57081
57575
  });
57082
57576
  try {
57577
+ const servingBefore = await readAccountStoreAdmission(
57578
+ legacyPath,
57579
+ modules,
57580
+ Date.now,
57581
+ generationId
57582
+ );
57083
57583
  const read = await repository.read();
57084
57584
  if (read.status !== "ready") {
57085
57585
  return {
@@ -57087,7 +57587,20 @@ async function readAccountStore(legacyPath) {
57087
57587
  reason: `the account store is ${read.status}`
57088
57588
  };
57089
57589
  }
57090
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
57590
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
57591
+ legacyPath,
57592
+ modules,
57593
+ Date.now,
57594
+ generationId
57595
+ ) : servingBefore;
57596
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
57597
+ (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
57598
+ );
57599
+ return {
57600
+ kind: "store",
57601
+ accounts: read.rows.map(cliAccountOf),
57602
+ reconnectReady
57603
+ };
57091
57604
  } finally {
57092
57605
  await repository.dispose();
57093
57606
  }
@@ -57637,7 +58150,30 @@ function isSessionId(value) {
57637
58150
  init_private_files2();
57638
58151
  import { createHash as createHash21, randomUUID as randomUUID21 } from "node:crypto";
57639
58152
  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";
58153
+ import { uptime as uptime2 } from "node:os";
57640
58154
  import { join as join35, resolve as resolve26 } from "node:path";
58155
+ function staleBefore(clock2) {
58156
+ return (clock2.now ?? Date.now)() - (clock2.uptime ?? uptime2)() * 1e3 - 3e5;
58157
+ }
58158
+ function isStalePortFile(entry, info, cutoff) {
58159
+ const time = entry.startedAt === void 0 ? info?.mtimeMs : entry.startedAt;
58160
+ return typeof time === "number" && Number.isFinite(time) && time < cutoff;
58161
+ }
58162
+ async function removeStalePortFile(path5, raw, info, beforeRemove2) {
58163
+ if (!info)
58164
+ return;
58165
+ await beforeRemove2?.(path5);
58166
+ try {
58167
+ const current = await readPrivateText2(path5);
58168
+ const identity3 = await stat15(path5);
58169
+ if (current === raw && identity3.dev === info.dev && identity3.ino === info.ino && identity3.mtimeMs === info.mtimeMs && identity3.size === info.size)
58170
+ await unlink13(path5).catch(() => {
58171
+ });
58172
+ } catch (error) {
58173
+ if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
58174
+ throw error;
58175
+ }
58176
+ }
57641
58177
  function isProbeablePid(pid) {
57642
58178
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
57643
58179
  }
@@ -57715,7 +58251,8 @@ async function writePortFile(dir, entry, options = {}) {
57715
58251
  throw error;
57716
58252
  }
57717
58253
  }
57718
- async function sweepRpcState(root, activeDir, isManagedDir, log17) {
58254
+ async function sweepRpcState(root, activeDir, isManagedDir, log17, options = {}) {
58255
+ const cutoff = staleBefore(options);
57719
58256
  let projectDirs;
57720
58257
  try {
57721
58258
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -57742,6 +58279,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
57742
58279
  if (!name.startsWith("port-") || !name.endsWith(".json"))
57743
58280
  continue;
57744
58281
  const portFile = join35(dir, name);
58282
+ const info = await stat15(portFile).catch(() => void 0);
57745
58283
  let raw;
57746
58284
  try {
57747
58285
  raw = await readPrivateText2(portFile);
@@ -57767,6 +58305,8 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
57767
58305
  if (!pidAlive2(entry.pid))
57768
58306
  await unlink13(portFile).catch(() => {
57769
58307
  });
58308
+ else if (isStalePortFile(entry, info, cutoff))
58309
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
57770
58310
  }
57771
58311
  if (resolve26(dir) !== active2)
57772
58312
  await rmdir3(dir).catch(() => {