@cortexkit/opencode-antigravity-auth 3.0.28 → 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 (179) hide show
  1. package/dist/cli.js +689 -183
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +131 -68
  4. package/dist/index.js +844 -199
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +173 -76
  7. package/dist/server.js +855 -213
  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/plugin/shared/request-services.d.ts +14 -18
  71. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  72. package/dist/src/plugin/shared/request-services.js +127 -7
  73. package/dist/src/plugin/shared/request-services.js.map +1 -1
  74. package/dist/src/runtime-layout.d.ts +9 -2
  75. package/dist/src/runtime-layout.d.ts.map +1 -1
  76. package/dist/src/runtime-layout.js +8 -8
  77. package/dist/src/runtime-layout.js.map +1 -1
  78. package/dist/src/setup.d.ts.map +1 -1
  79. package/dist/src/setup.js +29 -40
  80. package/dist/src/setup.js.map +1 -1
  81. package/dist/tui-build-map.json +9 -9
  82. package/dist/tui-ga-build-map.json +1 -1
  83. package/dist/types/src/cli.d.ts +1 -0
  84. package/dist/types/src/cli.d.ts.map +1 -1
  85. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  86. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  87. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  88. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  89. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  90. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  91. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  92. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  93. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +63 -0
  94. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +141 -0
  95. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  96. package/dist/types/src/common-auth-embedded/limits/families.d.ts +57 -0
  97. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +64 -0
  98. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  99. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  100. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  101. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  102. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  103. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  104. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  105. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  106. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  107. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  108. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  109. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  110. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  111. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  112. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  113. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  114. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  115. package/dist/types/src/plugin/shared/request-services.d.ts +14 -18
  116. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  117. package/dist/types/src/runtime-layout.d.ts +9 -2
  118. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  119. package/dist/types/src/setup.d.ts.map +1 -1
  120. package/package.json +2 -2
  121. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  122. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  123. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  124. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  125. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  126. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  127. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  128. package/src/common-auth-embedded/claustrum/roster.d.ts +2 -0
  129. package/src/common-auth-embedded/claustrum/roster.js +2 -0
  130. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  131. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  132. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  133. package/src/common-auth-embedded/commands/builtins.js +38 -0
  134. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  135. package/src/common-auth-embedded/fs/private-files.js +7 -0
  136. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  137. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  138. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  139. package/src/common-auth-embedded/limits/axes.d.ts +63 -0
  140. package/src/common-auth-embedded/limits/decide.d.ts +141 -0
  141. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  142. package/src/common-auth-embedded/limits/families.d.ts +57 -0
  143. package/src/common-auth-embedded/limits/marker.d.ts +64 -0
  144. package/src/common-auth-embedded/limits/request-history.d.ts +77 -0
  145. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  146. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  147. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  148. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  149. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  150. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  151. package/src/common-auth-embedded/opencode2/install.d.ts +2 -2
  152. package/src/common-auth-embedded/opencode2/install.js +161 -18
  153. package/src/common-auth-embedded/opencode2/types.d.ts +95 -9
  154. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  155. package/src/common-auth-embedded/routing/admission.js +17 -7
  156. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  157. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  158. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  159. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  160. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  161. package/src/common-auth-embedded/source-output.json +254 -118
  162. package/src/common-auth-embedded/store/attribution.js +3 -2
  163. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  164. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  165. package/src/common-auth-embedded/store/hooks.js +20 -5
  166. package/src/common-auth-embedded/store/index.d.ts +1 -0
  167. package/src/common-auth-embedded/store/limits-namespace.d.ts +7 -0
  168. package/src/common-auth-embedded/store/limits-namespace.js +34 -0
  169. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  170. package/src/common-auth-embedded/store/pool.js +2 -0
  171. package/src/common-auth-embedded/store/provider-state.js +5 -5
  172. package/src/common-auth-embedded/store/refresh.js +1 -1
  173. package/src/common-auth-embedded/store/schema.js +9 -4
  174. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  175. package/src/common-auth-embedded/store/settings.js +11 -4
  176. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  177. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  178. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  179. 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();
@@ -6632,6 +6635,15 @@ function resolveQuotaGroup(family, model, cachedQuota) {
6632
6635
  }
6633
6636
  return family === "claude" ? "non-gemini" : "gemini";
6634
6637
  }
6638
+ function reportsArgon(account) {
6639
+ return account.cachedQuotaUpdatedAt !== void 0 && account.cachedQuota?.["gemini-argon"] !== void 0;
6640
+ }
6641
+ function preferArgonAccounts(accounts, model) {
6642
+ if (!model || getQuotaGroupForModel(model, true) !== "gemini-argon")
6643
+ return accounts;
6644
+ const reporting = accounts.filter(reportsArgon);
6645
+ return reporting.length > 0 ? reporting : accounts;
6646
+ }
6635
6647
  function isOverSoftQuotaThreshold(account, family, thresholdPercent, cacheTtlMs, now, model) {
6636
6648
  if (thresholdPercent >= 100)
6637
6649
  return false;
@@ -7106,7 +7118,10 @@ var init_account_selector = __esm({
7106
7118
  };
7107
7119
  });
7108
7120
  const currentIndex = this.getActiveIndex(family, identity3);
7109
- const selectedIndex = selectHybridAccount(accountsWithMetrics, tokenTracker, currentIndex, 50, this.now);
7121
+ const preferred2 = preferArgonAccounts(eligibleAccounts, model);
7122
+ const preferredIndexes = new Set(preferred2.map((row) => row.index));
7123
+ const select4 = (candidates) => selectHybridAccount(candidates, tokenTracker, currentIndex, 50, this.now);
7124
+ const selectedIndex = select4(accountsWithMetrics.filter((row) => preferredIndexes.has(row.index))) ?? select4(accountsWithMetrics);
7110
7125
  if (selectedIndex !== null) {
7111
7126
  const selected = this.accounts[selectedIndex];
7112
7127
  if (selected) {
@@ -7134,7 +7149,8 @@ var init_account_selector = __esm({
7134
7149
  offsetApplied[family] = true;
7135
7150
  }
7136
7151
  const current = this.getCurrentAccountForFamily(family, identity3);
7137
- if (current && !excludeIndexes?.has(current.index)) {
7152
+ const preferred = preferArgonAccounts(this.accounts.filter((row) => row.enabled !== false && !row.accountIneligible && !row.verificationRequired && !excludeIndexes?.has(row.index) && !isRateLimitedForFamily(row, family, this.now, model) && !this.isAccountCoolingDown(row) && !isOverSoftQuotaThreshold(row, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model)), model);
7153
+ if (current && preferred.includes(current)) {
7138
7154
  clearExpiredRateLimits(current, this.now);
7139
7155
  const isLimitedForRequestedStyle = isRateLimitedForFamily(current, family, this.now, model);
7140
7156
  const isOverThreshold = isOverSoftQuotaThreshold(current, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model);
@@ -7156,7 +7172,7 @@ var init_account_selector = __esm({
7156
7172
  clearExpiredRateLimits(account2, this.now);
7157
7173
  return account2.enabled !== false && account2.accountIneligible !== true && account2.verificationRequired !== true && !excludeIndexes?.has(account2.index) && !isRateLimitedForFamily(account2, family, this.now, model) && !isOverSoftQuotaThreshold(account2, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model) && !this.isAccountCoolingDown(account2);
7158
7174
  });
7159
- const available = this.preferAccountOutsideParent(allAvailable, family, identity3);
7175
+ const available = this.preferAccountOutsideParent(preferArgonAccounts(allAvailable, model), family, identity3);
7160
7176
  if (available.length === 0) {
7161
7177
  return null;
7162
7178
  }
@@ -12520,6 +12536,48 @@ var init_identity = __esm({
12520
12536
  }
12521
12537
  });
12522
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
+
12523
12581
  // ../core/dist/common-auth-embedded/fs/atomic-write.js
12524
12582
  import { randomUUID as randomUUID8 } from "node:crypto";
12525
12583
  import { mkdir as mkdir6, open as open3, rename as rename5, rm as rm3 } from "node:fs/promises";
@@ -12901,37 +12959,83 @@ async function acquireRefreshFileLockWithClock(options) {
12901
12959
  await rm4(path5, { recursive: true, force: true }).catch(() => {
12902
12960
  });
12903
12961
  }
12904
- async function releaseEvictionMarker() {
12905
- if (await ownsEvictionMarker()) {
12906
- await removeLeaseObject(evictPath);
12907
- }
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");
12908
12966
  }
12909
- 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) {
12910
13017
  if (!created)
12911
13018
  return false;
12912
- let current;
12913
- try {
12914
- const st = await lstat3(evictPath);
12915
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
12916
- } catch {
12917
- return false;
12918
- }
12919
- if (!sameMarkerDirectory(created, current))
12920
- return false;
13019
+ let stillOurs = false;
12921
13020
  try {
12922
- await stat3(evictOwnerPath);
12923
- return true;
12924
- } catch (error) {
12925
- if (error.code !== "ENOENT")
12926
- return true;
12927
- }
12928
- try {
12929
- 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);
12930
13034
  } catch {
12931
13035
  }
12932
- return true;
13036
+ return stillOurs;
12933
13037
  }
12934
- async function tryAcquireEvictionMarker() {
13038
+ async function tryAcquireEvictionMarker(deadline) {
12935
13039
  if (windowsPrivateFiles)
12936
13040
  await createPrivateDirectoryExclusive(evictPath);
12937
13041
  else
@@ -12955,11 +13059,11 @@ async function acquireRefreshFileLockWithClock(options) {
12955
13059
  else
12956
13060
  await createExclusiveText(evictOwnerPath, bytes);
12957
13061
  } catch (error) {
12958
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
13062
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
12959
13063
  if (isLostMarkerRaceError(error) && !stillOurs)
12960
13064
  return false;
12961
13065
  try {
12962
- await releaseEvictionMarker();
13066
+ await releaseEvictionMarker(deadline);
12963
13067
  } catch {
12964
13068
  }
12965
13069
  throw error;
@@ -12968,7 +13072,7 @@ async function acquireRefreshFileLockWithClock(options) {
12968
13072
  await options.onStep("eviction-marker-acquired");
12969
13073
  return true;
12970
13074
  }
12971
- async function recoverStaleEvictionMarker() {
13075
+ async function recoverStaleEvictionMarker(deadline) {
12972
13076
  let evictStat;
12973
13077
  try {
12974
13078
  evictStat = await stat3(evictPath);
@@ -13013,12 +13117,22 @@ async function acquireRefreshFileLockWithClock(options) {
13013
13117
  }
13014
13118
  if (options.onStep)
13015
13119
  await options.onStep("stale-marker-claimed");
13016
- 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);
13017
13131
  return "recovered";
13018
13132
  }
13019
- async function withEvictionMarker(action) {
13133
+ async function withEvictionMarker(action, deadline) {
13020
13134
  try {
13021
- if (!await tryAcquireEvictionMarker())
13135
+ if (!await tryAcquireEvictionMarker(deadline))
13022
13136
  return false;
13023
13137
  } catch (error) {
13024
13138
  if (error.code === "EEXIST") {
@@ -13035,11 +13149,23 @@ async function acquireRefreshFileLockWithClock(options) {
13035
13149
  }
13036
13150
  throw error;
13037
13151
  }
13152
+ let actionFailed = false;
13153
+ let actionError;
13038
13154
  try {
13039
13155
  await action();
13040
- } finally {
13041
- 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;
13042
13166
  }
13167
+ if (actionFailed)
13168
+ throw actionError;
13043
13169
  return true;
13044
13170
  }
13045
13171
  async function relinquishLockAfterMarkerLoss() {
@@ -13276,6 +13402,7 @@ async function acquireRefreshFileLockWithClock(options) {
13276
13402
  await renewalInFlight;
13277
13403
  const deadline = performance.now() + EVICT_TTL + 1e3;
13278
13404
  let delayMs = 5;
13405
+ let removalError;
13279
13406
  for (; ; ) {
13280
13407
  try {
13281
13408
  let removalConfirmed = false;
@@ -13300,7 +13427,7 @@ async function acquireRefreshFileLockWithClock(options) {
13300
13427
  return;
13301
13428
  await removeLeaseObject(lockPath);
13302
13429
  removalConfirmed = true;
13303
- });
13430
+ }, deadline);
13304
13431
  if (markerAcquired) {
13305
13432
  if (windowsPrivateFiles && !removalConfirmed)
13306
13433
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -13311,20 +13438,25 @@ async function acquireRefreshFileLockWithClock(options) {
13311
13438
  }
13312
13439
  if (signal?.aborted)
13313
13440
  return;
13314
- await recoverStaleEvictionMarker();
13441
+ await recoverStaleEvictionMarker(deadline);
13315
13442
  } catch (error) {
13316
- if (windowsPrivateFiles)
13317
- throw error;
13318
- return;
13443
+ if (!isRetryableRemoval(error, lockPath)) {
13444
+ if (windowsPrivateFiles)
13445
+ throw error;
13446
+ return;
13447
+ }
13448
+ removalError ??= error;
13319
13449
  }
13320
13450
  const remainingMs = deadline - performance.now();
13321
13451
  if (remainingMs <= 0)
13322
13452
  break;
13323
13453
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
13454
+ if (windowsPrivateFiles && performance.now() >= deadline)
13455
+ break;
13324
13456
  delayMs = Math.min(delayMs * 2, 50);
13325
13457
  }
13326
13458
  if (windowsPrivateFiles)
13327
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
13459
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
13328
13460
  code: "ETIMEDOUT"
13329
13461
  });
13330
13462
  }
@@ -13348,7 +13480,7 @@ function lockPathFor(target, name) {
13348
13480
  return `${target}.${name}.lock`;
13349
13481
  }
13350
13482
  function isChangingLockRead(error, target, name) {
13351
- 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")
13352
13484
  return false;
13353
13485
  const path5 = resolve3(lockPathFor(target, name));
13354
13486
  return error.path === path5 || error.path === join6(path5, "owner.json");
@@ -13420,37 +13552,6 @@ var init_with_lock = __esm({
13420
13552
  }
13421
13553
  });
13422
13554
 
13423
- // ../core/dist/common-auth-embedded/store/hooks.js
13424
- import { AsyncLocalStorage } from "node:async_hooks";
13425
- function assertNotInsideHook(operation) {
13426
- if (insideHook.getStore() !== void 0)
13427
- throw new PoolReentryError(operation);
13428
- }
13429
- function runInsideHook(operation, fn) {
13430
- return insideHook.run(operation, async () => await fn());
13431
- }
13432
- async function callFailureHook(operation, hook, rowId2, error, logger3) {
13433
- if (!hook)
13434
- return;
13435
- try {
13436
- await runInsideHook(operation, () => hook(rowId2, error));
13437
- } catch (hookError) {
13438
- logger3?.warn("store failure hook threw; the original failure stands", {
13439
- operation,
13440
- rowId: rowId2,
13441
- error: hookError instanceof Error ? hookError.message : String(hookError)
13442
- });
13443
- }
13444
- }
13445
- var insideHook;
13446
- var init_hooks = __esm({
13447
- "../core/dist/common-auth-embedded/store/hooks.js"() {
13448
- "use strict";
13449
- init_errors();
13450
- insideHook = new AsyncLocalStorage();
13451
- }
13452
- });
13453
-
13454
13555
  // ../core/dist/common-auth-embedded/store/refresh-lock.js
13455
13556
  async function acquirePoolLock(spec, defaults, env3) {
13456
13557
  const emit = (type) => {
@@ -13682,7 +13783,7 @@ function stampFor(credential, credentialEpoch2, binding, options = {}) {
13682
13783
  };
13683
13784
  }
13684
13785
  function providerStateDigest(codec, value) {
13685
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
13786
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
13686
13787
  return createHash5("sha256").update(`provider-state\0${JSON.stringify(bound ?? null)}`).digest("hex");
13687
13788
  }
13688
13789
  function boundProviderStateDigest(account, credential, credentialEpoch2, identity3) {
@@ -13849,8 +13950,8 @@ function parseEntry(raw, codec) {
13849
13950
  return void 0;
13850
13951
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
13851
13952
  return void 0;
13852
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
13853
- 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)))
13854
13955
  return void 0;
13855
13956
  if ("staged" in raw && !parseReservation(raw.staged))
13856
13957
  return void 0;
@@ -14022,7 +14123,7 @@ function providerStateFields(account, credential, credentialEpoch2, identity3, c
14022
14123
  if (digest3 === void 0)
14023
14124
  return { providerStateDropped: "uncovered" };
14024
14125
  const value = account[PROVIDER_STATE_KEY];
14025
- if (!codec?.validate(value))
14126
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
14026
14127
  return { providerStateDropped: "invalid" };
14027
14128
  if (providerStateDigest(codec, value) !== digest3)
14028
14129
  return { providerStateDropped: "uncovered" };
@@ -14099,6 +14200,7 @@ var POOL_KEY, POOL_SCHEMA_VERSION, POOL_ROWS_KEY, POOL_RETIRED_EPOCHS_KEY, LEGAC
14099
14200
  var init_schema = __esm({
14100
14201
  "../core/dist/common-auth-embedded/store/schema.js"() {
14101
14202
  "use strict";
14203
+ init_hooks();
14102
14204
  POOL_KEY = "commonAuthPool";
14103
14205
  POOL_SCHEMA_VERSION = 1;
14104
14206
  POOL_ROWS_KEY = "rows";
@@ -14799,8 +14901,8 @@ function assertQuotaRow(id, attribution, row) {
14799
14901
  });
14800
14902
  }
14801
14903
  function mergedQuota(ctx, id, stored, observation) {
14802
- const merged = ctx.codec.merge(stored, observation);
14803
- if (!ctx.codec.validate(merged))
14904
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
14905
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
14804
14906
  throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
14805
14907
  return merged;
14806
14908
  }
@@ -14840,6 +14942,7 @@ var init_attribution = __esm({
14840
14942
  "../core/dist/common-auth-embedded/store/attribution.js"() {
14841
14943
  "use strict";
14842
14944
  init_errors();
14945
+ init_hooks();
14843
14946
  init_mutate();
14844
14947
  init_refresh_lock();
14845
14948
  init_runtime();
@@ -14847,6 +14950,46 @@ var init_attribution = __esm({
14847
14950
  }
14848
14951
  });
14849
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
+
14850
14993
  // ../core/dist/common-auth-embedded/store/provider-state.js
14851
14994
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
14852
14995
  if (!codec)
@@ -14860,7 +15003,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
14860
15003
  }
14861
15004
  if (normalized === void 0)
14862
15005
  throw refusal2(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
14863
- if (!codec.validate(normalized))
15006
+ if (!runInsideCodec(() => codec.validate(normalized)))
14864
15007
  throw refusal2(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
14865
15008
  return normalized;
14866
15009
  }
@@ -14869,18 +15012,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
14869
15012
  return { kind: "set", value: incoming };
14870
15013
  return {
14871
15014
  kind: "set",
14872
- 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")
14873
15016
  };
14874
15017
  }
14875
15018
  function replacementProviderState(codec, row, credentialEpoch2, identity3, incoming) {
14876
15019
  const hook = codec?.onReplace;
14877
- 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), {
14878
15021
  id: row.id,
14879
15022
  credentialEpoch: credentialEpoch2,
14880
15023
  ...row.identity !== void 0 ? { previousIdentity: row.identity } : {},
14881
15024
  ...identity3 !== void 0 ? { identity: identity3 } : {},
14882
15025
  ...incoming !== void 0 ? { incoming: structuredClone(incoming) } : {}
14883
- }) : incoming;
15026
+ })) : incoming;
14884
15027
  if (next === void 0)
14885
15028
  return { kind: "clear" };
14886
15029
  if (!hook)
@@ -17140,7 +17283,7 @@ async function refreshRow(rt, id, provider2, options = {}) {
17140
17283
  if (options.onPersisted) {
17141
17284
  try {
17142
17285
  const persisted = options.onPersisted;
17143
- await runInsideHook("refresh", () => persisted(id, commit.stored));
17286
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
17144
17287
  } catch (cause) {
17145
17288
  throw new PoolOperationError({
17146
17289
  operation: "refresh",
@@ -17249,7 +17392,7 @@ function defineKey(target, key, value) {
17249
17392
  function composeConfig(config, next) {
17250
17393
  const out = {};
17251
17394
  for (const [key, value] of Object.entries(config)) {
17252
- if (POOL_OWNED_KEYS.includes(key))
17395
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
17253
17396
  defineKey(out, key, value);
17254
17397
  else if (Object.hasOwn(next, key))
17255
17398
  defineKey(out, key, next[key]);
@@ -17301,9 +17444,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
17301
17444
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
17302
17445
  if (owned.length > 0)
17303
17446
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
17304
- if (isDeepStrictEqual3(next, current))
17305
- 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");
17306
17449
  const config = composeConfig(result.config, next);
17450
+ if (isDeepStrictEqual3(settingsOf2(config), current))
17451
+ return { settings: current, outcome: "unchanged" };
17307
17452
  const info = { operation: "updateSettings", rowId: void 0 };
17308
17453
  await writeJsonAtomic2(ctx.configPath, config, {
17309
17454
  beforeRename: async () => {
@@ -17438,6 +17583,7 @@ function openPoolStore(options) {
17438
17583
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
17439
17584
  readSettings: () => readPoolSettings(rt),
17440
17585
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
17586
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
17441
17587
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
17442
17588
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
17443
17589
  recordQuota: record3,
@@ -17452,6 +17598,7 @@ var init_pool = __esm({
17452
17598
  "../core/dist/common-auth-embedded/store/pool.js"() {
17453
17599
  "use strict";
17454
17600
  init_attribution();
17601
+ init_limits_namespace();
17455
17602
  init_mutate();
17456
17603
  init_provider_state();
17457
17604
  init_publication();
@@ -17557,7 +17704,7 @@ function exclusionFor(id, inputs, now) {
17557
17704
  }
17558
17705
  return void 0;
17559
17706
  }
17560
- function judgeStageOne(id, projection, requiredLabels, now) {
17707
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
17561
17708
  if (projection.limits.length === 0) {
17562
17709
  return {
17563
17710
  id,
@@ -17581,7 +17728,7 @@ function judgeStageOne(id, projection, requiredLabels, now) {
17581
17728
  }
17582
17729
  const exhausted = projection.limits.filter(readsExhausted);
17583
17730
  for (const limit of exhausted) {
17584
- if (futureResetAt(limit, now) === void 0) {
17731
+ if (futureResetAt(limit, now) === void 0 && !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
17585
17732
  return {
17586
17733
  id,
17587
17734
  stage: 1,
@@ -17614,6 +17761,7 @@ function admit(input2) {
17614
17761
  const excluded = [];
17615
17762
  const refused2 = [];
17616
17763
  const survivors = [];
17764
+ const needsPull = /* @__PURE__ */ new Set();
17617
17765
  for (const row of input2.rows) {
17618
17766
  const exclusion = exclusionFor(row.id, input2, input2.now);
17619
17767
  if (exclusion) {
@@ -17625,7 +17773,10 @@ function admit(input2) {
17625
17773
  continue;
17626
17774
  }
17627
17775
  const projection = projectQuota(row.quota, scope);
17628
- 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);
17629
17780
  if (refusal3) {
17630
17781
  refused2.push(refusal3);
17631
17782
  continue;
@@ -17651,7 +17802,10 @@ function admit(input2) {
17651
17802
  const order = new Map(input2.rows.map((row, index) => [row.id, index]));
17652
17803
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
17653
17804
  refused2.sort(byInput);
17654
- 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);
17655
17809
  for (const id of pulls)
17656
17810
  input2.requestPull?.(id);
17657
17811
  return { admitted, refused: refused2, excluded, pulls };
@@ -18622,6 +18776,44 @@ function routingSection2(options, snap) {
18622
18776
  return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
18623
18777
  }
18624
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
+ }
18625
18817
  return {
18626
18818
  id: "routing",
18627
18819
  slot: "routing",
@@ -21686,9 +21878,144 @@ var init_shutdown = __esm({
21686
21878
  }
21687
21879
  });
21688
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
+
21689
22016
  // ../core/dist/common-auth-embedded/claustrum/custody.js
21690
22017
  import { channel } from "node:diagnostics_channel";
21691
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
22018
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
21692
22019
  function isScopedCredentialRotation(served, current) {
21693
22020
  return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
21694
22021
  }
@@ -21703,6 +22030,12 @@ function scopedRetryReason(served, current) {
21703
22030
  return "version-unchanged";
21704
22031
  return "rotated";
21705
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
+ }
21706
22039
  function decideScopedRetryAfter401(site, served, current, logger3 = defaultLogger) {
21707
22040
  const retry = isScopedCredentialRotation(served, current);
21708
22041
  logger3.debug("scoped 401 re-authorized", {
@@ -21811,6 +22144,7 @@ var init_custody = __esm({
21811
22144
  init_errors2();
21812
22145
  init_host_slot();
21813
22146
  init_shutdown();
22147
+ init_usage();
21814
22148
  init_watch();
21815
22149
  defaultLogger = createLogger2("claustrum");
21816
22150
  phaseDiagnostics = channel("common-auth.claustrum.phases");
@@ -21828,6 +22162,8 @@ var init_custody = __esm({
21828
22162
  #reports = /* @__PURE__ */ new WeakMap();
21829
22163
  #kept = /* @__PURE__ */ new Map();
21830
22164
  #keptAttempts = /* @__PURE__ */ new WeakMap();
22165
+ #usage;
22166
+ #usageServed = /* @__PURE__ */ new Map();
21831
22167
  #setTimeout;
21832
22168
  #clearTimeout;
21833
22169
  #outage = false;
@@ -21842,6 +22178,7 @@ var init_custody = __esm({
21842
22178
  #watches = /* @__PURE__ */ new Set();
21843
22179
  #tokenReads = /* @__PURE__ */ new Set();
21844
22180
  #warnShutdown;
22181
+ #onDrainTimeout;
21845
22182
  #disposing;
21846
22183
  constructor(options) {
21847
22184
  const tokenPath = options.tokenPath;
@@ -21861,13 +22198,21 @@ var init_custody = __esm({
21861
22198
  this.#warnShutdown = shutdownWarning(this.#logger);
21862
22199
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
21863
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
+ });
21864
22209
  }
21865
22210
  /** A watch losing its transport is the same outage as an unreachable read. */
21866
22211
  transportLost(error) {
21867
22212
  if (this.#closed || this.#outage)
21868
22213
  return;
21869
22214
  this.#outage = true;
21870
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
22215
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError();
21871
22216
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
21872
22217
  this.#scheduleProbe();
21873
22218
  }
@@ -21936,10 +22281,7 @@ var init_custody = __esm({
21936
22281
  });
21937
22282
  }
21938
22283
  this.#check(signal);
21939
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
21940
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
21941
- }
21942
- return value.token;
22284
+ return checkedEnrollmentToken(value);
21943
22285
  }
21944
22286
  async #call(operation, signal) {
21945
22287
  this.#check(signal);
@@ -21963,7 +22305,7 @@ var init_custody = __esm({
21963
22305
  this.transportLost(error);
21964
22306
  else
21965
22307
  this.reachable();
21966
- if (error instanceof ClaustrumCredentialError3)
22308
+ if (error instanceof ClaustrumCredentialError4)
21967
22309
  throw error;
21968
22310
  if (classifyVaultFailure(error) === "unreachable")
21969
22311
  throw new ClaustrumUnreachableError();
@@ -21993,6 +22335,7 @@ var init_custody = __esm({
21993
22335
  token = await this.#token(signal);
21994
22336
  } catch (error) {
21995
22337
  this.#kept.clear();
22338
+ this.#clearUsageOwnership();
21996
22339
  throw error;
21997
22340
  }
21998
22341
  if (phaseDiagnostics.hasSubscribers)
@@ -22094,11 +22437,19 @@ var init_custody = __esm({
22094
22437
  else {
22095
22438
  this.reachable();
22096
22439
  this.#kept.clear();
22440
+ this.#clearUsageOwnership();
22097
22441
  }
22098
22442
  }
22099
22443
  /** Discard bearer material when a route is removed, declined or rebound. */
22100
22444
  forget(credentialId) {
22101
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();
22102
22453
  }
22103
22454
  /** Apply an already-held roster; this never fetches credentials or writes it. */
22104
22455
  retain(identities) {
@@ -22108,6 +22459,11 @@ var init_custody = __esm({
22108
22459
  if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== kept.attempt.credentialType || identity3.accountIdentity !== kept.attempt.expectedAccountIdentity)
22109
22460
  this.forget(id);
22110
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
+ }
22111
22467
  }
22112
22468
  /** A frozen, non-secret summary for a plugin's status display. */
22113
22469
  keptReceiptState() {
@@ -22139,6 +22495,7 @@ var init_custody = __esm({
22139
22495
  token = await this.#token(signal);
22140
22496
  } catch (error) {
22141
22497
  this.#kept.clear();
22498
+ this.#clearUsageOwnership();
22142
22499
  throw error;
22143
22500
  }
22144
22501
  if (this.#outage && kept) {
@@ -22148,6 +22505,7 @@ var init_custody = __esm({
22148
22505
  try {
22149
22506
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
22150
22507
  this.#kept.set(credentialId, { attempt, routeId, since: null });
22508
+ this.#usageServed.set(credentialId, { ...identity3 });
22151
22509
  return attempt;
22152
22510
  } catch (error) {
22153
22511
  this.#check(signal);
@@ -22332,6 +22690,23 @@ var init_custody = __esm({
22332
22690
  }
22333
22691
  };
22334
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
+ }
22335
22710
  close() {
22336
22711
  if (this.#closed)
22337
22712
  return;
@@ -22343,12 +22718,23 @@ var init_custody = __esm({
22343
22718
  watch.stop();
22344
22719
  this.#watches.clear();
22345
22720
  this.#kept.clear();
22346
- 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
+ });
22347
22733
  }
22348
- /** 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. */
22349
22735
  async dispose(onTimeout = this.#warnShutdown) {
22736
+ this.#onDrainTimeout = onTimeout;
22350
22737
  this.close();
22351
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
22352
22738
  await this.#disposing;
22353
22739
  }
22354
22740
  };
@@ -22589,6 +22975,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
22589
22975
  return {
22590
22976
  version: 1,
22591
22977
  view: inventory.view,
22978
+ ...previous?.limits !== void 0 && { limits: previous.limits },
22592
22979
  complete,
22593
22980
  ...!complete && {
22594
22981
  rejected: inventory.skipped.map((record3) => ({
@@ -22659,6 +23046,7 @@ function decodeRoster(value) {
22659
23046
  // that was used whole, so it reads as complete.
22660
23047
  complete: value.complete !== false,
22661
23048
  ...rejected && { rejected },
23049
+ ...value.limits !== void 0 && { limits: value.limits },
22662
23050
  rows,
22663
23051
  declined
22664
23052
  };
@@ -23870,6 +24258,33 @@ var init_consumer = __esm({
23870
24258
  combined.dispose();
23871
24259
  }
23872
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
+ }
23873
24288
  async reportFailure(attempt, status, source) {
23874
24289
  this.#assertOpen();
23875
24290
  if (this.#hub) {
@@ -24481,6 +24896,14 @@ var init_hub = __esm({
24481
24896
  check();
24482
24897
  return custody.reportFailure(attempt, status, source);
24483
24898
  },
24899
+ reportUsage: (input2) => {
24900
+ if (!state.released && !generation.ended)
24901
+ custody.reportUsage(input2);
24902
+ },
24903
+ usageReportState: () => {
24904
+ check();
24905
+ return custody.usageReportState();
24906
+ },
24484
24907
  forget: (credentialId) => {
24485
24908
  check();
24486
24909
  custody.forget(credentialId);
@@ -25024,7 +25447,7 @@ __export(claustrum_exports, {
25024
25447
  ChangeNoticeReader: () => ChangeNoticeReader,
25025
25448
  ClaustrumConsumer: () => ClaustrumConsumer,
25026
25449
  ClaustrumConsumerError: () => ClaustrumConsumerError,
25027
- ClaustrumCredentialError: () => ClaustrumCredentialError4,
25450
+ ClaustrumCredentialError: () => ClaustrumCredentialError5,
25028
25451
  ClaustrumDiscoveryHub: () => ClaustrumDiscoveryHub,
25029
25452
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
25030
25453
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
@@ -25081,7 +25504,7 @@ __export(claustrum_exports, {
25081
25504
  vaultRoutingRows: () => vaultRoutingRows
25082
25505
  });
25083
25506
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
25084
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
25507
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
25085
25508
  async function connectClaustrumScopedClient(options) {
25086
25509
  const { connectTimeoutMs, ...client } = options;
25087
25510
  const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
@@ -28995,6 +29418,9 @@ function loadBackend2() {
28995
29418
  });
28996
29419
  return backend2;
28997
29420
  }
29421
+ function isWindowsSharingViolation2(error) {
29422
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
29423
+ }
28998
29424
  async function privateOperation2(path5, stage, operation) {
28999
29425
  try {
29000
29426
  return await operation();
@@ -32422,7 +32848,8 @@ async function removeOldCopies(location, files, present5, layoutLock, input2) {
32422
32848
  if (!await unlinkIfIdentical(
32423
32849
  file,
32424
32850
  location.stateHomeDir,
32425
- () => beforeRemove(file.old, layoutLock, input2.steps)
32851
+ () => beforeRemove(file.old, layoutLock, input2.steps),
32852
+ input2.steps?.oldFileIO
32426
32853
  ))
32427
32854
  kept.push(file.old);
32428
32855
  }
@@ -32444,21 +32871,21 @@ async function sameBytes(a, b) {
32444
32871
  return false;
32445
32872
  }
32446
32873
  }
32447
- function isWindowsSharingError(error) {
32874
+ function isWindowsSharingError(error, platform) {
32448
32875
  const code2 = error?.code;
32449
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32876
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32450
32877
  }
32451
- async function unlinkIfIdentical(file, stateDir, guard) {
32878
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink10 }) {
32452
32879
  const started = performance.now();
32453
32880
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
32454
32881
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
32455
32882
  let same;
32456
32883
  try {
32457
- same = (await readFile12(file.old)).equals(await readFile12(file.next));
32884
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
32458
32885
  } catch (error) {
32459
32886
  if (error.code === "ENOENT" && !await exists2(file.old))
32460
32887
  return true;
32461
- if (isWindowsSharingError(error)) {
32888
+ if (isWindowsSharingError(error, io.platform)) {
32462
32889
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
32463
32890
  continue;
32464
32891
  }
@@ -32467,11 +32894,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32467
32894
  if (!same) throw credentialConflict(stateDir, file);
32468
32895
  await guard();
32469
32896
  try {
32470
- await unlink10(file.old);
32897
+ await io.unlink(file.old);
32471
32898
  return true;
32472
32899
  } catch (error) {
32473
32900
  if (error.code === "ENOENT") return true;
32474
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32901
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32475
32902
  return false;
32476
32903
  }
32477
32904
  }
@@ -34032,7 +34459,7 @@ var init_logger4 = __esm({
34032
34459
 
34033
34460
  // src/plugin/index.ts
34034
34461
  init_dist();
34035
- import { createHash as createHash23, randomUUID as randomUUID21 } from "node:crypto";
34462
+ import { createHash as createHash24, randomUUID as randomUUID21 } from "node:crypto";
34036
34463
  import { join as join39, resolve as resolve26 } from "node:path";
34037
34464
 
34038
34465
  // src/cli.ts
@@ -36634,7 +37061,7 @@ import { createHash as createHash13, randomBytes as randomBytes5, randomUUID as
36634
37061
  import { constants as fsConstants2 } from "node:fs";
36635
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";
36636
37063
  import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute4, join as join20, resolve as resolve19 } from "node:path";
36637
- 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";
36638
37065
 
36639
37066
  // src/common-auth-embedded/fs/file-read-cache.js
36640
37067
  import { lstat as lstat7 } from "node:fs/promises";
@@ -37009,37 +37436,83 @@ async function acquireRefreshFileLockWithClock2(options) {
37009
37436
  await rm6(path5, { recursive: true, force: true }).catch(() => {
37010
37437
  });
37011
37438
  }
37012
- async function releaseEvictionMarker() {
37013
- if (await ownsEvictionMarker()) {
37014
- await removeLeaseObject(evictPath);
37015
- }
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");
37016
37443
  }
37017
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
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);
37492
+ }
37493
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
37018
37494
  if (!created)
37019
37495
  return false;
37020
- let current;
37021
- try {
37022
- const st = await lstat8(evictPath);
37023
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
37024
- } catch {
37025
- return false;
37026
- }
37027
- if (!sameMarkerDirectory2(created, current))
37028
- return false;
37496
+ let stillOurs = false;
37029
37497
  try {
37030
- await stat11(evictOwnerPath);
37031
- return true;
37032
- } catch (error) {
37033
- if (error.code !== "ENOENT")
37034
- return true;
37035
- }
37036
- try {
37037
- 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);
37038
37511
  } catch {
37039
37512
  }
37040
- return true;
37513
+ return stillOurs;
37041
37514
  }
37042
- async function tryAcquireEvictionMarker() {
37515
+ async function tryAcquireEvictionMarker(deadline) {
37043
37516
  if (windowsPrivateFiles2)
37044
37517
  await createPrivateDirectoryExclusive2(evictPath);
37045
37518
  else
@@ -37063,11 +37536,11 @@ async function acquireRefreshFileLockWithClock2(options) {
37063
37536
  else
37064
37537
  await createExclusiveText2(evictOwnerPath, bytes);
37065
37538
  } catch (error) {
37066
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
37539
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
37067
37540
  if (isLostMarkerRaceError2(error) && !stillOurs)
37068
37541
  return false;
37069
37542
  try {
37070
- await releaseEvictionMarker();
37543
+ await releaseEvictionMarker(deadline);
37071
37544
  } catch {
37072
37545
  }
37073
37546
  throw error;
@@ -37076,7 +37549,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37076
37549
  await options.onStep("eviction-marker-acquired");
37077
37550
  return true;
37078
37551
  }
37079
- async function recoverStaleEvictionMarker() {
37552
+ async function recoverStaleEvictionMarker(deadline) {
37080
37553
  let evictStat;
37081
37554
  try {
37082
37555
  evictStat = await stat11(evictPath);
@@ -37121,12 +37594,22 @@ async function acquireRefreshFileLockWithClock2(options) {
37121
37594
  }
37122
37595
  if (options.onStep)
37123
37596
  await options.onStep("stale-marker-claimed");
37124
- 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);
37125
37608
  return "recovered";
37126
37609
  }
37127
- async function withEvictionMarker(action) {
37610
+ async function withEvictionMarker(action, deadline) {
37128
37611
  try {
37129
- if (!await tryAcquireEvictionMarker())
37612
+ if (!await tryAcquireEvictionMarker(deadline))
37130
37613
  return false;
37131
37614
  } catch (error) {
37132
37615
  if (error.code === "EEXIST") {
@@ -37143,11 +37626,23 @@ async function acquireRefreshFileLockWithClock2(options) {
37143
37626
  }
37144
37627
  throw error;
37145
37628
  }
37629
+ let actionFailed = false;
37630
+ let actionError;
37146
37631
  try {
37147
37632
  await action();
37148
- } finally {
37149
- 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;
37150
37643
  }
37644
+ if (actionFailed)
37645
+ throw actionError;
37151
37646
  return true;
37152
37647
  }
37153
37648
  async function relinquishLockAfterMarkerLoss() {
@@ -37384,6 +37879,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37384
37879
  await renewalInFlight;
37385
37880
  const deadline = performance.now() + EVICT_TTL + 1e3;
37386
37881
  let delayMs = 5;
37882
+ let removalError;
37387
37883
  for (; ; ) {
37388
37884
  try {
37389
37885
  let removalConfirmed = false;
@@ -37408,7 +37904,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37408
37904
  return;
37409
37905
  await removeLeaseObject(lockPath);
37410
37906
  removalConfirmed = true;
37411
- });
37907
+ }, deadline);
37412
37908
  if (markerAcquired) {
37413
37909
  if (windowsPrivateFiles2 && !removalConfirmed)
37414
37910
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -37419,20 +37915,25 @@ async function acquireRefreshFileLockWithClock2(options) {
37419
37915
  }
37420
37916
  if (signal?.aborted)
37421
37917
  return;
37422
- await recoverStaleEvictionMarker();
37918
+ await recoverStaleEvictionMarker(deadline);
37423
37919
  } catch (error) {
37424
- if (windowsPrivateFiles2)
37425
- throw error;
37426
- return;
37920
+ if (!isRetryableRemoval(error, lockPath)) {
37921
+ if (windowsPrivateFiles2)
37922
+ throw error;
37923
+ return;
37924
+ }
37925
+ removalError ??= error;
37427
37926
  }
37428
37927
  const remainingMs = deadline - performance.now();
37429
37928
  if (remainingMs <= 0)
37430
37929
  break;
37431
37930
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
37931
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
37932
+ break;
37432
37933
  delayMs = Math.min(delayMs * 2, 50);
37433
37934
  }
37434
37935
  if (windowsPrivateFiles2)
37435
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
37936
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
37436
37937
  code: "ETIMEDOUT"
37437
37938
  });
37438
37939
  }
@@ -37475,7 +37976,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
37475
37976
  "pending_queue_full"
37476
37977
  ]);
37477
37978
  function classifyEnrollmentError2(error) {
37478
- if (!(error instanceof ClaustrumCredentialError5))
37979
+ if (!(error instanceof ClaustrumCredentialError6))
37479
37980
  return void 0;
37480
37981
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
37481
37982
  return { code: error.code, disposition: "terminal" };
@@ -39666,7 +40167,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39666
40167
  }
39667
40168
  };
39668
40169
  let openCodeLogin;
39669
- 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
+ };
39670
40177
  const manifest = JSON.parse(
39671
40178
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
39672
40179
  );
@@ -39724,18 +40231,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39724
40231
  await assertLocal(host, context);
39725
40232
  if (host === "opencode" && context.opencodeGeneration === "2") {
39726
40233
  if (!forceLogin) {
39727
- try {
39728
- const source2 = await deps.accountStore.read(
39729
- deps.accountStore.legacyPath()
39730
- );
39731
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
39732
- if (candidateAccounts.some(
39733
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39734
- )) {
39735
- hasLocalPool = true;
39736
- }
39737
- } catch {
39738
- }
40234
+ const source2 = await deps.accountStore.read(
40235
+ deps.accountStore.legacyPath()
40236
+ );
40237
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
39739
40238
  }
39740
40239
  return;
39741
40240
  }
@@ -39750,11 +40249,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39750
40249
  `Using existing local Antigravity login for ${host}.
39751
40250
  `
39752
40251
  );
39753
- if (host === "opencode" && accounts.some(
39754
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39755
- )) {
39756
- hasLocalPool = true;
39757
- }
39758
40252
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
39759
40253
  const account = accounts[0];
39760
40254
  await writeNativeSlot(
@@ -39787,18 +40281,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39787
40281
  );
39788
40282
  if (host === "opencode") {
39789
40283
  openCodeLogin = result;
39790
- hasLocalPool = true;
39791
40284
  }
39792
40285
  },
39793
40286
  beforeRegister: async (host, mode, context) => {
39794
40287
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
39795
- const nativeNextStep = (label) => {
39796
- deps.stdout.write(
39797
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
39798
- Setup has not completed the OpenCode 2 native Google connection.
39799
- `
39800
- );
39801
- };
39802
40288
  if (mode === "local") {
39803
40289
  await assertLocal(host, context);
39804
40290
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -39812,10 +40298,6 @@ Setup has not completed the OpenCode 2 native Google connection.
39812
40298
  },
39813
40299
  context
39814
40300
  );
39815
- if (needsOpenCode2)
39816
- nativeNextStep(
39817
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
39818
- );
39819
40301
  return;
39820
40302
  }
39821
40303
  if (await authority(host) !== "vault")
@@ -39886,11 +40368,28 @@ Setup has not completed the OpenCode 2 native Google connection.
39886
40368
  await publishedGeneration(stateAnchor),
39887
40369
  stateAnchor
39888
40370
  );
39889
- 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
+ );
39890
40392
  }
39891
- if (await migrateOpenCode() !== 0)
39892
- throw new Error("Offline Antigravity account migration failed.");
39893
- await deps.prepareVaultFolder?.();
39894
40393
  } else {
39895
40394
  deps.stdout.write(
39896
40395
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -40482,6 +40981,7 @@ async function readAccountStore(legacyPath) {
40482
40981
  case "bound":
40483
40982
  break;
40484
40983
  }
40984
+ const generationId = admission.receipt.id;
40485
40985
  const repository = createAccountRepositoryFactory(modules)({
40486
40986
  paths: admission.paths,
40487
40987
  now: Date.now,
@@ -40495,6 +40995,12 @@ async function readAccountStore(legacyPath) {
40495
40995
  }
40496
40996
  });
40497
40997
  try {
40998
+ const servingBefore = await readAccountStoreAdmission(
40999
+ legacyPath,
41000
+ modules,
41001
+ Date.now,
41002
+ generationId
41003
+ );
40498
41004
  const read = await repository.read();
40499
41005
  if (read.status !== "ready") {
40500
41006
  return {
@@ -40502,7 +41008,20 @@ async function readAccountStore(legacyPath) {
40502
41008
  reason: `the account store is ${read.status}`
40503
41009
  };
40504
41010
  }
40505
- 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
+ };
40506
41025
  } finally {
40507
41026
  await repository.dispose();
40508
41027
  }
@@ -41052,7 +41571,30 @@ function isSessionId(value) {
41052
41571
  init_private_files2();
41053
41572
  import { createHash as createHash15, randomUUID as randomUUID19 } from "node:crypto";
41054
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";
41055
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
+ }
41056
41598
  function isProbeablePid(pid) {
41057
41599
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
41058
41600
  }
@@ -41130,7 +41672,8 @@ async function writePortFile(dir, entry, options = {}) {
41130
41672
  throw error;
41131
41673
  }
41132
41674
  }
41133
- async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41675
+ async function sweepRpcState(root, activeDir, isManagedDir, log17, options = {}) {
41676
+ const cutoff = staleBefore(options);
41134
41677
  let projectDirs;
41135
41678
  try {
41136
41679
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -41157,6 +41700,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41157
41700
  if (!name.startsWith("port-") || !name.endsWith(".json"))
41158
41701
  continue;
41159
41702
  const portFile = join29(dir, name);
41703
+ const info = await stat15(portFile).catch(() => void 0);
41160
41704
  let raw;
41161
41705
  try {
41162
41706
  raw = await readPrivateText2(portFile);
@@ -41182,6 +41726,8 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41182
41726
  if (!pidAlive2(entry.pid))
41183
41727
  await unlink13(portFile).catch(() => {
41184
41728
  });
41729
+ else if (isStalePortFile(entry, info, cutoff))
41730
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
41185
41731
  }
41186
41732
  if (resolve23(dir) !== active2)
41187
41733
  await rmdir3(dir).catch(() => {
@@ -53774,17 +54320,20 @@ init_logger4();
53774
54320
 
53775
54321
  // src/plugin/shared/request-services.ts
53776
54322
  init_dist();
54323
+ import { createHash as createHash23 } from "node:crypto";
53777
54324
 
53778
- // src/common-auth-embedded/routing-accessor/index.js
53779
- function isObject2(value) {
53780
- return typeof value === "object" && value !== null;
53781
- }
54325
+ // src/common-auth-embedded/routing-accessor/handle.js
53782
54326
  function routingHandle(sessionId) {
53783
54327
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
53784
54328
  if (typeof routing !== "function")
53785
54329
  return void 0;
53786
54330
  const handle = routing(sessionId);
53787
- 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;
53788
54337
  }
53789
54338
  function selectionFor(answer, candidates) {
53790
54339
  if (!isObject2(answer))
@@ -53821,7 +54370,15 @@ async function askRouting(input2) {
53821
54370
  timer = setTimeout(() => resolve27(void 0), deadlineMs);
53822
54371
  timer.unref();
53823
54372
  });
53824
- 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 });
53825
54382
  if (!isObject2(pending) || typeof pending.then !== "function")
53826
54383
  return void 0;
53827
54384
  const answer = await Promise.race([pending, expired]);
@@ -53853,7 +54410,7 @@ function reportRouting(input2) {
53853
54410
  const { window, pool } = input2;
53854
54411
  if (window !== "5h" && window !== "7d")
53855
54412
  return;
53856
- 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)))
53857
54414
  return;
53858
54415
  payload = {
53859
54416
  ...identity3,
@@ -54593,6 +55150,7 @@ function isPrimaryVaultRequest(kind, headers) {
54593
55150
 
54594
55151
  // src/plugin/shared/request-services.ts
54595
55152
  var FIRST_RETRY_DELAY_MS = 1e3;
55153
+ var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
54596
55154
  function prepareAgyWireRequest(wire, request) {
54597
55155
  return wire.prepare(
54598
55156
  request.input,
@@ -54752,6 +55310,84 @@ function createRequestExecutor(deps) {
54752
55310
  } = deps;
54753
55311
  const retryState = createRetryState();
54754
55312
  const warmupState = createWarmupState();
55313
+ const modelAvailabilityNow = deps.modelAvailabilityNow ?? Date.now;
55314
+ const unavailableModels = /* @__PURE__ */ new Map();
55315
+ const accountKey = (account) => {
55316
+ if (credentials.domain === "vault") {
55317
+ const route = account.route;
55318
+ return route ? JSON.stringify([
55319
+ "vault",
55320
+ route.routeId,
55321
+ route.credentialId,
55322
+ route.accountIdentity
55323
+ ]) : account;
55324
+ }
55325
+ if (account.ref) {
55326
+ const ref = account.ref;
55327
+ return JSON.stringify([
55328
+ "local",
55329
+ ref.id,
55330
+ ref.credentialEpoch,
55331
+ ref.identity
55332
+ ]);
55333
+ }
55334
+ const refresh = credentials.toAuthDetails(account).refresh;
55335
+ return JSON.stringify([
55336
+ "pool-file",
55337
+ account.email?.toLowerCase(),
55338
+ createHash23("sha256").update(parseRefreshParts(refresh).refreshToken).digest("hex")
55339
+ ]);
55340
+ };
55341
+ const tierOf = (account) => JSON.stringify([account.capturedTierId, account.capturedPaidTierId]);
55342
+ const dropModel = (key, model, cause) => {
55343
+ const entries = unavailableModels.get(key);
55344
+ const entry = entries?.get(model);
55345
+ if (!entries || !entry) return;
55346
+ log17.debug("model-unavailable-memory-drop", {
55347
+ account: entry.label,
55348
+ model,
55349
+ cause
55350
+ });
55351
+ entries.delete(model);
55352
+ if (entries.size === 0) unavailableModels.delete(key);
55353
+ };
55354
+ const rememberedIndexes = (model) => {
55355
+ const rows = accountManager.getAccounts();
55356
+ const live = new Map(rows.map((row) => [accountKey(row), row]));
55357
+ const indexes = /* @__PURE__ */ new Set();
55358
+ for (const [key, entries] of unavailableModels) {
55359
+ const row = live.get(key);
55360
+ for (const [exactModel, entry] of entries) {
55361
+ const cause = !row ? "identity-replaced" : modelAvailabilityNow() - entry.recordedAt >= MODEL_UNAVAILABLE_TTL_MS ? "expired" : row.cachedQuotaUpdatedAt !== void 0 && row.cachedQuota?.["gemini-argon"] !== void 0 && (!entry.argonPool || row.cachedQuotaUpdatedAt !== entry.quotaUpdatedAt) ? "argon-pool" : row.cachedQuotaUpdatedAt !== void 0 && row.cachedQuotaUpdatedAt !== entry.quotaUpdatedAt ? "quota-reading" : tierOf(row) !== entry.tier ? "tier-changed" : void 0;
55362
+ if (cause) dropModel(key, exactModel, cause);
55363
+ else if (row && exactModel === model) indexes.add(row.index);
55364
+ }
55365
+ }
55366
+ return indexes;
55367
+ };
55368
+ const captureAvailability = (account) => ({
55369
+ key: accountKey(account),
55370
+ quotaUpdatedAt: account.cachedQuotaUpdatedAt,
55371
+ tier: tierOf(account),
55372
+ argonPool: account.cachedQuota?.["gemini-argon"] !== void 0,
55373
+ label: `Account ${account.index + 1}`
55374
+ });
55375
+ const rememberUnavailable = (snapshot2, model) => {
55376
+ const { key, ...entry } = snapshot2;
55377
+ let entries = unavailableModels.get(key);
55378
+ if (!entries) {
55379
+ entries = /* @__PURE__ */ new Map();
55380
+ unavailableModels.set(key, entries);
55381
+ }
55382
+ entries.set(model, {
55383
+ ...entry,
55384
+ recordedAt: modelAvailabilityNow()
55385
+ });
55386
+ log17.debug("model-unavailable-memory-record", {
55387
+ account: entry.label,
55388
+ model
55389
+ });
55390
+ };
54755
55391
  const shutdown = new AbortController();
54756
55392
  const inFlight = /* @__PURE__ */ new Set();
54757
55393
  const advisoryWork = /* @__PURE__ */ new Set();
@@ -55001,11 +55637,15 @@ function createRequestExecutor(deps) {
55001
55637
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
55002
55638
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
55003
55639
  );
55004
- if (modelUnavailableIndexes.size > 0) {
55640
+ const unavailableIndexes = /* @__PURE__ */ new Set([
55641
+ ...modelUnavailableIndexes,
55642
+ ...rememberedIndexes(model)
55643
+ ]);
55644
+ if (unavailableIndexes.size > 0) {
55005
55645
  const candidates = accountManager.getAccounts().filter(
55006
55646
  (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired && (eligibleIndexes === null || eligibleIndexes.has(entry.index))
55007
55647
  );
55008
- if (candidates.length > 0 && candidates.every((entry) => modelUnavailableIndexes.has(entry.index))) {
55648
+ if (candidates.length > 0 && candidates.every((entry) => unavailableIndexes.has(entry.index))) {
55009
55649
  pushDebug(
55010
55650
  `model-unavailable: all ${candidates.length} eligible account(s) skipped`
55011
55651
  );
@@ -55020,7 +55660,7 @@ function createRequestExecutor(deps) {
55020
55660
  });
55021
55661
  }
55022
55662
  }
55023
- const excludedIndexes = modelUnavailableIndexes.size === 0 ? killedIndexes : /* @__PURE__ */ new Set([...killedIndexes ?? [], ...modelUnavailableIndexes]);
55663
+ const excludedIndexes = unavailableIndexes.size === 0 ? killedIndexes : /* @__PURE__ */ new Set([...killedIndexes ?? [], ...unavailableIndexes]);
55024
55664
  const routingPresent = credentials.domain === "vault" && hasVaultRoutingAccessor();
55025
55665
  const firstPlacement = routingPresent && !routingPlacementConsidered && accountSessionIdentity && !accountManager.getCurrentAccountForFamily(
55026
55666
  family,
@@ -55611,6 +56251,7 @@ function createRequestExecutor(deps) {
55611
56251
  let tokenConsumed = false;
55612
56252
  let physicalAttemptStarted = false;
55613
56253
  try {
56254
+ const availabilitySnapshot = captureAvailability(account);
55614
56255
  let sendAdmission;
55615
56256
  let sendAccessToken;
55616
56257
  let sendProjectId;
@@ -56012,6 +56653,7 @@ function createRequestExecutor(deps) {
56012
56653
  void response.body?.cancel().catch(() => {
56013
56654
  });
56014
56655
  modelUnavailableIndexes.add(account.index);
56656
+ if (model) rememberUnavailable(availabilitySnapshot, model);
56015
56657
  skippedForModelUnavailable = true;
56016
56658
  shouldSwitchAccount = true;
56017
56659
  break;
@@ -56424,6 +57066,9 @@ function createRequestExecutor(deps) {
56424
57066
  while (advisoryWork.size > 0) await Promise.allSettled([...advisoryWork]);
56425
57067
  retryState.dispose();
56426
57068
  warmupState.dispose();
57069
+ for (const [key, entries] of unavailableModels) {
57070
+ for (const model of entries.keys()) dropModel(key, model, "disposed");
57071
+ }
56427
57072
  })();
56428
57073
  return drainPromise;
56429
57074
  }
@@ -57360,7 +58005,7 @@ init_storage();
57360
58005
  init_vault_custody();
57361
58006
  var logger2 = createLogger4("plugin");
57362
58007
  function quotaAccountIdentity4(refreshToken) {
57363
- return createHash23("sha256").update(refreshToken).digest("hex").slice(0, 16);
58008
+ return createHash24("sha256").update(refreshToken).digest("hex").slice(0, 16);
57364
58009
  }
57365
58010
  function registerQuotaManagerProducer(lifecycle, quotaManager) {
57366
58011
  lifecycle.register({ dispose: () => quotaManager.dispose() }, "producer");