@cortexkit/opencode-antigravity-auth 3.0.29 → 3.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/dist/cli.js +783 -254
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +145 -77
  4. package/dist/index.js +842 -297
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +177 -85
  7. package/dist/server.js +842 -300
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +1 -0
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +22 -2
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +36 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +74 -9
  18. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  19. package/dist/src/common-auth-embedded/claustrum/hub.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  21. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  22. package/dist/src/common-auth-embedded/claustrum/roster.js +34 -8
  23. package/dist/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  24. package/dist/src/common-auth-embedded/claustrum/usage.js +145 -0
  25. package/dist/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  26. package/dist/src/common-auth-embedded/commands/builtins.js +38 -0
  27. package/dist/src/common-auth-embedded/fs/file-read-cache.js +10 -5
  28. package/dist/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  29. package/dist/src/common-auth-embedded/fs/private-files.js +7 -0
  30. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  31. package/dist/src/common-auth-embedded/fs/with-lock.js +2 -5
  32. package/dist/src/common-auth-embedded/limits/activity.d.ts +26 -0
  33. package/dist/src/common-auth-embedded/limits/axes.d.ts +69 -0
  34. package/dist/src/common-auth-embedded/limits/decide.d.ts +146 -0
  35. package/dist/src/common-auth-embedded/limits/duration.d.ts +8 -0
  36. package/dist/src/common-auth-embedded/limits/families.d.ts +59 -0
  37. package/dist/src/common-auth-embedded/limits/marker.d.ts +69 -0
  38. package/dist/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  39. package/dist/src/common-auth-embedded/limits/scope.d.ts +12 -0
  40. package/dist/src/common-auth-embedded/limits/signal.d.ts +41 -0
  41. package/dist/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  42. package/dist/src/common-auth-embedded/limits/wake.d.ts +21 -0
  43. package/dist/src/common-auth-embedded/limits/wording.d.ts +25 -0
  44. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  45. package/dist/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  46. package/dist/src/common-auth-embedded/opencode2/install.js +219 -27
  47. package/dist/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  48. package/dist/src/common-auth-embedded/routing/admission.d.ts +7 -2
  49. package/dist/src/common-auth-embedded/routing/admission.js +17 -7
  50. package/dist/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  51. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  52. package/dist/src/common-auth-embedded/routing-accessor/index.js +11 -10
  53. package/dist/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  54. package/dist/src/common-auth-embedded/rpc/port-file.js +46 -4
  55. package/dist/src/common-auth-embedded/setup/enroll.js +7 -1
  56. package/dist/src/common-auth-embedded/source-output.json +260 -124
  57. package/dist/src/common-auth-embedded/store/attribution.js +3 -2
  58. package/dist/src/common-auth-embedded/store/errors.d.ts +1 -1
  59. package/dist/src/common-auth-embedded/store/hooks.d.ts +5 -1
  60. package/dist/src/common-auth-embedded/store/hooks.js +20 -5
  61. package/dist/src/common-auth-embedded/store/index.d.ts +1 -0
  62. package/dist/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  63. package/dist/src/common-auth-embedded/store/limits-namespace.js +46 -0
  64. package/dist/src/common-auth-embedded/store/pool.d.ts +10 -1
  65. package/dist/src/common-auth-embedded/store/pool.js +2 -0
  66. package/dist/src/common-auth-embedded/store/provider-state.js +5 -5
  67. package/dist/src/common-auth-embedded/store/refresh.js +1 -1
  68. package/dist/src/common-auth-embedded/store/schema.js +9 -4
  69. package/dist/src/common-auth-embedded/store/settings.d.ts +2 -0
  70. package/dist/src/common-auth-embedded/store/settings.js +11 -4
  71. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  72. package/dist/src/plugin/__fixtures__/release-model-ids.js +0 -1
  73. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  74. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  75. package/dist/src/plugin/account-access.js +1 -1
  76. package/dist/src/plugin/request.d.ts.map +1 -1
  77. package/dist/src/plugin/request.js +3 -2
  78. package/dist/src/plugin/request.js.map +1 -1
  79. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  80. package/dist/src/plugin/shared/request-services.js +1 -1
  81. package/dist/src/runtime-layout.d.ts +9 -2
  82. package/dist/src/runtime-layout.d.ts.map +1 -1
  83. package/dist/src/runtime-layout.js +8 -8
  84. package/dist/src/runtime-layout.js.map +1 -1
  85. package/dist/src/setup.d.ts.map +1 -1
  86. package/dist/src/setup.js +29 -40
  87. package/dist/src/setup.js.map +1 -1
  88. package/dist/tui-build-map.json +9 -9
  89. package/dist/tui-ga-build-map.json +1 -1
  90. package/dist/types/src/cli.d.ts +1 -0
  91. package/dist/types/src/cli.d.ts.map +1 -1
  92. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  93. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  94. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  95. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  96. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  97. package/dist/types/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  98. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  99. package/dist/types/src/common-auth-embedded/limits/activity.d.ts +26 -0
  100. package/dist/types/src/common-auth-embedded/limits/axes.d.ts +69 -0
  101. package/dist/types/src/common-auth-embedded/limits/decide.d.ts +146 -0
  102. package/dist/types/src/common-auth-embedded/limits/duration.d.ts +8 -0
  103. package/dist/types/src/common-auth-embedded/limits/families.d.ts +59 -0
  104. package/dist/types/src/common-auth-embedded/limits/marker.d.ts +69 -0
  105. package/dist/types/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  106. package/dist/types/src/common-auth-embedded/limits/scope.d.ts +12 -0
  107. package/dist/types/src/common-auth-embedded/limits/signal.d.ts +41 -0
  108. package/dist/types/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  109. package/dist/types/src/common-auth-embedded/limits/wake.d.ts +21 -0
  110. package/dist/types/src/common-auth-embedded/limits/wording.d.ts +25 -0
  111. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  112. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  113. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  114. package/dist/types/src/common-auth-embedded/routing/admission.d.ts +7 -2
  115. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  116. package/dist/types/src/common-auth-embedded/store/errors.d.ts +1 -1
  117. package/dist/types/src/common-auth-embedded/store/hooks.d.ts +5 -1
  118. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -0
  119. package/dist/types/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  120. package/dist/types/src/common-auth-embedded/store/pool.d.ts +10 -1
  121. package/dist/types/src/common-auth-embedded/store/settings.d.ts +2 -0
  122. package/dist/types/src/plugin/request.d.ts.map +1 -1
  123. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  124. package/dist/types/src/runtime-layout.d.ts +9 -2
  125. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  126. package/dist/types/src/setup.d.ts.map +1 -1
  127. package/package.json +3 -3
  128. package/src/common-auth-embedded/claustrum/consumer.d.ts +12 -0
  129. package/src/common-auth-embedded/claustrum/consumer.js +36 -0
  130. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -4
  131. package/src/common-auth-embedded/claustrum/custody.js +74 -9
  132. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  133. package/src/common-auth-embedded/claustrum/hub.js +8 -0
  134. package/src/common-auth-embedded/claustrum/index.d.ts +1 -0
  135. package/src/common-auth-embedded/claustrum/roster.d.ts +4 -0
  136. package/src/common-auth-embedded/claustrum/roster.js +34 -8
  137. package/src/common-auth-embedded/claustrum/usage.d.ts +41 -0
  138. package/src/common-auth-embedded/claustrum/usage.js +145 -0
  139. package/src/common-auth-embedded/commands/builtins.d.ts +5 -0
  140. package/src/common-auth-embedded/commands/builtins.js +38 -0
  141. package/src/common-auth-embedded/fs/file-read-cache.js +10 -5
  142. package/src/common-auth-embedded/fs/private-files.d.ts +5 -0
  143. package/src/common-auth-embedded/fs/private-files.js +7 -0
  144. package/src/common-auth-embedded/fs/refresh-file-lock.js +142 -47
  145. package/src/common-auth-embedded/fs/with-lock.js +2 -5
  146. package/src/common-auth-embedded/limits/activity.d.ts +26 -0
  147. package/src/common-auth-embedded/limits/axes.d.ts +69 -0
  148. package/src/common-auth-embedded/limits/decide.d.ts +146 -0
  149. package/src/common-auth-embedded/limits/duration.d.ts +8 -0
  150. package/src/common-auth-embedded/limits/families.d.ts +59 -0
  151. package/src/common-auth-embedded/limits/marker.d.ts +69 -0
  152. package/src/common-auth-embedded/limits/request-history.d.ts +79 -0
  153. package/src/common-auth-embedded/limits/scope.d.ts +12 -0
  154. package/src/common-auth-embedded/limits/signal.d.ts +41 -0
  155. package/src/common-auth-embedded/limits/terminal.d.ts +52 -0
  156. package/src/common-auth-embedded/limits/wake.d.ts +21 -0
  157. package/src/common-auth-embedded/limits/wording.d.ts +25 -0
  158. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  159. package/src/common-auth-embedded/opencode2/install.d.ts +4 -3
  160. package/src/common-auth-embedded/opencode2/install.js +219 -27
  161. package/src/common-auth-embedded/opencode2/types.d.ts +113 -11
  162. package/src/common-auth-embedded/routing/admission.d.ts +7 -2
  163. package/src/common-auth-embedded/routing/admission.js +17 -7
  164. package/src/common-auth-embedded/routing-accessor/handle.js +10 -0
  165. package/src/common-auth-embedded/routing-accessor/index.d.ts +13 -3
  166. package/src/common-auth-embedded/routing-accessor/index.js +11 -10
  167. package/src/common-auth-embedded/rpc/port-file.d.ts +12 -3
  168. package/src/common-auth-embedded/rpc/port-file.js +46 -4
  169. package/src/common-auth-embedded/setup/enroll.js +7 -1
  170. package/src/common-auth-embedded/source-output.json +260 -124
  171. package/src/common-auth-embedded/store/attribution.js +3 -2
  172. package/src/common-auth-embedded/store/errors.d.ts +1 -1
  173. package/src/common-auth-embedded/store/hooks.d.ts +5 -1
  174. package/src/common-auth-embedded/store/hooks.js +20 -5
  175. package/src/common-auth-embedded/store/index.d.ts +1 -0
  176. package/src/common-auth-embedded/store/limits-namespace.d.ts +13 -0
  177. package/src/common-auth-embedded/store/limits-namespace.js +46 -0
  178. package/src/common-auth-embedded/store/pool.d.ts +10 -1
  179. package/src/common-auth-embedded/store/pool.js +2 -0
  180. package/src/common-auth-embedded/store/provider-state.js +5 -5
  181. package/src/common-auth-embedded/store/refresh.js +1 -1
  182. package/src/common-auth-embedded/store/schema.js +9 -4
  183. package/src/common-auth-embedded/store/settings.d.ts +2 -0
  184. package/src/common-auth-embedded/store/settings.js +11 -4
  185. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +7 -0
  186. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +46 -4
  187. package/src/tui-raw/common-auth-embedded/fs/private-files.js +7 -0
  188. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +46 -4
package/dist/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();
@@ -1628,10 +1631,10 @@ async function privateDirectory(path5) {
1628
1631
  if (errno(error) !== "EEXIST")
1629
1632
  throw error;
1630
1633
  }
1631
- const stat16 = await lstat2(path5);
1632
- if (!stat16.isDirectory() || stat16.isSymbolicLink())
1634
+ const stat18 = await lstat2(path5);
1635
+ if (!stat18.isDirectory() || stat18.isSymbolicLink())
1633
1636
  throw new AccountMigrationError("successor directory is not a regular directory");
1634
- privateMode(stat16.mode, 448);
1637
+ privateMode(stat18.mode, 448);
1635
1638
  if (windowsPrivateFiles)
1636
1639
  await verifySafeDirectory(path5);
1637
1640
  if (!sameFilesystemPath(await realpath(path5), path5))
@@ -5876,7 +5879,7 @@ function getAgyNativeModel(model) {
5876
5879
  }
5877
5880
  function isRetiredAgyModel(model) {
5878
5881
  const route = model.toLowerCase().replace(/^antigravity-/, "").replace(/^gemini-(?=claude-)/, "").replace(/-preview(?:-customtools)?$/, "");
5879
- return (/^claude-(opus|sonnet)-4-6(?:-thinking)?(?:-(?:minimal|low|medium|high))?$/.test(route) || /^gemini-3\.1-pro(?:-(?:low|high))?$/.test(route) || /^gemini-3\.[67]-flash(?:-(?:low|medium|high|tiered))?$/.test(route) || route === "gemini-pro-agent") && getAgyNativeModel(route) === void 0;
5882
+ return (/^claude-(opus|sonnet)-4-6(?:-thinking)?(?:-(?:minimal|low|medium|high))?$/.test(route) || /^gemini-3\.1-pro(?:-(?:low|high))?$/.test(route) || /^gemini-3\.5-flash(?:-(?:low|medium|high|extra-low))?$/.test(route) || /^gemini-3\.[67]-flash(?:-(?:low|medium|high|tiered))?$/.test(route) || route === "gemini-3-flash-agent" || route === "gemini-pro-agent") && getAgyNativeModel(route) === void 0;
5880
5883
  }
5881
5884
  function pickModelDefinitions(ids) {
5882
5885
  return Object.fromEntries(ids.map((id) => [id, ALL_MODEL_DEFINITIONS[id]]));
@@ -6064,36 +6067,12 @@ var init_model_registry = __esm({
6064
6067
  supportsThinking: true,
6065
6068
  vertexModelId: "openai/gpt-oss-120b-maas"
6066
6069
  },
6067
- "gemini-3.5-flash-extra-low": {
6068
- displayName: "Gemini 3.5 Flash (Low)",
6069
- maxTokens: 1048576,
6070
- maxOutputTokens: 65536,
6071
- model: "MODEL_PLACEHOLDER_M187",
6072
- thinkingBudget: 1e3,
6073
- supportsThinking: true
6074
- },
6075
- "gemini-3.5-flash-low": {
6076
- displayName: "Gemini 3.5 Flash (Medium)",
6077
- maxTokens: 1048576,
6078
- maxOutputTokens: 65536,
6079
- model: "MODEL_PLACEHOLDER_M20",
6080
- thinkingBudget: 4e3,
6081
- supportsThinking: true
6082
- },
6083
- "gemini-3-flash-agent": {
6084
- displayName: "Gemini 3.5 Flash (High)",
6085
- maxTokens: 1048576,
6086
- maxOutputTokens: 65536,
6087
- model: "MODEL_PLACEHOLDER_M84",
6088
- thinkingBudget: -1,
6089
- supportsThinking: true
6090
- },
6091
6070
  "gemini-3.1-flash-image": {
6092
6071
  displayName: "Gemini 3.1 Flash Image",
6093
6072
  model: "MODEL_PLACEHOLDER_M21"
6094
6073
  }
6095
6074
  };
6096
- RETIRED_AGY_MODEL_MESSAGE = "This Antigravity model is no longer offered. Choose another model.";
6075
+ RETIRED_AGY_MODEL_MESSAGE = "This Antigravity model is no longer offered. Use Gemini 3.8 Flash, or Claude Sonnet 5.5 or Opus 5.5.";
6097
6076
  ALL_MODEL_DEFINITIONS = {
6098
6077
  "antigravity-gemini-4-argon": defineModel("antigravity-gemini-4-argon", {
6099
6078
  name: "Gemini 4 Argon (Antigravity)",
@@ -6106,17 +6085,6 @@ var init_model_registry = __esm({
6106
6085
  high: { thinkingLevel: "high" }
6107
6086
  }
6108
6087
  }),
6109
- "antigravity-gemini-3.5-flash": defineModel("antigravity-gemini-3.5-flash", {
6110
- name: "Gemini 3.5 Flash (Antigravity)",
6111
- reasoning: true,
6112
- limit: { context: 1048576, output: 65536 },
6113
- modalities: DEFAULT_MODALITIES,
6114
- variants: {
6115
- low: { thinkingLevel: "low" },
6116
- medium: { thinkingLevel: "medium" },
6117
- high: { thinkingLevel: "high" }
6118
- }
6119
- }),
6120
6088
  "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
6121
6089
  name: "Gemini 3.1 Flash Image (Antigravity)",
6122
6090
  reasoning: false,
@@ -6172,7 +6140,6 @@ var init_model_registry = __esm({
6172
6140
  "gemini-3-flash-low": "gemini-3-flash",
6173
6141
  "gemini-3-flash-medium": "gemini-3-flash",
6174
6142
  "gemini-3-flash-high": "gemini-3-flash",
6175
- "gemini-3.5-flash-low": "gemini-3.5-flash",
6176
6143
  "gemini-3.5-flash-medium": "gemini-3.5-flash",
6177
6144
  "gemini-3.5-flash-high": "gemini-3.5-flash",
6178
6145
  "gemini-3.6-flash-low": "gemini-3.6-flash",
@@ -6242,9 +6209,6 @@ var init_model_registry = __esm({
6242
6209
  "gemini-3.1-pro-low": "gemini",
6243
6210
  "gemini-3.1-pro-high": "gemini",
6244
6211
  "gemini-3-flash": "gemini",
6245
- "gemini-3-flash-agent": "gemini",
6246
- "gemini-3.5-flash-low": "gemini",
6247
- "gemini-3.5-flash-extra-low": "gemini",
6248
6212
  "gemini-3.6-flash-low": "gemini",
6249
6213
  "gemini-3.6-flash-medium": "gemini",
6250
6214
  "gemini-3.6-flash-high": "gemini",
@@ -6264,7 +6228,6 @@ var init_model_registry = __esm({
6264
6228
  ANTIGRAVITY_OPENCODE_MODEL_IDS = [
6265
6229
  "antigravity-gemini-4-argon",
6266
6230
  "antigravity-gemini-3.8-flash",
6267
- "antigravity-gemini-3.5-flash",
6268
6231
  "antigravity-gemini-3.1-flash-image",
6269
6232
  "antigravity-claude-sonnet-5-5",
6270
6233
  "antigravity-claude-opus-5-5",
@@ -10382,6 +10345,9 @@ var init_agy_request_metadata = __esm({
10382
10345
  }
10383
10346
  };
10384
10347
  HISTORICAL_AGY_MODEL_ENUMS = {
10348
+ "gemini-3.5-flash-extra-low": "MODEL_PLACEHOLDER_M187",
10349
+ "gemini-3.5-flash-low": "MODEL_PLACEHOLDER_M20",
10350
+ "gemini-3-flash-agent": "MODEL_PLACEHOLDER_M84",
10385
10351
  "gemini-3.1-pro-low": "MODEL_PLACEHOLDER_M36",
10386
10352
  "gemini-3.1-pro-high": "MODEL_PLACEHOLDER_M37",
10387
10353
  "gemini-pro-agent": "MODEL_PLACEHOLDER_M16",
@@ -12533,6 +12499,48 @@ var init_identity = __esm({
12533
12499
  }
12534
12500
  });
12535
12501
 
12502
+ // ../core/dist/common-auth-embedded/store/hooks.js
12503
+ import { AsyncLocalStorage } from "node:async_hooks";
12504
+ function assertNotInsideHook(operation) {
12505
+ if (insideHook.getStore() !== void 0)
12506
+ throw new PoolReentryError(operation);
12507
+ }
12508
+ function assertLimitsWriteAllowed() {
12509
+ if (insideHook.getStore()?.storeLocksReleased === false || insideCodec.getStore())
12510
+ throw new PoolReentryError("updateLimitsNamespace");
12511
+ }
12512
+ function runInsideCodec(fn) {
12513
+ return insideCodec.run(true, fn);
12514
+ }
12515
+ function runInsideHook(operation, fn, storeLocksReleased = false) {
12516
+ return insideHook.run({
12517
+ operation,
12518
+ storeLocksReleased: storeLocksReleased && insideHook.getStore()?.storeLocksReleased !== false
12519
+ }, async () => await fn());
12520
+ }
12521
+ async function callFailureHook(operation, hook, rowId2, error, logger3) {
12522
+ if (!hook)
12523
+ return;
12524
+ try {
12525
+ await runInsideHook(operation, () => hook(rowId2, error), true);
12526
+ } catch (hookError) {
12527
+ logger3?.warn("store failure hook threw; the original failure stands", {
12528
+ operation,
12529
+ rowId: rowId2,
12530
+ error: hookError instanceof Error ? hookError.message : String(hookError)
12531
+ });
12532
+ }
12533
+ }
12534
+ var insideHook, insideCodec;
12535
+ var init_hooks = __esm({
12536
+ "../core/dist/common-auth-embedded/store/hooks.js"() {
12537
+ "use strict";
12538
+ init_errors();
12539
+ insideHook = new AsyncLocalStorage();
12540
+ insideCodec = new AsyncLocalStorage();
12541
+ }
12542
+ });
12543
+
12536
12544
  // ../core/dist/common-auth-embedded/fs/atomic-write.js
12537
12545
  import { randomUUID as randomUUID8 } from "node:crypto";
12538
12546
  import { mkdir as mkdir6, open as open3, rename as rename5, rm as rm3 } from "node:fs/promises";
@@ -12914,37 +12922,83 @@ async function acquireRefreshFileLockWithClock(options) {
12914
12922
  await rm4(path5, { recursive: true, force: true }).catch(() => {
12915
12923
  });
12916
12924
  }
12917
- async function releaseEvictionMarker() {
12918
- if (await ownsEvictionMarker()) {
12919
- await removeLeaseObject(evictPath);
12920
- }
12925
+ function isRetryableRemoval(error, path5) {
12926
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path5)
12927
+ return false;
12928
+ return isWindowsSharingViolation(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
12929
+ }
12930
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
12931
+ let original;
12932
+ let delayMs = 5;
12933
+ while (await stillOwned()) {
12934
+ try {
12935
+ await removeLeaseObject(path5);
12936
+ return;
12937
+ } catch (error) {
12938
+ if (!isRetryableRemoval(error, path5))
12939
+ throw error;
12940
+ original ??= error;
12941
+ }
12942
+ const remainingMs = deadline - performance.now();
12943
+ if (remainingMs <= 0)
12944
+ throw original;
12945
+ await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
12946
+ if (performance.now() >= deadline)
12947
+ throw original;
12948
+ delayMs = Math.min(delayMs * 2, 50);
12949
+ }
12950
+ }
12951
+ async function releaseEvictionMarker(deadline) {
12952
+ let ownedDirectory;
12953
+ await removeOwnedLeaseObject(evictPath, async () => {
12954
+ if (!windowsPrivateFiles)
12955
+ return ownsEvictionMarker();
12956
+ const current = await lstat3(evictPath).catch((error) => {
12957
+ if (error.code !== "ENOENT")
12958
+ throw error;
12959
+ return void 0;
12960
+ });
12961
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
12962
+ return false;
12963
+ if (await ownsEvictionMarker()) {
12964
+ ownedDirectory = current;
12965
+ return true;
12966
+ }
12967
+ if (!ownedDirectory)
12968
+ return false;
12969
+ try {
12970
+ await stat3(evictOwnerPath);
12971
+ return false;
12972
+ } catch (error) {
12973
+ if (error.code !== "ENOENT")
12974
+ throw error;
12975
+ return true;
12976
+ }
12977
+ }, deadline);
12921
12978
  }
12922
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
12979
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
12923
12980
  if (!created)
12924
12981
  return false;
12925
- let current;
12926
- try {
12927
- const st = await lstat3(evictPath);
12928
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
12929
- } catch {
12930
- return false;
12931
- }
12932
- if (!sameMarkerDirectory(created, current))
12933
- return false;
12982
+ let stillOurs = false;
12934
12983
  try {
12935
- await stat3(evictOwnerPath);
12936
- return true;
12937
- } catch (error) {
12938
- if (error.code !== "ENOENT")
12939
- return true;
12940
- }
12941
- try {
12942
- await removeLeaseObject(evictPath);
12984
+ await removeOwnedLeaseObject(evictPath, async () => {
12985
+ stillOurs = false;
12986
+ const st = await lstat3(evictPath).catch(() => void 0);
12987
+ if (!st || !sameMarkerDirectory(created, st))
12988
+ return false;
12989
+ stillOurs = true;
12990
+ try {
12991
+ await stat3(evictOwnerPath);
12992
+ return false;
12993
+ } catch (error) {
12994
+ return error.code === "ENOENT";
12995
+ }
12996
+ }, deadline);
12943
12997
  } catch {
12944
12998
  }
12945
- return true;
12999
+ return stillOurs;
12946
13000
  }
12947
- async function tryAcquireEvictionMarker() {
13001
+ async function tryAcquireEvictionMarker(deadline) {
12948
13002
  if (windowsPrivateFiles)
12949
13003
  await createPrivateDirectoryExclusive(evictPath);
12950
13004
  else
@@ -12968,11 +13022,11 @@ async function acquireRefreshFileLockWithClock(options) {
12968
13022
  else
12969
13023
  await createExclusiveText(evictOwnerPath, bytes);
12970
13024
  } catch (error) {
12971
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
13025
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
12972
13026
  if (isLostMarkerRaceError(error) && !stillOurs)
12973
13027
  return false;
12974
13028
  try {
12975
- await releaseEvictionMarker();
13029
+ await releaseEvictionMarker(deadline);
12976
13030
  } catch {
12977
13031
  }
12978
13032
  throw error;
@@ -12981,7 +13035,7 @@ async function acquireRefreshFileLockWithClock(options) {
12981
13035
  await options.onStep("eviction-marker-acquired");
12982
13036
  return true;
12983
13037
  }
12984
- async function recoverStaleEvictionMarker() {
13038
+ async function recoverStaleEvictionMarker(deadline) {
12985
13039
  let evictStat;
12986
13040
  try {
12987
13041
  evictStat = await stat3(evictPath);
@@ -13026,12 +13080,22 @@ async function acquireRefreshFileLockWithClock(options) {
13026
13080
  }
13027
13081
  if (options.onStep)
13028
13082
  await options.onStep("stale-marker-claimed");
13029
- await removeLeaseObject(claimedPath);
13083
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : void 0;
13084
+ await removeOwnedLeaseObject(claimedPath, async () => {
13085
+ if (!claimedIdentity)
13086
+ return true;
13087
+ const current = await lstat3(claimedPath).catch((error) => {
13088
+ if (error.code !== "ENOENT")
13089
+ throw error;
13090
+ return void 0;
13091
+ });
13092
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
13093
+ }, deadline);
13030
13094
  return "recovered";
13031
13095
  }
13032
- async function withEvictionMarker(action) {
13096
+ async function withEvictionMarker(action, deadline) {
13033
13097
  try {
13034
- if (!await tryAcquireEvictionMarker())
13098
+ if (!await tryAcquireEvictionMarker(deadline))
13035
13099
  return false;
13036
13100
  } catch (error) {
13037
13101
  if (error.code === "EEXIST") {
@@ -13048,11 +13112,23 @@ async function acquireRefreshFileLockWithClock(options) {
13048
13112
  }
13049
13113
  throw error;
13050
13114
  }
13115
+ let actionFailed = false;
13116
+ let actionError;
13051
13117
  try {
13052
13118
  await action();
13053
- } finally {
13054
- await releaseEvictionMarker();
13119
+ } catch (error) {
13120
+ actionFailed = true;
13121
+ actionError = error;
13122
+ }
13123
+ try {
13124
+ await releaseEvictionMarker(deadline);
13125
+ } catch (error) {
13126
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
13127
+ throw actionError;
13128
+ throw error;
13055
13129
  }
13130
+ if (actionFailed)
13131
+ throw actionError;
13056
13132
  return true;
13057
13133
  }
13058
13134
  async function relinquishLockAfterMarkerLoss() {
@@ -13289,6 +13365,7 @@ async function acquireRefreshFileLockWithClock(options) {
13289
13365
  await renewalInFlight;
13290
13366
  const deadline = performance.now() + EVICT_TTL + 1e3;
13291
13367
  let delayMs = 5;
13368
+ let removalError;
13292
13369
  for (; ; ) {
13293
13370
  try {
13294
13371
  let removalConfirmed = false;
@@ -13313,7 +13390,7 @@ async function acquireRefreshFileLockWithClock(options) {
13313
13390
  return;
13314
13391
  await removeLeaseObject(lockPath);
13315
13392
  removalConfirmed = true;
13316
- });
13393
+ }, deadline);
13317
13394
  if (markerAcquired) {
13318
13395
  if (windowsPrivateFiles && !removalConfirmed)
13319
13396
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -13324,20 +13401,25 @@ async function acquireRefreshFileLockWithClock(options) {
13324
13401
  }
13325
13402
  if (signal?.aborted)
13326
13403
  return;
13327
- await recoverStaleEvictionMarker();
13404
+ await recoverStaleEvictionMarker(deadline);
13328
13405
  } catch (error) {
13329
- if (windowsPrivateFiles)
13330
- throw error;
13331
- return;
13406
+ if (!isRetryableRemoval(error, lockPath)) {
13407
+ if (windowsPrivateFiles)
13408
+ throw error;
13409
+ return;
13410
+ }
13411
+ removalError ??= error;
13332
13412
  }
13333
13413
  const remainingMs = deadline - performance.now();
13334
13414
  if (remainingMs <= 0)
13335
13415
  break;
13336
13416
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
13417
+ if (windowsPrivateFiles && performance.now() >= deadline)
13418
+ break;
13337
13419
  delayMs = Math.min(delayMs * 2, 50);
13338
13420
  }
13339
13421
  if (windowsPrivateFiles)
13340
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
13422
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
13341
13423
  code: "ETIMEDOUT"
13342
13424
  });
13343
13425
  }
@@ -13361,7 +13443,7 @@ function lockPathFor(target, name) {
13361
13443
  return `${target}.${name}.lock`;
13362
13444
  }
13363
13445
  function isChangingLockRead(error, target, name) {
13364
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.reason !== "io-error" || error.win32Code !== 32 && error.win32Code !== 303 || error.stage !== "read" && error.stage !== "verify")
13446
+ if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
13365
13447
  return false;
13366
13448
  const path5 = resolve3(lockPathFor(target, name));
13367
13449
  return error.path === path5 || error.path === join6(path5, "owner.json");
@@ -13433,37 +13515,6 @@ var init_with_lock = __esm({
13433
13515
  }
13434
13516
  });
13435
13517
 
13436
- // ../core/dist/common-auth-embedded/store/hooks.js
13437
- import { AsyncLocalStorage } from "node:async_hooks";
13438
- function assertNotInsideHook(operation) {
13439
- if (insideHook.getStore() !== void 0)
13440
- throw new PoolReentryError(operation);
13441
- }
13442
- function runInsideHook(operation, fn) {
13443
- return insideHook.run(operation, async () => await fn());
13444
- }
13445
- async function callFailureHook(operation, hook, rowId2, error, logger3) {
13446
- if (!hook)
13447
- return;
13448
- try {
13449
- await runInsideHook(operation, () => hook(rowId2, error));
13450
- } catch (hookError) {
13451
- logger3?.warn("store failure hook threw; the original failure stands", {
13452
- operation,
13453
- rowId: rowId2,
13454
- error: hookError instanceof Error ? hookError.message : String(hookError)
13455
- });
13456
- }
13457
- }
13458
- var insideHook;
13459
- var init_hooks = __esm({
13460
- "../core/dist/common-auth-embedded/store/hooks.js"() {
13461
- "use strict";
13462
- init_errors();
13463
- insideHook = new AsyncLocalStorage();
13464
- }
13465
- });
13466
-
13467
13518
  // ../core/dist/common-auth-embedded/store/refresh-lock.js
13468
13519
  async function acquirePoolLock(spec, defaults, env3) {
13469
13520
  const emit = (type) => {
@@ -13695,7 +13746,7 @@ function stampFor(credential, credentialEpoch2, binding, options = {}) {
13695
13746
  };
13696
13747
  }
13697
13748
  function providerStateDigest(codec, value) {
13698
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
13749
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
13699
13750
  return createHash5("sha256").update(`provider-state\0${JSON.stringify(bound ?? null)}`).digest("hex");
13700
13751
  }
13701
13752
  function boundProviderStateDigest(account, credential, credentialEpoch2, identity3) {
@@ -13862,8 +13913,8 @@ function parseEntry(raw, codec) {
13862
13913
  return void 0;
13863
13914
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
13864
13915
  return void 0;
13865
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
13866
- if ("quota" in raw && !codec.validate(quota))
13916
+ const quota = "quota" in raw && codec.decode ? runInsideCodec(() => codec.decode?.(raw.quota)) : raw.quota;
13917
+ if ("quota" in raw && !runInsideCodec(() => codec.validate(quota)))
13867
13918
  return void 0;
13868
13919
  if ("staged" in raw && !parseReservation(raw.staged))
13869
13920
  return void 0;
@@ -14035,7 +14086,7 @@ function providerStateFields(account, credential, credentialEpoch2, identity3, c
14035
14086
  if (digest3 === void 0)
14036
14087
  return { providerStateDropped: "uncovered" };
14037
14088
  const value = account[PROVIDER_STATE_KEY];
14038
- if (!codec?.validate(value))
14089
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
14039
14090
  return { providerStateDropped: "invalid" };
14040
14091
  if (providerStateDigest(codec, value) !== digest3)
14041
14092
  return { providerStateDropped: "uncovered" };
@@ -14112,6 +14163,7 @@ var POOL_KEY, POOL_SCHEMA_VERSION, POOL_ROWS_KEY, POOL_RETIRED_EPOCHS_KEY, LEGAC
14112
14163
  var init_schema = __esm({
14113
14164
  "../core/dist/common-auth-embedded/store/schema.js"() {
14114
14165
  "use strict";
14166
+ init_hooks();
14115
14167
  POOL_KEY = "commonAuthPool";
14116
14168
  POOL_SCHEMA_VERSION = 1;
14117
14169
  POOL_ROWS_KEY = "rows";
@@ -14812,8 +14864,8 @@ function assertQuotaRow(id, attribution, row) {
14812
14864
  });
14813
14865
  }
14814
14866
  function mergedQuota(ctx, id, stored, observation) {
14815
- const merged = ctx.codec.merge(stored, observation);
14816
- if (!ctx.codec.validate(merged))
14867
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
14868
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
14817
14869
  throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
14818
14870
  return merged;
14819
14871
  }
@@ -14853,6 +14905,7 @@ var init_attribution = __esm({
14853
14905
  "../core/dist/common-auth-embedded/store/attribution.js"() {
14854
14906
  "use strict";
14855
14907
  init_errors();
14908
+ init_hooks();
14856
14909
  init_mutate();
14857
14910
  init_refresh_lock();
14858
14911
  init_runtime();
@@ -14860,6 +14913,54 @@ var init_attribution = __esm({
14860
14913
  }
14861
14914
  });
14862
14915
 
14916
+ // ../core/dist/common-auth-embedded/store/limits-namespace.js
14917
+ async function updatePoolLimitsNamespace(rt, mutator, options = {}) {
14918
+ assertLimitsWriteAllowed();
14919
+ const { ctx } = rt;
14920
+ await runOperation(ctx, "updateLimitsNamespace", void 0, void 0, async (locks, progress) => {
14921
+ for (const spec of ctx.storeLocks)
14922
+ await locks.acquire(spec);
14923
+ const result = await readPool(ctx);
14924
+ if (result.status !== "ready")
14925
+ throw notReadyError(result, "updateLimitsNamespace", void 0);
14926
+ const rows = result.rows.map(({ id, credentialEpoch: credentialEpoch2, identity: identity3 }) => ({
14927
+ id,
14928
+ credentialEpoch: credentialEpoch2,
14929
+ identity: identity3
14930
+ }));
14931
+ const envelope = await runInsideHook("updateLimitsNamespace", () => mutator(structuredClone(result.config.commonAuthLimits), rows));
14932
+ const config = { ...result.config, commonAuthLimits: envelope };
14933
+ const info = {
14934
+ operation: "updateLimitsNamespace",
14935
+ rowId: void 0
14936
+ };
14937
+ try {
14938
+ await writeJsonAtomic2(ctx.configPath, config, {
14939
+ beforeRename: async () => {
14940
+ await ctx.onStep?.("before-config-write", info);
14941
+ await locks.assertAll();
14942
+ options.beforePublish?.();
14943
+ }
14944
+ });
14945
+ } catch (error) {
14946
+ if (error && typeof error === "object" && "published" in error && error.published === true)
14947
+ options.onPublished?.();
14948
+ throw error;
14949
+ }
14950
+ progress.writes++;
14951
+ options.onPublished?.();
14952
+ await ctx.onStep?.("after-config-write", info);
14953
+ });
14954
+ }
14955
+ var init_limits_namespace = __esm({
14956
+ "../core/dist/common-auth-embedded/store/limits-namespace.js"() {
14957
+ "use strict";
14958
+ init_atomic_write2();
14959
+ init_hooks();
14960
+ init_mutate();
14961
+ }
14962
+ });
14963
+
14863
14964
  // ../core/dist/common-auth-embedded/store/provider-state.js
14864
14965
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
14865
14966
  if (!codec)
@@ -14873,7 +14974,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
14873
14974
  }
14874
14975
  if (normalized === void 0)
14875
14976
  throw refusal2(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
14876
- if (!codec.validate(normalized))
14977
+ if (!runInsideCodec(() => codec.validate(normalized)))
14877
14978
  throw refusal2(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
14878
14979
  return normalized;
14879
14980
  }
@@ -14882,18 +14983,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
14882
14983
  return { kind: "set", value: incoming };
14883
14984
  return {
14884
14985
  kind: "set",
14885
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), "the merged provider state")
14986
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), "the merged provider state")
14886
14987
  };
14887
14988
  }
14888
14989
  function replacementProviderState(codec, row, credentialEpoch2, identity3, incoming) {
14889
14990
  const hook = codec?.onReplace;
14890
- const next = hook ? hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
14991
+ const next = hook ? runInsideCodec(() => hook(row.providerState === void 0 ? void 0 : structuredClone(row.providerState), {
14891
14992
  id: row.id,
14892
14993
  credentialEpoch: credentialEpoch2,
14893
14994
  ...row.identity !== void 0 ? { previousIdentity: row.identity } : {},
14894
14995
  ...identity3 !== void 0 ? { identity: identity3 } : {},
14895
14996
  ...incoming !== void 0 ? { incoming: structuredClone(incoming) } : {}
14896
- }) : incoming;
14997
+ })) : incoming;
14897
14998
  if (next === void 0)
14898
14999
  return { kind: "clear" };
14899
15000
  if (!hook)
@@ -17153,7 +17254,7 @@ async function refreshRow(rt, id, provider2, options = {}) {
17153
17254
  if (options.onPersisted) {
17154
17255
  try {
17155
17256
  const persisted = options.onPersisted;
17156
- await runInsideHook("refresh", () => persisted(id, commit.stored));
17257
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
17157
17258
  } catch (cause) {
17158
17259
  throw new PoolOperationError({
17159
17260
  operation: "refresh",
@@ -17192,11 +17293,11 @@ var init_refresh = __esm({
17192
17293
  });
17193
17294
 
17194
17295
  // ../core/dist/common-auth-embedded/fs/file-read-cache.js
17195
- import { lstat as lstat4 } from "node:fs/promises";
17296
+ import { lstat as lstat4, stat as stat4 } from "node:fs/promises";
17196
17297
  import { resolve as resolve5 } from "node:path";
17197
- async function identity(path5) {
17298
+ async function identity(path5, followSymlinks) {
17198
17299
  try {
17199
- const metadata = await lstat4(path5);
17300
+ const metadata = await (followSymlinks ? stat4(path5) : lstat4(path5));
17200
17301
  return metadata.isFile() ? metadata : void 0;
17201
17302
  } catch (error) {
17202
17303
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -17212,11 +17313,15 @@ var init_file_read_cache = __esm({
17212
17313
  "../core/dist/common-auth-embedded/fs/file-read-cache.js"() {
17213
17314
  "use strict";
17214
17315
  FileReadCache = class {
17316
+ #followSymlinks;
17215
17317
  #entries = /* @__PURE__ */ new Map();
17318
+ constructor(options = {}) {
17319
+ this.#followSymlinks = options.followSymlinks ?? false;
17320
+ }
17216
17321
  async read(paths, read, validateHit) {
17217
17322
  const resolvedPaths = paths.map((path5) => resolve5(path5));
17218
17323
  const key = JSON.stringify(resolvedPaths);
17219
- const probed = await Promise.all(resolvedPaths.map(identity));
17324
+ const probed = await Promise.all(resolvedPaths.map((path5) => identity(path5, this.#followSymlinks)));
17220
17325
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
17221
17326
  const cached = this.#entries.get(key);
17222
17327
  if (identities && cached && identities.every((entry, index) => {
@@ -17262,7 +17367,7 @@ function defineKey(target, key, value) {
17262
17367
  function composeConfig(config, next) {
17263
17368
  const out = {};
17264
17369
  for (const [key, value] of Object.entries(config)) {
17265
- if (POOL_OWNED_KEYS.includes(key))
17370
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
17266
17371
  defineKey(out, key, value);
17267
17372
  else if (Object.hasOwn(next, key))
17268
17373
  defineKey(out, key, next[key]);
@@ -17314,9 +17419,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
17314
17419
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
17315
17420
  if (owned.length > 0)
17316
17421
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
17317
- if (isDeepStrictEqual3(next, current))
17318
- return { settings: current, outcome: "unchanged" };
17422
+ if (Object.hasOwn(next, "commonAuthLimits") && (!Object.hasOwn(current, "commonAuthLimits") || !isDeepStrictEqual3(next.commonAuthLimits, current.commonAuthLimits)))
17423
+ throw settingsRefusal("settings cannot alter commonAuthLimits; use updateLimitsNamespace");
17319
17424
  const config = composeConfig(result.config, next);
17425
+ if (isDeepStrictEqual3(settingsOf2(config), current))
17426
+ return { settings: current, outcome: "unchanged" };
17320
17427
  const info = { operation: "updateSettings", rowId: void 0 };
17321
17428
  await writeJsonAtomic2(ctx.configPath, config, {
17322
17429
  beforeRename: async () => {
@@ -17451,6 +17558,7 @@ function openPoolStore(options) {
17451
17558
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
17452
17559
  readSettings: () => readPoolSettings(rt),
17453
17560
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
17561
+ updateLimitsNamespace: (mutator, options2) => updatePoolLimitsNamespace(rt, mutator, options2),
17454
17562
  recordIdentity: (id, identity3, attribution, callOptions) => recordRowIdentity(rt, id, identity3, attribution, callOptions),
17455
17563
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
17456
17564
  recordQuota: record3,
@@ -17465,6 +17573,7 @@ var init_pool = __esm({
17465
17573
  "../core/dist/common-auth-embedded/store/pool.js"() {
17466
17574
  "use strict";
17467
17575
  init_attribution();
17576
+ init_limits_namespace();
17468
17577
  init_mutate();
17469
17578
  init_provider_state();
17470
17579
  init_publication();
@@ -17570,7 +17679,7 @@ function exclusionFor(id, inputs, now) {
17570
17679
  }
17571
17680
  return void 0;
17572
17681
  }
17573
- function judgeStageOne(id, projection, requiredLabels, now) {
17682
+ function judgeStageOne(id, projection, requiredLabels, now, liftedWindows) {
17574
17683
  if (projection.limits.length === 0) {
17575
17684
  return {
17576
17685
  id,
@@ -17594,7 +17703,7 @@ function judgeStageOne(id, projection, requiredLabels, now) {
17594
17703
  }
17595
17704
  const exhausted = projection.limits.filter(readsExhausted);
17596
17705
  for (const limit of exhausted) {
17597
- if (futureResetAt(limit, now) === void 0) {
17706
+ if (futureResetAt(limit, now) === void 0 && !liftedWindows.some((window) => window.scope === limit.scope && window.label === limit.label)) {
17598
17707
  return {
17599
17708
  id,
17600
17709
  stage: 1,
@@ -17627,6 +17736,7 @@ function admit(input2) {
17627
17736
  const excluded = [];
17628
17737
  const refused2 = [];
17629
17738
  const survivors = [];
17739
+ const needsPull = /* @__PURE__ */ new Set();
17630
17740
  for (const row of input2.rows) {
17631
17741
  const exclusion = exclusionFor(row.id, input2, input2.now);
17632
17742
  if (exclusion) {
@@ -17638,7 +17748,10 @@ function admit(input2) {
17638
17748
  continue;
17639
17749
  }
17640
17750
  const projection = projectQuota(row.quota, scope);
17641
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input2.now);
17751
+ const lifted = input2.liftedWindows?.get(row.id) ?? [];
17752
+ if (projection.limits.some((limit) => readsExhausted(limit) && futureResetAt(limit, input2.now) === void 0 && lifted.some((window) => window.scope === limit.scope && window.label === limit.label)))
17753
+ needsPull.add(row.id);
17754
+ const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input2.now, lifted);
17642
17755
  if (refusal3) {
17643
17756
  refused2.push(refusal3);
17644
17757
  continue;
@@ -17664,7 +17777,10 @@ function admit(input2) {
17664
17777
  const order = new Map(input2.rows.map((row, index) => [row.id, index]));
17665
17778
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
17666
17779
  refused2.sort(byInput);
17667
- const pulls = refused2.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
17780
+ for (const refusal3 of refused2)
17781
+ if ("pullRequested" in refusal3)
17782
+ needsPull.add(refusal3.id);
17783
+ const pulls = input2.rows.filter((row) => needsPull.has(row.id)).map((row) => row.id);
17668
17784
  for (const id of pulls)
17669
17785
  input2.requestPull?.(id);
17670
17786
  return { admitted, refused: refused2, excluded, pulls };
@@ -18635,6 +18751,44 @@ function routingSection2(options, snap) {
18635
18751
  return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
18636
18752
  }
18637
18753
  });
18754
+ if (options.routing?.sameAccountWait) {
18755
+ const waitLabel = "Longest wait on the same account";
18756
+ const waitChoices = [
18757
+ { value: "0", label: "Don't wait" },
18758
+ { value: "15", label: "15 minutes" },
18759
+ { value: "max", label: "Until the cache expires" }
18760
+ ];
18761
+ const rawWait = record(snap.settings.routing).maxSameAccountWait;
18762
+ const wait2 = String(rawWait === 0 || rawWait === "max" ? rawWait : 15);
18763
+ const waitName = (value) => waitChoices.find((choice) => choice.value === value)?.label ?? value;
18764
+ lines.push(`${waitLabel}: ${waitName(wait2)}`);
18765
+ actions.push({
18766
+ id: "maxSameAccountWait",
18767
+ label: waitLabel,
18768
+ group: ACTIONS_GROUP,
18769
+ knobs: [
18770
+ {
18771
+ kind: "choice",
18772
+ id: "maxSameAccountWait",
18773
+ label: waitLabel,
18774
+ choices: waitChoices,
18775
+ value: wait2
18776
+ }
18777
+ ],
18778
+ run: async ({ values }) => {
18779
+ const value = String(values.maxSameAccountWait);
18780
+ const maxSameAccountWait = value === "max" ? "max" : Number(value);
18781
+ await store.updateSettings((settings) => {
18782
+ settings.routing = {
18783
+ ...record(settings.routing),
18784
+ maxSameAccountWait
18785
+ };
18786
+ return void 0;
18787
+ }, locks);
18788
+ return `${waitLabel} set to ${waitName(value)}.`;
18789
+ }
18790
+ });
18791
+ }
18638
18792
  return {
18639
18793
  id: "routing",
18640
18794
  slot: "routing",
@@ -20915,7 +21069,7 @@ var init_any_signal = __esm({
20915
21069
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
20916
21070
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
20917
21071
  import { constants as fsConstants } from "node:fs";
20918
- import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat4, unlink as unlink6 } from "node:fs/promises";
21072
+ import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat5, unlink as unlink6 } from "node:fs/promises";
20919
21073
  import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve7 } from "node:path";
20920
21074
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
20921
21075
  function classifyEnrollmentError(error) {
@@ -21135,7 +21289,7 @@ async function refuseWritableAncestor(parent, options = {}) {
21135
21289
  }
21136
21290
  let privateGroup;
21137
21291
  for (; ; ) {
21138
- const metadata = await stat4(component).catch(() => void 0);
21292
+ const metadata = await stat5(component).catch(() => void 0);
21139
21293
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
21140
21294
  if (privateGroup === void 0) {
21141
21295
  privateGroup = gid !== void 0 && await isPrivateGroup(uid, gid, options);
@@ -21164,7 +21318,7 @@ async function ensureClaustrumPrivateDirectory(directory, options = {}, what = "
21164
21318
  return;
21165
21319
  }
21166
21320
  await mkdir8(directory, { recursive: true, mode: 448 });
21167
- const metadata = await stat4(directory);
21321
+ const metadata = await stat5(directory);
21168
21322
  const uid = process.geteuid?.();
21169
21323
  if (uid !== void 0 && metadata.uid !== uid) {
21170
21324
  throw new ClaustrumConsumerError("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -21699,9 +21853,144 @@ var init_shutdown = __esm({
21699
21853
  }
21700
21854
  });
21701
21855
 
21856
+ // ../core/dist/common-auth-embedded/claustrum/usage.js
21857
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
21858
+ function plain(value) {
21859
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
21860
+ }
21861
+ var ScopedUsageReporter;
21862
+ var init_usage = __esm({
21863
+ "../core/dist/common-auth-embedded/claustrum/usage.js"() {
21864
+ "use strict";
21865
+ ScopedUsageReporter = class {
21866
+ options;
21867
+ #queue = /* @__PURE__ */ new Map();
21868
+ #latest = /* @__PURE__ */ new Map();
21869
+ #errors = /* @__PURE__ */ new Set();
21870
+ #timer;
21871
+ #running;
21872
+ #closing = false;
21873
+ #stopped = false;
21874
+ #dropped = 0;
21875
+ constructor(options) {
21876
+ this.options = options;
21877
+ }
21878
+ state() {
21879
+ return {
21880
+ pending: this.#queue.size,
21881
+ inFlight: this.#running !== void 0,
21882
+ dropped: this.#dropped
21883
+ };
21884
+ }
21885
+ report(credentialId, reading) {
21886
+ if (this.#closing || !this.options.client.reportUsageScoped)
21887
+ return;
21888
+ try {
21889
+ if (!this.options.owns(credentialId)) {
21890
+ this.#dropped++;
21891
+ return;
21892
+ }
21893
+ if (!plain(reading) || "credentialId" in reading || "vouched" in reading)
21894
+ throw new Error("invalid reading");
21895
+ const json = JSON.stringify(reading);
21896
+ if (Buffer.byteLength(json, "utf8") > 15360)
21897
+ throw new Error("oversized reading");
21898
+ const copy = JSON.parse(json);
21899
+ if (!plain(copy) || "credentialId" in copy || "vouched" in copy || typeof copy.observedAtMs !== "number" || !Number.isFinite(copy.observedAtMs))
21900
+ throw new Error("invalid reading");
21901
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
21902
+ this.#dropped++;
21903
+ return;
21904
+ }
21905
+ if (this.#queue.has(credentialId))
21906
+ this.#dropped++;
21907
+ this.#latest.set(credentialId, copy.observedAtMs);
21908
+ this.#queue.set(credentialId, copy);
21909
+ if (!this.#timer && !this.#running) {
21910
+ this.#timer = this.options.setTimeout(() => {
21911
+ this.#timer = void 0;
21912
+ this.#flush();
21913
+ }, 1e3);
21914
+ this.#timer.unref?.();
21915
+ }
21916
+ } catch {
21917
+ this.#dropped++;
21918
+ }
21919
+ }
21920
+ forget(credentialId) {
21921
+ if (this.#queue.delete(credentialId))
21922
+ this.#dropped++;
21923
+ this.#latest.delete(credentialId);
21924
+ }
21925
+ #flush() {
21926
+ if (this.#running || !this.#queue.size || this.#stopped)
21927
+ return this.#running;
21928
+ const running = Promise.resolve().then(async () => {
21929
+ while (!this.#stopped && this.#queue.size) {
21930
+ const entry = this.#queue.entries().next().value;
21931
+ if (!entry)
21932
+ break;
21933
+ const [credentialId, reading] = entry;
21934
+ this.#queue.delete(credentialId);
21935
+ try {
21936
+ const enrollmentToken = await this.options.token();
21937
+ if (this.#stopped || !this.options.owns(credentialId)) {
21938
+ if (!this.#stopped)
21939
+ this.#dropped++;
21940
+ continue;
21941
+ }
21942
+ await this.options.client.reportUsageScoped?.({
21943
+ credentialId,
21944
+ reading,
21945
+ enrollmentToken
21946
+ });
21947
+ } catch (error) {
21948
+ if (!this.#stopped)
21949
+ this.#dropped++;
21950
+ this.#log(error);
21951
+ }
21952
+ }
21953
+ });
21954
+ this.#running = running;
21955
+ void running.finally(() => {
21956
+ this.#running = void 0;
21957
+ });
21958
+ return running;
21959
+ }
21960
+ #log(error) {
21961
+ let code2 = "transport_error";
21962
+ try {
21963
+ if (error instanceof ClaustrumCredentialError3)
21964
+ code2 = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code2;
21965
+ if (this.#errors.has(code2))
21966
+ return;
21967
+ this.#errors.add(code2);
21968
+ this.options.logger.debug("claustrum usage report dropped", { code: code2 });
21969
+ } catch {
21970
+ }
21971
+ }
21972
+ /** Start the final flush; the custody's existing shutdown drain bounds it. */
21973
+ close() {
21974
+ this.#closing = true;
21975
+ if (this.#timer)
21976
+ this.options.clearTimeout(this.#timer);
21977
+ this.#timer = void 0;
21978
+ return this.#flush();
21979
+ }
21980
+ drop() {
21981
+ this.#stopped = true;
21982
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
21983
+ this.#running = void 0;
21984
+ this.#queue.clear();
21985
+ this.#latest.clear();
21986
+ }
21987
+ };
21988
+ }
21989
+ });
21990
+
21702
21991
  // ../core/dist/common-auth-embedded/claustrum/custody.js
21703
21992
  import { channel } from "node:diagnostics_channel";
21704
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
21993
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
21705
21994
  function isScopedCredentialRotation(served, current) {
21706
21995
  return current !== void 0 && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
21707
21996
  }
@@ -21716,6 +22005,12 @@ function scopedRetryReason(served, current) {
21716
22005
  return "version-unchanged";
21717
22006
  return "rotated";
21718
22007
  }
22008
+ function checkedEnrollmentToken(value) {
22009
+ if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
22010
+ throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
22011
+ }
22012
+ return value.token;
22013
+ }
21719
22014
  function decideScopedRetryAfter401(site, served, current, logger3 = defaultLogger) {
21720
22015
  const retry = isScopedCredentialRotation(served, current);
21721
22016
  logger3.debug("scoped 401 re-authorized", {
@@ -21824,6 +22119,7 @@ var init_custody = __esm({
21824
22119
  init_errors2();
21825
22120
  init_host_slot();
21826
22121
  init_shutdown();
22122
+ init_usage();
21827
22123
  init_watch();
21828
22124
  defaultLogger = createLogger2("claustrum");
21829
22125
  phaseDiagnostics = channel("common-auth.claustrum.phases");
@@ -21841,6 +22137,8 @@ var init_custody = __esm({
21841
22137
  #reports = /* @__PURE__ */ new WeakMap();
21842
22138
  #kept = /* @__PURE__ */ new Map();
21843
22139
  #keptAttempts = /* @__PURE__ */ new WeakMap();
22140
+ #usage;
22141
+ #usageServed = /* @__PURE__ */ new Map();
21844
22142
  #setTimeout;
21845
22143
  #clearTimeout;
21846
22144
  #outage = false;
@@ -21855,6 +22153,7 @@ var init_custody = __esm({
21855
22153
  #watches = /* @__PURE__ */ new Set();
21856
22154
  #tokenReads = /* @__PURE__ */ new Set();
21857
22155
  #warnShutdown;
22156
+ #onDrainTimeout;
21858
22157
  #disposing;
21859
22158
  constructor(options) {
21860
22159
  const tokenPath = options.tokenPath;
@@ -21874,13 +22173,21 @@ var init_custody = __esm({
21874
22173
  this.#warnShutdown = shutdownWarning(this.#logger);
21875
22174
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
21876
22175
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
22176
+ this.#usage = new ScopedUsageReporter({
22177
+ client: this.#client,
22178
+ owns: (id) => this.#usageServed.has(id),
22179
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
22180
+ logger: this.#logger,
22181
+ setTimeout: this.#setTimeout,
22182
+ clearTimeout: this.#clearTimeout
22183
+ });
21877
22184
  }
21878
22185
  /** A watch losing its transport is the same outage as an unreachable read. */
21879
22186
  transportLost(error) {
21880
22187
  if (this.#closed || this.#outage)
21881
22188
  return;
21882
22189
  this.#outage = true;
21883
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError();
22190
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError();
21884
22191
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
21885
22192
  this.#scheduleProbe();
21886
22193
  }
@@ -21949,10 +22256,7 @@ var init_custody = __esm({
21949
22256
  });
21950
22257
  }
21951
22258
  this.#check(signal);
21952
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
21953
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
21954
- }
21955
- return value.token;
22259
+ return checkedEnrollmentToken(value);
21956
22260
  }
21957
22261
  async #call(operation, signal) {
21958
22262
  this.#check(signal);
@@ -21976,7 +22280,7 @@ var init_custody = __esm({
21976
22280
  this.transportLost(error);
21977
22281
  else
21978
22282
  this.reachable();
21979
- if (error instanceof ClaustrumCredentialError3)
22283
+ if (error instanceof ClaustrumCredentialError4)
21980
22284
  throw error;
21981
22285
  if (classifyVaultFailure(error) === "unreachable")
21982
22286
  throw new ClaustrumUnreachableError();
@@ -22006,6 +22310,7 @@ var init_custody = __esm({
22006
22310
  token = await this.#token(signal);
22007
22311
  } catch (error) {
22008
22312
  this.#kept.clear();
22313
+ this.#clearUsageOwnership();
22009
22314
  throw error;
22010
22315
  }
22011
22316
  if (phaseDiagnostics.hasSubscribers)
@@ -22107,11 +22412,19 @@ var init_custody = __esm({
22107
22412
  else {
22108
22413
  this.reachable();
22109
22414
  this.#kept.clear();
22415
+ this.#clearUsageOwnership();
22110
22416
  }
22111
22417
  }
22112
22418
  /** Discard bearer material when a route is removed, declined or rebound. */
22113
22419
  forget(credentialId) {
22114
22420
  this.#kept.delete(credentialId);
22421
+ this.#usageServed.delete(credentialId);
22422
+ this.#usage.forget(credentialId);
22423
+ }
22424
+ #clearUsageOwnership() {
22425
+ for (const id of this.#usageServed.keys())
22426
+ this.#usage.forget(id);
22427
+ this.#usageServed.clear();
22115
22428
  }
22116
22429
  /** Apply an already-held roster; this never fetches credentials or writes it. */
22117
22430
  retain(identities) {
@@ -22121,6 +22434,11 @@ var init_custody = __esm({
22121
22434
  if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== kept.attempt.credentialType || identity3.accountIdentity !== kept.attempt.expectedAccountIdentity)
22122
22435
  this.forget(id);
22123
22436
  }
22437
+ for (const [id, served] of this.#usageServed) {
22438
+ const identity3 = current.get(id);
22439
+ if (!identity3?.enabled || identity3.state !== "active" || identity3.credentialType !== served.credentialType || identity3.accountIdentity !== served.accountIdentity)
22440
+ this.forget(id);
22441
+ }
22124
22442
  }
22125
22443
  /** A frozen, non-secret summary for a plugin's status display. */
22126
22444
  keptReceiptState() {
@@ -22152,6 +22470,7 @@ var init_custody = __esm({
22152
22470
  token = await this.#token(signal);
22153
22471
  } catch (error) {
22154
22472
  this.#kept.clear();
22473
+ this.#clearUsageOwnership();
22155
22474
  throw error;
22156
22475
  }
22157
22476
  if (this.#outage && kept) {
@@ -22161,6 +22480,7 @@ var init_custody = __esm({
22161
22480
  try {
22162
22481
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
22163
22482
  this.#kept.set(credentialId, { attempt, routeId, since: null });
22483
+ this.#usageServed.set(credentialId, { ...identity3 });
22164
22484
  return attempt;
22165
22485
  } catch (error) {
22166
22486
  this.#check(signal);
@@ -22345,6 +22665,23 @@ var init_custody = __esm({
22345
22665
  }
22346
22666
  };
22347
22667
  }
22668
+ /**
22669
+ * Queue reply quota metadata and return synchronously. Pass rate-limit
22670
+ * headers only, never tokens: the library does not filter header names.
22671
+ * Only credentials served by this custody and retained in its roster report.
22672
+ * Hosts managing their own roster must call retain() when that roster changes.
22673
+ */
22674
+ reportUsage(input2) {
22675
+ if (this.#closed)
22676
+ return;
22677
+ try {
22678
+ this.#usage.report(input2.credentialId, input2.reading);
22679
+ } catch {
22680
+ }
22681
+ }
22682
+ usageReportState() {
22683
+ return this.#usage.state();
22684
+ }
22348
22685
  close() {
22349
22686
  if (this.#closed)
22350
22687
  return;
@@ -22356,12 +22693,23 @@ var init_custody = __esm({
22356
22693
  watch.stop();
22357
22694
  this.#watches.clear();
22358
22695
  this.#kept.clear();
22359
- this.#client.close();
22696
+ const usage = this.#usage.close();
22697
+ if (usage) {
22698
+ this.#tokenReads.add(usage);
22699
+ void usage.then(() => this.#tokenReads.delete(usage));
22700
+ } else
22701
+ this.#client.close();
22702
+ this.#disposing = drainShutdown(this.#tokenReads, (count3) => (this.#onDrainTimeout ?? this.#warnShutdown)(count3)).finally(() => {
22703
+ this.#usage.drop();
22704
+ this.#usageServed.clear();
22705
+ if (usage)
22706
+ this.#client.close();
22707
+ });
22360
22708
  }
22361
- /** Stop immediately; allow token reads 2 s and share an owner's timeout warning. */
22709
+ /** Stop accepting work; give token reads and reply reports one shared 2 s drain. */
22362
22710
  async dispose(onTimeout = this.#warnShutdown) {
22711
+ this.#onDrainTimeout = onTimeout;
22363
22712
  this.close();
22364
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
22365
22713
  await this.#disposing;
22366
22714
  }
22367
22715
  };
@@ -22451,7 +22799,7 @@ var init_interlock = __esm({
22451
22799
 
22452
22800
  // ../core/dist/common-auth-embedded/claustrum/roster.js
22453
22801
  import { createHash as createHash7 } from "node:crypto";
22454
- import { stat as stat5 } from "node:fs/promises";
22802
+ import { stat as stat6 } from "node:fs/promises";
22455
22803
  import { resolve as resolve8 } from "node:path";
22456
22804
  function vaultRosterSeed(roster) {
22457
22805
  return {
@@ -22602,6 +22950,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
22602
22950
  return {
22603
22951
  version: 1,
22604
22952
  view: inventory.view,
22953
+ ...previous?.limits !== void 0 && { limits: previous.limits },
22605
22954
  complete,
22606
22955
  ...!complete && {
22607
22956
  rejected: inventory.skipped.map((record3) => ({
@@ -22672,6 +23021,7 @@ function decodeRoster(value) {
22672
23021
  // that was used whole, so it reads as complete.
22673
23022
  complete: value.complete !== false,
22674
23023
  ...rejected && { rejected },
23024
+ ...value.limits !== void 0 && { limits: value.limits },
22675
23025
  rows,
22676
23026
  declined
22677
23027
  };
@@ -22680,6 +23030,12 @@ function decodedVaultRoster(roster) {
22680
23030
  return decodeRoster(JSON.parse(JSON.stringify(roster)));
22681
23031
  }
22682
23032
  async function readVaultRoster(path5) {
23033
+ if (windowsPrivateFiles)
23034
+ return readFreshVaultRoster(path5);
23035
+ const roster = await rosterReadCache.read([path5], ([resolvedPath = path5]) => readFreshVaultRoster(resolvedPath));
23036
+ return structuredClone(roster);
23037
+ }
23038
+ async function readFreshVaultRoster(path5) {
22683
23039
  let text2;
22684
23040
  try {
22685
23041
  text2 = await readPrivateText(path5, windowsPrivateFiles);
@@ -22698,19 +23054,26 @@ async function readVaultRoster(path5) {
22698
23054
  }
22699
23055
  async function mutateVaultRoster(path5, change, options = {}) {
22700
23056
  return withLock(path5, { ...WRITE_LOCK, signal: options.signal }, async (lock) => {
22701
- const current = await readVaultRoster(path5);
23057
+ const current = await readFreshVaultRoster(path5);
22702
23058
  const { next, result } = await change(current, {
22703
23059
  assertOwned: () => lock.assertOwned()
22704
23060
  });
22705
23061
  if (next) {
22706
23062
  await lock.assertOwned();
22707
- await writeJsonAtomic2(path5, next, {
22708
- beforeRename: async () => {
22709
- await options.beforePublish?.();
22710
- options.signal?.throwIfAborted();
22711
- await lock.assertOwned();
22712
- }
22713
- });
23063
+ try {
23064
+ await writeJsonAtomic2(path5, next, {
23065
+ beforeRename: async () => {
23066
+ await options.beforePublish?.();
23067
+ options.signal?.throwIfAborted();
23068
+ await lock.assertOwned();
23069
+ }
23070
+ });
23071
+ } catch (error) {
23072
+ if (error && typeof error === "object" && "published" in error && error.published === true)
23073
+ options.onPublished?.();
23074
+ throw error;
23075
+ }
23076
+ options.onPublished?.();
22714
23077
  }
22715
23078
  return result;
22716
23079
  });
@@ -22858,7 +23221,7 @@ function isVaultRosterLockRefusal(path5, error) {
22858
23221
  }
22859
23222
  async function fileStamp(path5) {
22860
23223
  try {
22861
- const { dev, ino, size, mtimeMs } = await stat5(path5);
23224
+ const { dev, ino, size, mtimeMs } = await stat6(path5);
22862
23225
  return { dev, ino, size, mtimeMs };
22863
23226
  } catch {
22864
23227
  return void 0;
@@ -22998,10 +23361,11 @@ function resolveVaultPrimary(input2) {
22998
23361
  ...previous && previous.accountIdentity !== identity3 && { replaced: previous }
22999
23362
  };
23000
23363
  }
23001
- var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries, UNLOCKED_READ_ATTEMPTS;
23364
+ var DEFAULT_ROUTE_PREFIX, SKIPPED_REASONS, rosterReadCache, WRITE_LOCK, DISCOVERY_LEASE, pendingDiscoveries, UNLOCKED_READ_ATTEMPTS;
23002
23365
  var init_roster = __esm({
23003
23366
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
23004
23367
  "use strict";
23368
+ init_file_read_cache();
23005
23369
  init_fs();
23006
23370
  init_private_files();
23007
23371
  init_quota();
@@ -23016,6 +23380,9 @@ var init_roster = __esm({
23016
23380
  "blank account identity",
23017
23381
  "empty state"
23018
23382
  ]);
23383
+ rosterReadCache = new FileReadCache({
23384
+ followSymlinks: true
23385
+ });
23019
23386
  WRITE_LOCK = {
23020
23387
  name: "claustrum-roster-write",
23021
23388
  ttlMs: 1e4,
@@ -23883,6 +24250,33 @@ var init_consumer = __esm({
23883
24250
  combined.dispose();
23884
24251
  }
23885
24252
  }
24253
+ /**
24254
+ * Queue reply quota metadata without waiting or throwing. Pass rate-limit
24255
+ * headers only, never tokens: the library does not filter header names.
24256
+ * The credential must have been served by this host and still belong to the route.
24257
+ */
24258
+ reportUsage(input2) {
24259
+ if (this.#shutdown.signal.aborted)
24260
+ return;
24261
+ try {
24262
+ const row = this.#roster?.rows.find((row2) => row2.routeId === input2.routeId);
24263
+ if (!row?.enabled || row.state !== "active" || row.credentialId !== input2.credentialId && !row.aliases?.includes(input2.credentialId))
24264
+ return;
24265
+ if (this.#hub) {
24266
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
24267
+ this.#lease.custody.reportUsage(input2);
24268
+ } else
24269
+ this.#custody?.reportUsage(input2);
24270
+ } catch {
24271
+ }
24272
+ }
24273
+ usageReportState() {
24274
+ try {
24275
+ return (this.#hub ? this.#lease?.custody : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 };
24276
+ } catch {
24277
+ return { pending: 0, inFlight: false, dropped: 0 };
24278
+ }
24279
+ }
23886
24280
  async reportFailure(attempt, status, source) {
23887
24281
  this.#assertOpen();
23888
24282
  if (this.#hub) {
@@ -24044,7 +24438,7 @@ var init_consumer = __esm({
24044
24438
  // ../core/dist/common-auth-embedded/claustrum/hub.js
24045
24439
  import { createHash as createHash8 } from "node:crypto";
24046
24440
  import { channel as channel2 } from "node:diagnostics_channel";
24047
- import { readdir, stat as stat6 } from "node:fs/promises";
24441
+ import { readdir, stat as stat7 } from "node:fs/promises";
24048
24442
  import { dirname as dirname10, join as join8, resolve as resolve10 } from "node:path";
24049
24443
  function canonicalJson3(value, path5 = /* @__PURE__ */ new Set()) {
24050
24444
  if (value === null)
@@ -24494,6 +24888,14 @@ var init_hub = __esm({
24494
24888
  check();
24495
24889
  return custody.reportFailure(attempt, status, source);
24496
24890
  },
24891
+ reportUsage: (input2) => {
24892
+ if (!state.released && !generation.ended)
24893
+ custody.reportUsage(input2);
24894
+ },
24895
+ usageReportState: () => {
24896
+ check();
24897
+ return custody.usageReportState();
24898
+ },
24497
24899
  forget: (credentialId) => {
24498
24900
  check();
24499
24901
  custody.forget(credentialId);
@@ -24777,7 +25179,7 @@ var init_hub = __esm({
24777
25179
  let newest;
24778
25180
  for (const path5 of candidates) {
24779
25181
  try {
24780
- const modified = (await stat6(path5)).mtimeMs;
25182
+ const modified = (await stat7(path5)).mtimeMs;
24781
25183
  const roster = await readVaultRoster(path5);
24782
25184
  if (roster && (!newest || modified > newest.modified))
24783
25185
  newest = { modified, roster };
@@ -25037,7 +25439,7 @@ __export(claustrum_exports, {
25037
25439
  ChangeNoticeReader: () => ChangeNoticeReader,
25038
25440
  ClaustrumConsumer: () => ClaustrumConsumer,
25039
25441
  ClaustrumConsumerError: () => ClaustrumConsumerError,
25040
- ClaustrumCredentialError: () => ClaustrumCredentialError4,
25442
+ ClaustrumCredentialError: () => ClaustrumCredentialError5,
25041
25443
  ClaustrumDiscoveryHub: () => ClaustrumDiscoveryHub,
25042
25444
  ClaustrumEnrollmentManager: () => ClaustrumEnrollmentManager,
25043
25445
  ClaustrumScopedCustody: () => ClaustrumScopedCustody,
@@ -25094,7 +25496,7 @@ __export(claustrum_exports, {
25094
25496
  vaultRoutingRows: () => vaultRoutingRows
25095
25497
  });
25096
25498
  import { ClaustrumClient } from "@cortexkit/claustrum-client";
25097
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
25499
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
25098
25500
  async function connectClaustrumScopedClient(options) {
25099
25501
  const { connectTimeoutMs, ...client } = options;
25100
25502
  const limit = connectTimeoutMs ?? SCOPED_CONNECT_TIMEOUT_MS;
@@ -25144,7 +25546,7 @@ var init_claustrum = __esm({
25144
25546
 
25145
25547
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
25146
25548
  import { rmdirSync, statSync as statSync2, utimesSync } from "node:fs";
25147
- import { mkdir as mkdir9, rmdir, stat as stat7, utimes } from "node:fs/promises";
25549
+ import { mkdir as mkdir9, rmdir, stat as stat8, utimes } from "node:fs/promises";
25148
25550
  function sameDirectory(observed, identity3) {
25149
25551
  return observed.dev === identity3.dev && observed.ino === identity3.ino;
25150
25552
  }
@@ -25172,7 +25574,7 @@ async function acquire(path5, stale) {
25172
25574
  throw held();
25173
25575
  let mtime;
25174
25576
  try {
25175
- mtime = (await stat7(path5)).mtime.getTime();
25577
+ mtime = (await stat8(path5)).mtime.getTime();
25176
25578
  } catch (error2) {
25177
25579
  if (errorCode(error2) === "ENOENT")
25178
25580
  return acquire(path5, 0);
@@ -25185,7 +25587,7 @@ async function acquire(path5, stale) {
25185
25587
  }
25186
25588
  let created;
25187
25589
  try {
25188
- const st = await stat7(path5);
25590
+ const st = await stat8(path5);
25189
25591
  created = { dev: st.dev, ino: st.ino };
25190
25592
  } catch {
25191
25593
  created = void 0;
@@ -25195,14 +25597,14 @@ async function acquire(path5, stale) {
25195
25597
  const probe = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
25196
25598
  await utimes(path5, probe, probe);
25197
25599
  }
25198
- const observed = await stat7(path5);
25600
+ const observed = await stat8(path5);
25199
25601
  const mtime = observed.mtime.getTime();
25200
25602
  precision ??= mtime % 1e3 === 0 ? "s" : "ms";
25201
25603
  return { dev: observed.dev, ino: observed.ino, mtime };
25202
25604
  } catch (error) {
25203
25605
  try {
25204
25606
  if (created) {
25205
- const current = await stat7(path5).catch(() => void 0);
25607
+ const current = await stat8(path5).catch(() => void 0);
25206
25608
  if (current && current.dev === created.dev && current.ino === created.ino)
25207
25609
  await remove(path5).catch(() => {
25208
25610
  });
@@ -25302,7 +25704,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
25302
25704
  }
25303
25705
  let observed;
25304
25706
  try {
25305
- observed = await stat7(path5);
25707
+ observed = await stat8(path5);
25306
25708
  } catch (error) {
25307
25709
  if (errorCode(error) !== "ENOENT")
25308
25710
  throw error;
@@ -25441,13 +25843,13 @@ async function safeRead(path5, privateFile = false, afterReadCheck) {
25441
25843
  let file;
25442
25844
  try {
25443
25845
  file = await open7(path5, constants2.O_RDONLY | constants2.O_NOFOLLOW);
25444
- const stat16 = await file.stat();
25445
- if (!stat16.isFile() || privateFile && (stat16.mode & 511) !== 384) {
25846
+ const stat18 = await file.stat();
25847
+ if (!stat18.isFile() || privateFile && (stat18.mode & 511) !== 384) {
25446
25848
  throw new PiSlotError("unsafe-path");
25447
25849
  }
25448
25850
  await afterReadCheck?.(path5);
25449
25851
  const current = await lstat5(path5);
25450
- if (!current.isFile() || current.dev !== stat16.dev || current.ino !== stat16.ino) {
25852
+ if (!current.isFile() || current.dev !== stat18.dev || current.ino !== stat18.ino) {
25451
25853
  throw new PiSlotError("unsafe-path");
25452
25854
  }
25453
25855
  const bytes = await file.readFile();
@@ -29008,6 +29410,9 @@ function loadBackend2() {
29008
29410
  });
29009
29411
  return backend2;
29010
29412
  }
29413
+ function isWindowsSharingViolation2(error) {
29414
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
29415
+ }
29011
29416
  async function privateOperation2(path5, stage, operation) {
29012
29417
  try {
29013
29418
  return await operation();
@@ -30222,7 +30627,7 @@ var init_vault_insula_quota = __esm({
30222
30627
  });
30223
30628
 
30224
30629
  // src/plugin/vault-custody.ts
30225
- import { chmod as chmod3, mkdir as mkdir11, readFile as readFile9, stat as stat8 } from "node:fs/promises";
30630
+ import { chmod as chmod3, mkdir as mkdir11, readFile as readFile9, stat as stat9 } from "node:fs/promises";
30226
30631
  import { join as join11 } from "node:path";
30227
30632
  async function enrollmentFilesIdentity(paths) {
30228
30633
  const takenAt = performance.now();
@@ -30230,7 +30635,7 @@ async function enrollmentFilesIdentity(paths) {
30230
30635
  const parts = [];
30231
30636
  for (const path5 of [paths.tokenPath, paths.statePath]) {
30232
30637
  try {
30233
- const info = await stat8(path5, { bigint: true });
30638
+ const info = await stat9(path5, { bigint: true });
30234
30639
  if (info.ino === 0n) coarse = true;
30235
30640
  parts.push(
30236
30641
  `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
@@ -31126,7 +31531,7 @@ var init_process_heartbeat = __esm({
31126
31531
  });
31127
31532
 
31128
31533
  // src/version-fence.ts
31129
- import { readdir as readdir2, readFile as readFile11, stat as stat9, unlink as unlink9 } from "node:fs/promises";
31534
+ import { readdir as readdir2, readFile as readFile11, stat as stat10, unlink as unlink9 } from "node:fs/promises";
31130
31535
  import { homedir as homedir3, uptime } from "node:os";
31131
31536
  import { join as join13 } from "node:path";
31132
31537
  function defaultStateHome() {
@@ -31246,7 +31651,7 @@ async function staleRecord(path5, record3, boot, heartbeat) {
31246
31651
  let start = heartbeat ? record3.startedAt : void 0;
31247
31652
  if (start === void 0) {
31248
31653
  try {
31249
- start = (await stat9(path5)).mtimeMs;
31654
+ start = (await stat10(path5)).mtimeMs;
31250
31655
  } catch {
31251
31656
  return false;
31252
31657
  }
@@ -31471,7 +31876,7 @@ import {
31471
31876
  readFile as readFile12,
31472
31877
  rename as rename10,
31473
31878
  rmdir as rmdir2,
31474
- stat as stat10,
31879
+ stat as stat11,
31475
31880
  unlink as unlink10
31476
31881
  } from "node:fs/promises";
31477
31882
  import { basename as basename4, dirname as dirname15, join as join14, resolve as resolve15 } from "node:path";
@@ -32390,7 +32795,7 @@ async function physicalAliases(location, files) {
32390
32795
  async function samePhysical(a, b) {
32391
32796
  const id = async (path5) => {
32392
32797
  try {
32393
- const info = await stat10(path5, { bigint: true });
32798
+ const info = await stat11(path5, { bigint: true });
32394
32799
  return info.ino === 0n ? void 0 : `${info.dev}:${info.ino}`;
32395
32800
  } catch (error) {
32396
32801
  const code2 = error.code;
@@ -32435,7 +32840,8 @@ async function removeOldCopies(location, files, present5, layoutLock, input2) {
32435
32840
  if (!await unlinkIfIdentical(
32436
32841
  file,
32437
32842
  location.stateHomeDir,
32438
- () => beforeRemove(file.old, layoutLock, input2.steps)
32843
+ () => beforeRemove(file.old, layoutLock, input2.steps),
32844
+ input2.steps?.oldFileIO
32439
32845
  ))
32440
32846
  kept.push(file.old);
32441
32847
  }
@@ -32457,21 +32863,21 @@ async function sameBytes(a, b) {
32457
32863
  return false;
32458
32864
  }
32459
32865
  }
32460
- function isWindowsSharingError(error) {
32866
+ function isWindowsSharingError(error, platform) {
32461
32867
  const code2 = error?.code;
32462
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32868
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32463
32869
  }
32464
- async function unlinkIfIdentical(file, stateDir, guard) {
32870
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink10 }) {
32465
32871
  const started = performance.now();
32466
32872
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
32467
32873
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
32468
32874
  let same;
32469
32875
  try {
32470
- same = (await readFile12(file.old)).equals(await readFile12(file.next));
32876
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
32471
32877
  } catch (error) {
32472
32878
  if (error.code === "ENOENT" && !await exists2(file.old))
32473
32879
  return true;
32474
- if (isWindowsSharingError(error)) {
32880
+ if (isWindowsSharingError(error, io.platform)) {
32475
32881
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
32476
32882
  continue;
32477
32883
  }
@@ -32480,11 +32886,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32480
32886
  if (!same) throw credentialConflict(stateDir, file);
32481
32887
  await guard();
32482
32888
  try {
32483
- await unlink10(file.old);
32889
+ await io.unlink(file.old);
32484
32890
  return true;
32485
32891
  } catch (error) {
32486
32892
  if (error.code === "ENOENT") return true;
32487
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32893
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32488
32894
  return false;
32489
32895
  }
32490
32896
  }
@@ -32655,7 +33061,7 @@ function lockHolderText(name) {
32655
33061
  }
32656
33062
  async function exists2(path5) {
32657
33063
  try {
32658
- await stat10(path5);
33064
+ await stat11(path5);
32659
33065
  return true;
32660
33066
  } catch (error) {
32661
33067
  const code2 = error.code;
@@ -36645,16 +37051,16 @@ async function select2(terminal, items, options) {
36645
37051
  // src/common-auth-embedded/claustrum/enrollment.js
36646
37052
  import { createHash as createHash13, randomBytes as randomBytes5, randomUUID as randomUUID17 } from "node:crypto";
36647
37053
  import { constants as fsConstants2 } from "node:fs";
36648
- 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";
37054
+ import { chmod as chmod6, mkdir as mkdir15, open as open10, readFile as readFile14, realpath as realpath4, rename as rename12, stat as stat14, unlink as unlink11 } from "node:fs/promises";
36649
37055
  import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute4, join as join20, resolve as resolve19 } from "node:path";
36650
- import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
37056
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
36651
37057
 
36652
37058
  // src/common-auth-embedded/fs/file-read-cache.js
36653
- import { lstat as lstat7 } from "node:fs/promises";
37059
+ import { lstat as lstat7, stat as stat12 } from "node:fs/promises";
36654
37060
  import { resolve as resolve18 } from "node:path";
36655
- async function identity2(path5) {
37061
+ async function identity2(path5, followSymlinks) {
36656
37062
  try {
36657
- const metadata = await lstat7(path5);
37063
+ const metadata = await (followSymlinks ? stat12(path5) : lstat7(path5));
36658
37064
  return metadata.isFile() ? metadata : void 0;
36659
37065
  } catch (error) {
36660
37066
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -36666,11 +37072,15 @@ function sameIdentity2(left, right) {
36666
37072
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
36667
37073
  }
36668
37074
  var FileReadCache2 = class {
37075
+ #followSymlinks;
36669
37076
  #entries = /* @__PURE__ */ new Map();
37077
+ constructor(options = {}) {
37078
+ this.#followSymlinks = options.followSymlinks ?? false;
37079
+ }
36670
37080
  async read(paths, read, validateHit) {
36671
37081
  const resolvedPaths = paths.map((path5) => resolve18(path5));
36672
37082
  const key = JSON.stringify(resolvedPaths);
36673
- const probed = await Promise.all(resolvedPaths.map(identity2));
37083
+ const probed = await Promise.all(resolvedPaths.map((path5) => identity2(path5, this.#followSymlinks)));
36674
37084
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
36675
37085
  const cached = this.#entries.get(key);
36676
37086
  if (identities && cached && identities.every((entry, index) => {
@@ -36719,7 +37129,7 @@ init_private_files2();
36719
37129
  // src/common-auth-embedded/fs/refresh-file-lock.js
36720
37130
  init_private_files2();
36721
37131
  import { randomUUID as randomUUID16 } from "node:crypto";
36722
- import { lstat as lstat8, mkdir as mkdir14, open as open9, readFile as readFile13, rename as rename11, rm as rm6, stat as stat11 } from "node:fs/promises";
37132
+ import { lstat as lstat8, mkdir as mkdir14, open as open9, readFile as readFile13, rename as rename11, rm as rm6, stat as stat13 } from "node:fs/promises";
36723
37133
  import { dirname as dirname19, join as join19 } from "node:path";
36724
37134
 
36725
37135
  // src/common-auth-embedded/fs/with-lock.js
@@ -36973,7 +37383,7 @@ async function acquireRefreshFileLockWithClock2(options) {
36973
37383
  };
36974
37384
  }
36975
37385
  try {
36976
- const current = await stat11(lockPath);
37386
+ const current = await stat13(lockPath);
36977
37387
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
36978
37388
  if (legacyExpiry > now())
36979
37389
  return { status: "live" };
@@ -37022,37 +37432,83 @@ async function acquireRefreshFileLockWithClock2(options) {
37022
37432
  await rm6(path5, { recursive: true, force: true }).catch(() => {
37023
37433
  });
37024
37434
  }
37025
- async function releaseEvictionMarker() {
37026
- if (await ownsEvictionMarker()) {
37027
- await removeLeaseObject(evictPath);
37028
- }
37435
+ function isRetryableRemoval(error, path5) {
37436
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path5)
37437
+ return false;
37438
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
37439
+ }
37440
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
37441
+ let original;
37442
+ let delayMs = 5;
37443
+ while (await stillOwned()) {
37444
+ try {
37445
+ await removeLeaseObject(path5);
37446
+ return;
37447
+ } catch (error) {
37448
+ if (!isRetryableRemoval(error, path5))
37449
+ throw error;
37450
+ original ??= error;
37451
+ }
37452
+ const remainingMs = deadline - performance.now();
37453
+ if (remainingMs <= 0)
37454
+ throw original;
37455
+ await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
37456
+ if (performance.now() >= deadline)
37457
+ throw original;
37458
+ delayMs = Math.min(delayMs * 2, 50);
37459
+ }
37460
+ }
37461
+ async function releaseEvictionMarker(deadline) {
37462
+ let ownedDirectory;
37463
+ await removeOwnedLeaseObject(evictPath, async () => {
37464
+ if (!windowsPrivateFiles2)
37465
+ return ownsEvictionMarker();
37466
+ const current = await lstat8(evictPath).catch((error) => {
37467
+ if (error.code !== "ENOENT")
37468
+ throw error;
37469
+ return void 0;
37470
+ });
37471
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
37472
+ return false;
37473
+ if (await ownsEvictionMarker()) {
37474
+ ownedDirectory = current;
37475
+ return true;
37476
+ }
37477
+ if (!ownedDirectory)
37478
+ return false;
37479
+ try {
37480
+ await stat13(evictOwnerPath);
37481
+ return false;
37482
+ } catch (error) {
37483
+ if (error.code !== "ENOENT")
37484
+ throw error;
37485
+ return true;
37486
+ }
37487
+ }, deadline);
37029
37488
  }
37030
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
37489
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
37031
37490
  if (!created)
37032
37491
  return false;
37033
- let current;
37034
- try {
37035
- const st = await lstat8(evictPath);
37036
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
37037
- } catch {
37038
- return false;
37039
- }
37040
- if (!sameMarkerDirectory2(created, current))
37041
- return false;
37492
+ let stillOurs = false;
37042
37493
  try {
37043
- await stat11(evictOwnerPath);
37044
- return true;
37045
- } catch (error) {
37046
- if (error.code !== "ENOENT")
37047
- return true;
37048
- }
37049
- try {
37050
- await removeLeaseObject(evictPath);
37494
+ await removeOwnedLeaseObject(evictPath, async () => {
37495
+ stillOurs = false;
37496
+ const st = await lstat8(evictPath).catch(() => void 0);
37497
+ if (!st || !sameMarkerDirectory2(created, st))
37498
+ return false;
37499
+ stillOurs = true;
37500
+ try {
37501
+ await stat13(evictOwnerPath);
37502
+ return false;
37503
+ } catch (error) {
37504
+ return error.code === "ENOENT";
37505
+ }
37506
+ }, deadline);
37051
37507
  } catch {
37052
37508
  }
37053
- return true;
37509
+ return stillOurs;
37054
37510
  }
37055
- async function tryAcquireEvictionMarker() {
37511
+ async function tryAcquireEvictionMarker(deadline) {
37056
37512
  if (windowsPrivateFiles2)
37057
37513
  await createPrivateDirectoryExclusive2(evictPath);
37058
37514
  else
@@ -37076,11 +37532,11 @@ async function acquireRefreshFileLockWithClock2(options) {
37076
37532
  else
37077
37533
  await createExclusiveText2(evictOwnerPath, bytes);
37078
37534
  } catch (error) {
37079
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
37535
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
37080
37536
  if (isLostMarkerRaceError2(error) && !stillOurs)
37081
37537
  return false;
37082
37538
  try {
37083
- await releaseEvictionMarker();
37539
+ await releaseEvictionMarker(deadline);
37084
37540
  } catch {
37085
37541
  }
37086
37542
  throw error;
@@ -37089,10 +37545,10 @@ async function acquireRefreshFileLockWithClock2(options) {
37089
37545
  await options.onStep("eviction-marker-acquired");
37090
37546
  return true;
37091
37547
  }
37092
- async function recoverStaleEvictionMarker() {
37548
+ async function recoverStaleEvictionMarker(deadline) {
37093
37549
  let evictStat;
37094
37550
  try {
37095
- evictStat = await stat11(evictPath);
37551
+ evictStat = await stat13(evictPath);
37096
37552
  } catch (error) {
37097
37553
  if (error.code === "ENOENT")
37098
37554
  return "missing";
@@ -37110,7 +37566,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37110
37566
  if (evictStat.mtimeMs + EVICT_TTL > now()) {
37111
37567
  let hasOwner = true;
37112
37568
  try {
37113
- await stat11(evictOwnerPath);
37569
+ await stat13(evictOwnerPath);
37114
37570
  } catch (error) {
37115
37571
  if (error.code === "ENOENT")
37116
37572
  hasOwner = false;
@@ -37134,12 +37590,22 @@ async function acquireRefreshFileLockWithClock2(options) {
37134
37590
  }
37135
37591
  if (options.onStep)
37136
37592
  await options.onStep("stale-marker-claimed");
37137
- await removeLeaseObject(claimedPath);
37593
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
37594
+ await removeOwnedLeaseObject(claimedPath, async () => {
37595
+ if (!claimedIdentity)
37596
+ return true;
37597
+ const current = await lstat8(claimedPath).catch((error) => {
37598
+ if (error.code !== "ENOENT")
37599
+ throw error;
37600
+ return void 0;
37601
+ });
37602
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
37603
+ }, deadline);
37138
37604
  return "recovered";
37139
37605
  }
37140
- async function withEvictionMarker(action) {
37606
+ async function withEvictionMarker(action, deadline) {
37141
37607
  try {
37142
- if (!await tryAcquireEvictionMarker())
37608
+ if (!await tryAcquireEvictionMarker(deadline))
37143
37609
  return false;
37144
37610
  } catch (error) {
37145
37611
  if (error.code === "EEXIST") {
@@ -37156,11 +37622,23 @@ async function acquireRefreshFileLockWithClock2(options) {
37156
37622
  }
37157
37623
  throw error;
37158
37624
  }
37625
+ let actionFailed = false;
37626
+ let actionError;
37159
37627
  try {
37160
37628
  await action();
37161
- } finally {
37162
- await releaseEvictionMarker();
37629
+ } catch (error) {
37630
+ actionFailed = true;
37631
+ actionError = error;
37632
+ }
37633
+ try {
37634
+ await releaseEvictionMarker(deadline);
37635
+ } catch (error) {
37636
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
37637
+ throw actionError;
37638
+ throw error;
37163
37639
  }
37640
+ if (actionFailed)
37641
+ throw actionError;
37164
37642
  return true;
37165
37643
  }
37166
37644
  async function relinquishLockAfterMarkerLoss() {
@@ -37397,6 +37875,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37397
37875
  await renewalInFlight;
37398
37876
  const deadline = performance.now() + EVICT_TTL + 1e3;
37399
37877
  let delayMs = 5;
37878
+ let removalError;
37400
37879
  for (; ; ) {
37401
37880
  try {
37402
37881
  let removalConfirmed = false;
@@ -37421,7 +37900,7 @@ async function acquireRefreshFileLockWithClock2(options) {
37421
37900
  return;
37422
37901
  await removeLeaseObject(lockPath);
37423
37902
  removalConfirmed = true;
37424
- });
37903
+ }, deadline);
37425
37904
  if (markerAcquired) {
37426
37905
  if (windowsPrivateFiles2 && !removalConfirmed)
37427
37906
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -37432,20 +37911,25 @@ async function acquireRefreshFileLockWithClock2(options) {
37432
37911
  }
37433
37912
  if (signal?.aborted)
37434
37913
  return;
37435
- await recoverStaleEvictionMarker();
37914
+ await recoverStaleEvictionMarker(deadline);
37436
37915
  } catch (error) {
37437
- if (windowsPrivateFiles2)
37438
- throw error;
37439
- return;
37916
+ if (!isRetryableRemoval(error, lockPath)) {
37917
+ if (windowsPrivateFiles2)
37918
+ throw error;
37919
+ return;
37920
+ }
37921
+ removalError ??= error;
37440
37922
  }
37441
37923
  const remainingMs = deadline - performance.now();
37442
37924
  if (remainingMs <= 0)
37443
37925
  break;
37444
37926
  await new Promise((resolve27) => setTimeout(resolve27, Math.min(delayMs, remainingMs)));
37927
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
37928
+ break;
37445
37929
  delayMs = Math.min(delayMs * 2, 50);
37446
37930
  }
37447
37931
  if (windowsPrivateFiles2)
37448
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
37932
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
37449
37933
  code: "ETIMEDOUT"
37450
37934
  });
37451
37935
  }
@@ -37488,7 +37972,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
37488
37972
  "pending_queue_full"
37489
37973
  ]);
37490
37974
  function classifyEnrollmentError2(error) {
37491
- if (!(error instanceof ClaustrumCredentialError5))
37975
+ if (!(error instanceof ClaustrumCredentialError6))
37492
37976
  return void 0;
37493
37977
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
37494
37978
  return { code: error.code, disposition: "terminal" };
@@ -37699,7 +38183,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
37699
38183
  }
37700
38184
  let privateGroup;
37701
38185
  for (; ; ) {
37702
- const metadata = await stat12(component).catch(() => void 0);
38186
+ const metadata = await stat14(component).catch(() => void 0);
37703
38187
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
37704
38188
  if (privateGroup === void 0) {
37705
38189
  privateGroup = gid !== void 0 && await isPrivateGroup2(uid, gid, options);
@@ -37728,7 +38212,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
37728
38212
  return;
37729
38213
  }
37730
38214
  await mkdir15(directory, { recursive: true, mode: 448 });
37731
- const metadata = await stat12(directory);
38215
+ const metadata = await stat14(directory);
37732
38216
  const uid = process.geteuid?.();
37733
38217
  if (uid !== void 0 && metadata.uid !== uid) {
37734
38218
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -38317,7 +38801,7 @@ function setupPaths(io = {}) {
38317
38801
  }
38318
38802
 
38319
38803
  // src/common-auth-embedded/setup/detect.js
38320
- function stat13(path5, kind) {
38804
+ function stat15(path5, kind) {
38321
38805
  try {
38322
38806
  return statSync5(path5)[kind]();
38323
38807
  } catch {
@@ -38326,12 +38810,12 @@ function stat13(path5, kind) {
38326
38810
  }
38327
38811
  var defaultSetupFileSystem = {
38328
38812
  exists: existsSync6,
38329
- isFile: (path5) => stat13(path5, "isFile"),
38330
- isDirectory: (path5) => stat13(path5, "isDirectory"),
38813
+ isFile: (path5) => stat15(path5, "isFile"),
38814
+ isDirectory: (path5) => stat15(path5, "isDirectory"),
38331
38815
  isExecutable(path5) {
38332
38816
  try {
38333
38817
  accessSync(path5, constants3.X_OK);
38334
- return stat13(path5, "isFile");
38818
+ return stat15(path5, "isFile");
38335
38819
  } catch {
38336
38820
  return false;
38337
38821
  }
@@ -38830,6 +39314,12 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
38830
39314
  await writeEnrollmentTokenFile3(path5, file);
38831
39315
  }
38832
39316
  });
39317
+ await fence();
39318
+ const initial = await manager.status();
39319
+ if (initial.state === "approved") {
39320
+ printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
39321
+ return;
39322
+ }
38833
39323
  printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
38834
39324
  const deadline = now() + ENROLLMENT_WAIT_MS;
38835
39325
  let printedRequest;
@@ -38837,7 +39327,6 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
38837
39327
  let reportedCode;
38838
39328
  let failedProposals = 0;
38839
39329
  for (; ; ) {
38840
- await fence();
38841
39330
  const status = await manager.reconcile();
38842
39331
  if (status.state === "approved") {
38843
39332
  printLine2(terminal, `Connected ${host} to Claustrum.`);
@@ -38883,6 +39372,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
38883
39372
  if (remaining <= 0)
38884
39373
  break;
38885
39374
  await wait2(Math.min(pause, remaining));
39375
+ await fence();
38886
39376
  }
38887
39377
  if (printedRequest)
38888
39378
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -39037,7 +39527,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
39037
39527
 
39038
39528
  // src/common-auth-embedded/setup/config-write.js
39039
39529
  import { randomUUID as randomUUID18 } from "node:crypto";
39040
- import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat14, unlink as unlink12 } from "node:fs/promises";
39530
+ import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat16, unlink as unlink12 } from "node:fs/promises";
39041
39531
  import { basename as basename6, dirname as dirname21, join as join22 } from "node:path";
39042
39532
  import { setTimeout as delay2 } from "node:timers/promises";
39043
39533
  async function writeHostConfigAtomic(file, content, options = {}) {
@@ -39047,7 +39537,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
39047
39537
  let mode;
39048
39538
  if (!windows2) {
39049
39539
  try {
39050
- mode = (await stat14(file)).mode & 4095;
39540
+ mode = (await stat16(file)).mode & 4095;
39051
39541
  } catch (error) {
39052
39542
  if (error.code !== "ENOENT")
39053
39543
  throw error;
@@ -39679,7 +40169,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39679
40169
  }
39680
40170
  };
39681
40171
  let openCodeLogin;
39682
- let hasLocalPool = false;
40172
+ const nativeNextStep = (label) => {
40173
+ deps.stdout.write(
40174
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
40175
+ Setup has not completed the OpenCode 2 native Google connection.
40176
+ `
40177
+ );
40178
+ };
39683
40179
  const manifest = JSON.parse(
39684
40180
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
39685
40181
  );
@@ -39737,18 +40233,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39737
40233
  await assertLocal(host, context);
39738
40234
  if (host === "opencode" && context.opencodeGeneration === "2") {
39739
40235
  if (!forceLogin) {
39740
- try {
39741
- const source2 = await deps.accountStore.read(
39742
- deps.accountStore.legacyPath()
39743
- );
39744
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
39745
- if (candidateAccounts.some(
39746
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39747
- )) {
39748
- hasLocalPool = true;
39749
- }
39750
- } catch {
39751
- }
40236
+ const source2 = await deps.accountStore.read(
40237
+ deps.accountStore.legacyPath()
40238
+ );
40239
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
39752
40240
  }
39753
40241
  return;
39754
40242
  }
@@ -39763,11 +40251,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39763
40251
  `Using existing local Antigravity login for ${host}.
39764
40252
  `
39765
40253
  );
39766
- if (host === "opencode" && accounts.some(
39767
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39768
- )) {
39769
- hasLocalPool = true;
39770
- }
39771
40254
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
39772
40255
  const account = accounts[0];
39773
40256
  await writeNativeSlot(
@@ -39800,18 +40283,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39800
40283
  );
39801
40284
  if (host === "opencode") {
39802
40285
  openCodeLogin = result;
39803
- hasLocalPool = true;
39804
40286
  }
39805
40287
  },
39806
40288
  beforeRegister: async (host, mode, context) => {
39807
40289
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
39808
- const nativeNextStep = (label) => {
39809
- deps.stdout.write(
39810
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
39811
- Setup has not completed the OpenCode 2 native Google connection.
39812
- `
39813
- );
39814
- };
39815
40290
  if (mode === "local") {
39816
40291
  await assertLocal(host, context);
39817
40292
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -39825,10 +40300,6 @@ Setup has not completed the OpenCode 2 native Google connection.
39825
40300
  },
39826
40301
  context
39827
40302
  );
39828
- if (needsOpenCode2)
39829
- nativeNextStep(
39830
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
39831
- );
39832
40303
  return;
39833
40304
  }
39834
40305
  if (await authority(host) !== "vault")
@@ -39899,11 +40370,28 @@ Setup has not completed the OpenCode 2 native Google connection.
39899
40370
  await publishedGeneration(stateAnchor),
39900
40371
  stateAnchor
39901
40372
  );
39902
- return;
40373
+ } else {
40374
+ if (await migrateOpenCode() !== 0)
40375
+ throw new Error("Offline Antigravity account migration failed.");
40376
+ await deps.prepareVaultFolder?.();
40377
+ }
40378
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
40379
+ let reconnectReady = false;
40380
+ if (!forceLogin || context.opencodeGeneration !== "2") {
40381
+ if (source.kind === "store") {
40382
+ reconnectReady = source.reconnectReady;
40383
+ } else if (source.kind === "legacy") {
40384
+ const post = await deps.accountStore.read(
40385
+ deps.accountStore.legacyPath()
40386
+ );
40387
+ if (post.kind === "unavailable") throw new Error(post.reason);
40388
+ reconnectReady = post.kind === "store" && post.reconnectReady;
40389
+ }
40390
+ }
40391
+ nativeNextStep(
40392
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
40393
+ );
39903
40394
  }
39904
- if (await migrateOpenCode() !== 0)
39905
- throw new Error("Offline Antigravity account migration failed.");
39906
- await deps.prepareVaultFolder?.();
39907
40395
  } else {
39908
40396
  deps.stdout.write(
39909
40397
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -40495,6 +40983,7 @@ async function readAccountStore(legacyPath) {
40495
40983
  case "bound":
40496
40984
  break;
40497
40985
  }
40986
+ const generationId = admission.receipt.id;
40498
40987
  const repository = createAccountRepositoryFactory(modules)({
40499
40988
  paths: admission.paths,
40500
40989
  now: Date.now,
@@ -40508,6 +40997,12 @@ async function readAccountStore(legacyPath) {
40508
40997
  }
40509
40998
  });
40510
40999
  try {
41000
+ const servingBefore = await readAccountStoreAdmission(
41001
+ legacyPath,
41002
+ modules,
41003
+ Date.now,
41004
+ generationId
41005
+ );
40511
41006
  const read = await repository.read();
40512
41007
  if (read.status !== "ready") {
40513
41008
  return {
@@ -40515,7 +41010,20 @@ async function readAccountStore(legacyPath) {
40515
41010
  reason: `the account store is ${read.status}`
40516
41011
  };
40517
41012
  }
40518
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
41013
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
41014
+ legacyPath,
41015
+ modules,
41016
+ Date.now,
41017
+ generationId
41018
+ ) : servingBefore;
41019
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
41020
+ (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
41021
+ );
41022
+ return {
41023
+ kind: "store",
41024
+ accounts: read.rows.map(cliAccountOf),
41025
+ reconnectReady
41026
+ };
40519
41027
  } finally {
40520
41028
  await repository.dispose();
40521
41029
  }
@@ -40733,8 +41241,8 @@ function getLocalDevPath(directory) {
40733
41241
  }
40734
41242
  function findPackageJsonUp(startPath) {
40735
41243
  try {
40736
- const stat16 = fs4.statSync(startPath);
40737
- let dir = stat16.isDirectory() ? startPath : path4.dirname(startPath);
41244
+ const stat18 = fs4.statSync(startPath);
41245
+ let dir = stat18.isDirectory() ? startPath : path4.dirname(startPath);
40738
41246
  for (let i = 0; i < 10; i++) {
40739
41247
  const pkgPath = path4.join(dir, "package.json");
40740
41248
  if (fs4.existsSync(pkgPath)) {
@@ -41064,8 +41572,31 @@ function isSessionId(value) {
41064
41572
  // src/common-auth-embedded/rpc/port-file.js
41065
41573
  init_private_files2();
41066
41574
  import { createHash as createHash15, randomUUID as randomUUID19 } from "node:crypto";
41067
- 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";
41575
+ import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir4, rename as rename14, rmdir as rmdir3, stat as stat17, unlink as unlink13 } from "node:fs/promises";
41576
+ import { uptime as uptime2 } from "node:os";
41068
41577
  import { join as join29, resolve as resolve23 } from "node:path";
41578
+ function staleBefore(clock2) {
41579
+ return (clock2.now ?? Date.now)() - (clock2.uptime ?? uptime2)() * 1e3 - 3e5;
41580
+ }
41581
+ function isStalePortFile(entry, info, cutoff) {
41582
+ const time = entry.startedAt === void 0 ? info?.mtimeMs : entry.startedAt;
41583
+ return typeof time === "number" && Number.isFinite(time) && time < cutoff;
41584
+ }
41585
+ async function removeStalePortFile(path5, raw, info, beforeRemove2) {
41586
+ if (!info)
41587
+ return;
41588
+ await beforeRemove2?.(path5);
41589
+ try {
41590
+ const current = await readPrivateText2(path5);
41591
+ const identity3 = await stat17(path5);
41592
+ if (current === raw && identity3.dev === info.dev && identity3.ino === info.ino && identity3.mtimeMs === info.mtimeMs && identity3.size === info.size)
41593
+ await unlink13(path5).catch(() => {
41594
+ });
41595
+ } catch (error) {
41596
+ if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
41597
+ throw error;
41598
+ }
41599
+ }
41069
41600
  function isProbeablePid(pid) {
41070
41601
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
41071
41602
  }
@@ -41143,7 +41674,8 @@ async function writePortFile(dir, entry, options = {}) {
41143
41674
  throw error;
41144
41675
  }
41145
41676
  }
41146
- async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41677
+ async function sweepRpcState(root, activeDir, isManagedDir, log17, options = {}) {
41678
+ const cutoff = staleBefore(options);
41147
41679
  let projectDirs;
41148
41680
  try {
41149
41681
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -41170,6 +41702,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41170
41702
  if (!name.startsWith("port-") || !name.endsWith(".json"))
41171
41703
  continue;
41172
41704
  const portFile = join29(dir, name);
41705
+ const info = await stat17(portFile).catch(() => void 0);
41173
41706
  let raw;
41174
41707
  try {
41175
41708
  raw = await readPrivateText2(portFile);
@@ -41195,6 +41728,8 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
41195
41728
  if (!pidAlive2(entry.pid))
41196
41729
  await unlink13(portFile).catch(() => {
41197
41730
  });
41731
+ else if (isStalePortFile(entry, info, cutoff))
41732
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
41198
41733
  }
41199
41734
  if (resolve23(dir) !== active2)
41200
41735
  await rmdir3(dir).catch(() => {
@@ -41832,7 +42367,7 @@ function extractAccountAccessErrorDetails(bodyText) {
41832
42367
  };
41833
42368
  }
41834
42369
  function buildAccountAccessProbeRequest(projectId) {
41835
- const wireModel = "gemini-3.5-flash-low";
42370
+ const wireModel = "gemini-3.8-flash-low";
41836
42371
  const request = {
41837
42372
  contents: [{ role: "user", parts: [{ text: "ping" }] }],
41838
42373
  generationConfig: { maxOutputTokens: 1, temperature: 0 }
@@ -50734,8 +51269,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
50734
51269
  } else {
50735
51270
  const requestPayload = { ...parsedBody };
50736
51271
  if (isImageGenerationModel(effectiveModel) && isOpenCodeTitleGenerationRequest(requestPayload)) {
50737
- effectiveModel = "gemini-3.5-flash-low";
50738
- tierThinkingBudget = 4e3;
51272
+ effectiveModel = "gemini-3.8-flash-low";
51273
+ tierThinkingBudget = 1e3;
50739
51274
  tierThinkingLevel = void 0;
50740
51275
  }
50741
51276
  const rawGenerationConfig = requestPayload.generationConfig;
@@ -53789,16 +54324,18 @@ init_logger4();
53789
54324
  init_dist();
53790
54325
  import { createHash as createHash23 } from "node:crypto";
53791
54326
 
53792
- // src/common-auth-embedded/routing-accessor/index.js
53793
- function isObject2(value) {
53794
- return typeof value === "object" && value !== null;
53795
- }
54327
+ // src/common-auth-embedded/routing-accessor/handle.js
53796
54328
  function routingHandle(sessionId) {
53797
54329
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
53798
54330
  if (typeof routing !== "function")
53799
54331
  return void 0;
53800
54332
  const handle = routing(sessionId);
53801
- return isObject2(handle) ? handle : void 0;
54333
+ return typeof handle === "object" && handle !== null ? handle : void 0;
54334
+ }
54335
+
54336
+ // src/common-auth-embedded/routing-accessor/index.js
54337
+ function isObject2(value) {
54338
+ return typeof value === "object" && value !== null;
53802
54339
  }
53803
54340
  function selectionFor(answer, candidates) {
53804
54341
  if (!isObject2(answer))
@@ -53835,7 +54372,15 @@ async function askRouting(input2) {
53835
54372
  timer = setTimeout(() => resolve27(void 0), deadlineMs);
53836
54373
  timer.unref();
53837
54374
  });
53838
- const pending = accountFor.call(handle, { provider: input2.provider, modelId: input2.modelId }, { deadlineMs });
54375
+ const request = {
54376
+ provider: input2.provider,
54377
+ modelId: input2.modelId
54378
+ };
54379
+ const cap = input2.holdWaitMaxS;
54380
+ if (typeof cap === "number" && Number.isFinite(cap)) {
54381
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
54382
+ }
54383
+ const pending = accountFor.call(handle, request, { deadlineMs });
53839
54384
  if (!isObject2(pending) || typeof pending.then !== "function")
53840
54385
  return void 0;
53841
54386
  const answer = await Promise.race([pending, expired]);
@@ -53867,7 +54412,7 @@ function reportRouting(input2) {
53867
54412
  const { window, pool } = input2;
53868
54413
  if (window !== "5h" && window !== "7d")
53869
54414
  return;
53870
- if (pool !== void 0 && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
54415
+ if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
53871
54416
  return;
53872
54417
  payload = {
53873
54418
  ...identity3,
@@ -54619,7 +55164,7 @@ function prepareAgyWireRequest(wire, request) {
54619
55164
  request.options
54620
55165
  );
54621
55166
  }
54622
- var TITLE_FALLBACK_MODEL = "gemini-3.5-flash-low";
55167
+ var TITLE_FALLBACK_MODEL = "gemini-3.8-flash-low";
54623
55168
  function routeTitleModel(url) {
54624
55169
  const model = extractModelFromUrl(url);
54625
55170
  if (model === null) return url;