@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/server.js CHANGED
@@ -636,6 +636,9 @@ function loadBackend() {
636
636
  });
637
637
  return backend;
638
638
  }
639
+ function isWindowsSharingViolation(error) {
640
+ return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
641
+ }
639
642
  async function privateOperation(path5, stage, operation) {
640
643
  try {
641
644
  return await operation();
@@ -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((resolve28) => setTimeout(resolve28, 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((resolve28) => setTimeout(resolve28, 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();
@@ -29001,6 +29403,9 @@ function loadBackend2() {
29001
29403
  });
29002
29404
  return backend2;
29003
29405
  }
29406
+ function isWindowsSharingViolation2(error) {
29407
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
29408
+ }
29004
29409
  async function privateOperation2(path5, stage, operation) {
29005
29410
  try {
29006
29411
  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
  }
@@ -31375,7 +31780,7 @@ import {
31375
31780
  readFile as readFile12,
31376
31781
  rename as rename10,
31377
31782
  rmdir as rmdir2,
31378
- stat as stat10,
31783
+ stat as stat11,
31379
31784
  unlink as unlink10
31380
31785
  } from "node:fs/promises";
31381
31786
  import { basename as basename4, dirname as dirname15, join as join14, resolve as resolve15 } from "node:path";
@@ -32294,7 +32699,7 @@ async function physicalAliases(location, files) {
32294
32699
  async function samePhysical(a, b) {
32295
32700
  const id = async (path5) => {
32296
32701
  try {
32297
- const info = await stat10(path5, { bigint: true });
32702
+ const info = await stat11(path5, { bigint: true });
32298
32703
  return info.ino === 0n ? void 0 : `${info.dev}:${info.ino}`;
32299
32704
  } catch (error) {
32300
32705
  const code2 = error.code;
@@ -32339,7 +32744,8 @@ async function removeOldCopies(location, files, present6, layoutLock, input2) {
32339
32744
  if (!await unlinkIfIdentical(
32340
32745
  file,
32341
32746
  location.stateHomeDir,
32342
- () => beforeRemove(file.old, layoutLock, input2.steps)
32747
+ () => beforeRemove(file.old, layoutLock, input2.steps),
32748
+ input2.steps?.oldFileIO
32343
32749
  ))
32344
32750
  kept.push(file.old);
32345
32751
  }
@@ -32361,21 +32767,21 @@ async function sameBytes(a, b) {
32361
32767
  return false;
32362
32768
  }
32363
32769
  }
32364
- function isWindowsSharingError(error) {
32770
+ function isWindowsSharingError(error, platform) {
32365
32771
  const code2 = error?.code;
32366
- return process.platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32772
+ return platform === "win32" && (code2 === "EBUSY" || code2 === "EPERM" || code2 === "EACCES");
32367
32773
  }
32368
- async function unlinkIfIdentical(file, stateDir, guard) {
32774
+ async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink10 }) {
32369
32775
  const started = performance.now();
32370
32776
  for (const delay3 of SHARING_RETRY_DELAYS_MS) {
32371
32777
  if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
32372
32778
  let same;
32373
32779
  try {
32374
- same = (await readFile12(file.old)).equals(await readFile12(file.next));
32780
+ same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
32375
32781
  } catch (error) {
32376
32782
  if (error.code === "ENOENT" && !await exists2(file.old))
32377
32783
  return true;
32378
- if (isWindowsSharingError(error)) {
32784
+ if (isWindowsSharingError(error, io.platform)) {
32379
32785
  if (performance.now() - started >= SHARING_RETRY_BUDGET_MS) return false;
32380
32786
  continue;
32381
32787
  }
@@ -32384,11 +32790,11 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32384
32790
  if (!same) throw credentialConflict(stateDir, file);
32385
32791
  await guard();
32386
32792
  try {
32387
- await unlink10(file.old);
32793
+ await io.unlink(file.old);
32388
32794
  return true;
32389
32795
  } catch (error) {
32390
32796
  if (error.code === "ENOENT") return true;
32391
- if (!isWindowsSharingError(error) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32797
+ if (!isWindowsSharingError(error, io.platform) || performance.now() - started >= SHARING_RETRY_BUDGET_MS)
32392
32798
  return false;
32393
32799
  }
32394
32800
  }
@@ -32559,7 +32965,7 @@ function lockHolderText(name) {
32559
32965
  }
32560
32966
  async function exists2(path5) {
32561
32967
  try {
32562
- await stat10(path5);
32968
+ await stat11(path5);
32563
32969
  return true;
32564
32970
  } catch (error) {
32565
32971
  const code2 = error.code;
@@ -34157,9 +34563,6 @@ async function registerOpenCode2AuthMethods(ctx, options) {
34157
34563
  });
34158
34564
  }
34159
34565
 
34160
- // src/common-auth-embedded/opencode2/install.js
34161
- var MAX_RETRY_HOLD_MS = 20 * 60 * 1e3;
34162
-
34163
34566
  // src/plugin/ga-location-services.ts
34164
34567
  init_dist();
34165
34568
  init_vault_folder();
@@ -34606,7 +35009,7 @@ function extractAccountAccessErrorDetails(bodyText) {
34606
35009
  };
34607
35010
  }
34608
35011
  function buildAccountAccessProbeRequest(projectId) {
34609
- const wireModel = "gemini-3.5-flash-low";
35012
+ const wireModel = "gemini-3.8-flash-low";
34610
35013
  const request = {
34611
35014
  contents: [{ role: "user", parts: [{ text: "ping" }] }],
34612
35015
  generationConfig: { maxOutputTokens: 1, temperature: 0 }
@@ -43226,8 +43629,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
43226
43629
  } else {
43227
43630
  const requestPayload = { ...parsedBody };
43228
43631
  if (isImageGenerationModel(effectiveModel) && isOpenCodeTitleGenerationRequest(requestPayload)) {
43229
- effectiveModel = "gemini-3.5-flash-low";
43230
- tierThinkingBudget = 4e3;
43632
+ effectiveModel = "gemini-3.8-flash-low";
43633
+ tierThinkingBudget = 1e3;
43231
43634
  tierThinkingLevel = void 0;
43232
43635
  }
43233
43636
  const rawGenerationConfig = requestPayload.generationConfig;
@@ -44681,16 +45084,18 @@ async function retainResponseLifetime(response, cancellation) {
44681
45084
  init_dist();
44682
45085
  import { createHash as createHash17 } from "node:crypto";
44683
45086
 
44684
- // src/common-auth-embedded/routing-accessor/index.js
44685
- function isObject2(value) {
44686
- return typeof value === "object" && value !== null;
44687
- }
45087
+ // src/common-auth-embedded/routing-accessor/handle.js
44688
45088
  function routingHandle(sessionId) {
44689
45089
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
44690
45090
  if (typeof routing !== "function")
44691
45091
  return void 0;
44692
45092
  const handle = routing(sessionId);
44693
- return isObject2(handle) ? handle : void 0;
45093
+ return typeof handle === "object" && handle !== null ? handle : void 0;
45094
+ }
45095
+
45096
+ // src/common-auth-embedded/routing-accessor/index.js
45097
+ function isObject2(value) {
45098
+ return typeof value === "object" && value !== null;
44694
45099
  }
44695
45100
  function selectionFor(answer, candidates) {
44696
45101
  if (!isObject2(answer))
@@ -44727,7 +45132,15 @@ async function askRouting(input2) {
44727
45132
  timer = setTimeout(() => resolve28(void 0), deadlineMs);
44728
45133
  timer.unref();
44729
45134
  });
44730
- const pending = accountFor.call(handle, { provider: input2.provider, modelId: input2.modelId }, { deadlineMs });
45135
+ const request = {
45136
+ provider: input2.provider,
45137
+ modelId: input2.modelId
45138
+ };
45139
+ const cap = input2.holdWaitMaxS;
45140
+ if (typeof cap === "number" && Number.isFinite(cap)) {
45141
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
45142
+ }
45143
+ const pending = accountFor.call(handle, request, { deadlineMs });
44731
45144
  if (!isObject2(pending) || typeof pending.then !== "function")
44732
45145
  return void 0;
44733
45146
  const answer = await Promise.race([pending, expired]);
@@ -44759,7 +45172,7 @@ function reportRouting(input2) {
44759
45172
  const { window, pool } = input2;
44760
45173
  if (window !== "5h" && window !== "7d")
44761
45174
  return;
44762
- if (pool !== void 0 && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
45175
+ if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
44763
45176
  return;
44764
45177
  payload = {
44765
45178
  ...identity3,
@@ -45518,7 +45931,7 @@ function prepareAgyWireRequest(wire, request) {
45518
45931
  request.options
45519
45932
  );
45520
45933
  }
45521
- var TITLE_FALLBACK_MODEL = "gemini-3.5-flash-low";
45934
+ var TITLE_FALLBACK_MODEL = "gemini-3.8-flash-low";
45522
45935
  function routeTitleModel(url) {
45523
45936
  const model = extractModelFromUrl(url);
45524
45937
  if (model === null) return url;
@@ -53217,16 +53630,16 @@ async function select2(terminal, items, options) {
53217
53630
  // src/common-auth-embedded/claustrum/enrollment.js
53218
53631
  import { createHash as createHash19, randomBytes as randomBytes6, randomUUID as randomUUID19 } from "node:crypto";
53219
53632
  import { constants as fsConstants2 } from "node:fs";
53220
- 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";
53633
+ 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";
53221
53634
  import { basename as basename6, dirname as dirname22, extname as extname2, isAbsolute as isAbsolute4, join as join26, resolve as resolve22 } from "node:path";
53222
- import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
53635
+ import { ClaustrumCredentialError as ClaustrumCredentialError6, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
53223
53636
 
53224
53637
  // src/common-auth-embedded/fs/file-read-cache.js
53225
- import { lstat as lstat7 } from "node:fs/promises";
53638
+ import { lstat as lstat7, stat as stat12 } from "node:fs/promises";
53226
53639
  import { resolve as resolve21 } from "node:path";
53227
- async function identity2(path5) {
53640
+ async function identity2(path5, followSymlinks) {
53228
53641
  try {
53229
- const metadata = await lstat7(path5);
53642
+ const metadata = await (followSymlinks ? stat12(path5) : lstat7(path5));
53230
53643
  return metadata.isFile() ? metadata : void 0;
53231
53644
  } catch (error) {
53232
53645
  return error.code === "ENOENT" ? "absent" : void 0;
@@ -53238,11 +53651,15 @@ function sameIdentity2(left, right) {
53238
53651
  return left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
53239
53652
  }
53240
53653
  var FileReadCache2 = class {
53654
+ #followSymlinks;
53241
53655
  #entries = /* @__PURE__ */ new Map();
53656
+ constructor(options = {}) {
53657
+ this.#followSymlinks = options.followSymlinks ?? false;
53658
+ }
53242
53659
  async read(paths, read, validateHit) {
53243
53660
  const resolvedPaths = paths.map((path5) => resolve21(path5));
53244
53661
  const key = JSON.stringify(resolvedPaths);
53245
- const probed = await Promise.all(resolvedPaths.map(identity2));
53662
+ const probed = await Promise.all(resolvedPaths.map((path5) => identity2(path5, this.#followSymlinks)));
53246
53663
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
53247
53664
  const cached = this.#entries.get(key);
53248
53665
  if (identities && cached && identities.every((entry, index) => {
@@ -53291,7 +53708,7 @@ init_private_files2();
53291
53708
  // src/common-auth-embedded/fs/refresh-file-lock.js
53292
53709
  init_private_files2();
53293
53710
  import { randomUUID as randomUUID18 } from "node:crypto";
53294
- 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";
53711
+ 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";
53295
53712
  import { dirname as dirname21, join as join25 } from "node:path";
53296
53713
 
53297
53714
  // src/common-auth-embedded/fs/with-lock.js
@@ -53545,7 +53962,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53545
53962
  };
53546
53963
  }
53547
53964
  try {
53548
- const current = await stat11(lockPath);
53965
+ const current = await stat13(lockPath);
53549
53966
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
53550
53967
  if (legacyExpiry > now())
53551
53968
  return { status: "live" };
@@ -53594,37 +54011,83 @@ async function acquireRefreshFileLockWithClock2(options) {
53594
54011
  await rm6(path5, { recursive: true, force: true }).catch(() => {
53595
54012
  });
53596
54013
  }
53597
- async function releaseEvictionMarker() {
53598
- if (await ownsEvictionMarker()) {
53599
- await removeLeaseObject(evictPath);
53600
- }
54014
+ function isRetryableRemoval(error, path5) {
54015
+ if (!windowsPrivateFiles2 || !(error instanceof PrivateFileError2) || error.stage !== "remove" || error.path !== path5)
54016
+ return false;
54017
+ return isWindowsSharingViolation2(error) || error.win32Code === void 0 && error.reason === void 0 && (error.code === "EBUSY" || error.code === "EPERM");
54018
+ }
54019
+ async function removeOwnedLeaseObject(path5, stillOwned, deadline = performance.now() + EVICT_TTL + 1e3) {
54020
+ let original;
54021
+ let delayMs = 5;
54022
+ while (await stillOwned()) {
54023
+ try {
54024
+ await removeLeaseObject(path5);
54025
+ return;
54026
+ } catch (error) {
54027
+ if (!isRetryableRemoval(error, path5))
54028
+ throw error;
54029
+ original ??= error;
54030
+ }
54031
+ const remainingMs = deadline - performance.now();
54032
+ if (remainingMs <= 0)
54033
+ throw original;
54034
+ await new Promise((resolve28) => setTimeout(resolve28, Math.min(delayMs, remainingMs)));
54035
+ if (performance.now() >= deadline)
54036
+ throw original;
54037
+ delayMs = Math.min(delayMs * 2, 50);
54038
+ }
54039
+ }
54040
+ async function releaseEvictionMarker(deadline) {
54041
+ let ownedDirectory;
54042
+ await removeOwnedLeaseObject(evictPath, async () => {
54043
+ if (!windowsPrivateFiles2)
54044
+ return ownsEvictionMarker();
54045
+ const current = await lstat8(evictPath).catch((error) => {
54046
+ if (error.code !== "ENOENT")
54047
+ throw error;
54048
+ return void 0;
54049
+ });
54050
+ if (!current || ownedDirectory && !sameMarkerDirectory2(ownedDirectory, current))
54051
+ return false;
54052
+ if (await ownsEvictionMarker()) {
54053
+ ownedDirectory = current;
54054
+ return true;
54055
+ }
54056
+ if (!ownedDirectory)
54057
+ return false;
54058
+ try {
54059
+ await stat13(evictOwnerPath);
54060
+ return false;
54061
+ } catch (error) {
54062
+ if (error.code !== "ENOENT")
54063
+ throw error;
54064
+ return true;
54065
+ }
54066
+ }, deadline);
53601
54067
  }
53602
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
54068
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
53603
54069
  if (!created)
53604
54070
  return false;
53605
- let current;
53606
- try {
53607
- const st = await lstat8(evictPath);
53608
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
53609
- } catch {
53610
- return false;
53611
- }
53612
- if (!sameMarkerDirectory2(created, current))
53613
- return false;
54071
+ let stillOurs = false;
53614
54072
  try {
53615
- await stat11(evictOwnerPath);
53616
- return true;
53617
- } catch (error) {
53618
- if (error.code !== "ENOENT")
53619
- return true;
53620
- }
53621
- try {
53622
- await removeLeaseObject(evictPath);
54073
+ await removeOwnedLeaseObject(evictPath, async () => {
54074
+ stillOurs = false;
54075
+ const st = await lstat8(evictPath).catch(() => void 0);
54076
+ if (!st || !sameMarkerDirectory2(created, st))
54077
+ return false;
54078
+ stillOurs = true;
54079
+ try {
54080
+ await stat13(evictOwnerPath);
54081
+ return false;
54082
+ } catch (error) {
54083
+ return error.code === "ENOENT";
54084
+ }
54085
+ }, deadline);
53623
54086
  } catch {
53624
54087
  }
53625
- return true;
54088
+ return stillOurs;
53626
54089
  }
53627
- async function tryAcquireEvictionMarker() {
54090
+ async function tryAcquireEvictionMarker(deadline) {
53628
54091
  if (windowsPrivateFiles2)
53629
54092
  await createPrivateDirectoryExclusive2(evictPath);
53630
54093
  else
@@ -53648,11 +54111,11 @@ async function acquireRefreshFileLockWithClock2(options) {
53648
54111
  else
53649
54112
  await createExclusiveText2(evictOwnerPath, bytes);
53650
54113
  } catch (error) {
53651
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
54114
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
53652
54115
  if (isLostMarkerRaceError2(error) && !stillOurs)
53653
54116
  return false;
53654
54117
  try {
53655
- await releaseEvictionMarker();
54118
+ await releaseEvictionMarker(deadline);
53656
54119
  } catch {
53657
54120
  }
53658
54121
  throw error;
@@ -53661,10 +54124,10 @@ async function acquireRefreshFileLockWithClock2(options) {
53661
54124
  await options.onStep("eviction-marker-acquired");
53662
54125
  return true;
53663
54126
  }
53664
- async function recoverStaleEvictionMarker() {
54127
+ async function recoverStaleEvictionMarker(deadline) {
53665
54128
  let evictStat;
53666
54129
  try {
53667
- evictStat = await stat11(evictPath);
54130
+ evictStat = await stat13(evictPath);
53668
54131
  } catch (error) {
53669
54132
  if (error.code === "ENOENT")
53670
54133
  return "missing";
@@ -53682,7 +54145,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53682
54145
  if (evictStat.mtimeMs + EVICT_TTL > now()) {
53683
54146
  let hasOwner = true;
53684
54147
  try {
53685
- await stat11(evictOwnerPath);
54148
+ await stat13(evictOwnerPath);
53686
54149
  } catch (error) {
53687
54150
  if (error.code === "ENOENT")
53688
54151
  hasOwner = false;
@@ -53706,12 +54169,22 @@ async function acquireRefreshFileLockWithClock2(options) {
53706
54169
  }
53707
54170
  if (options.onStep)
53708
54171
  await options.onStep("stale-marker-claimed");
53709
- await removeLeaseObject(claimedPath);
54172
+ const claimedIdentity = windowsPrivateFiles2 ? await lstat8(claimedPath) : void 0;
54173
+ await removeOwnedLeaseObject(claimedPath, async () => {
54174
+ if (!claimedIdentity)
54175
+ return true;
54176
+ const current = await lstat8(claimedPath).catch((error) => {
54177
+ if (error.code !== "ENOENT")
54178
+ throw error;
54179
+ return void 0;
54180
+ });
54181
+ return !!current && sameMarkerDirectory2(claimedIdentity, current);
54182
+ }, deadline);
53710
54183
  return "recovered";
53711
54184
  }
53712
- async function withEvictionMarker(action) {
54185
+ async function withEvictionMarker(action, deadline) {
53713
54186
  try {
53714
- if (!await tryAcquireEvictionMarker())
54187
+ if (!await tryAcquireEvictionMarker(deadline))
53715
54188
  return false;
53716
54189
  } catch (error) {
53717
54190
  if (error.code === "EEXIST") {
@@ -53728,11 +54201,23 @@ async function acquireRefreshFileLockWithClock2(options) {
53728
54201
  }
53729
54202
  throw error;
53730
54203
  }
54204
+ let actionFailed = false;
54205
+ let actionError;
53731
54206
  try {
53732
54207
  await action();
53733
- } finally {
53734
- await releaseEvictionMarker();
54208
+ } catch (error) {
54209
+ actionFailed = true;
54210
+ actionError = error;
54211
+ }
54212
+ try {
54213
+ await releaseEvictionMarker(deadline);
54214
+ } catch (error) {
54215
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
54216
+ throw actionError;
54217
+ throw error;
53735
54218
  }
54219
+ if (actionFailed)
54220
+ throw actionError;
53736
54221
  return true;
53737
54222
  }
53738
54223
  async function relinquishLockAfterMarkerLoss() {
@@ -53969,6 +54454,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53969
54454
  await renewalInFlight;
53970
54455
  const deadline = performance.now() + EVICT_TTL + 1e3;
53971
54456
  let delayMs = 5;
54457
+ let removalError;
53972
54458
  for (; ; ) {
53973
54459
  try {
53974
54460
  let removalConfirmed = false;
@@ -53993,7 +54479,7 @@ async function acquireRefreshFileLockWithClock2(options) {
53993
54479
  return;
53994
54480
  await removeLeaseObject(lockPath);
53995
54481
  removalConfirmed = true;
53996
- });
54482
+ }, deadline);
53997
54483
  if (markerAcquired) {
53998
54484
  if (windowsPrivateFiles2 && !removalConfirmed)
53999
54485
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -54004,20 +54490,25 @@ async function acquireRefreshFileLockWithClock2(options) {
54004
54490
  }
54005
54491
  if (signal?.aborted)
54006
54492
  return;
54007
- await recoverStaleEvictionMarker();
54493
+ await recoverStaleEvictionMarker(deadline);
54008
54494
  } catch (error) {
54009
- if (windowsPrivateFiles2)
54010
- throw error;
54011
- return;
54495
+ if (!isRetryableRemoval(error, lockPath)) {
54496
+ if (windowsPrivateFiles2)
54497
+ throw error;
54498
+ return;
54499
+ }
54500
+ removalError ??= error;
54012
54501
  }
54013
54502
  const remainingMs = deadline - performance.now();
54014
54503
  if (remainingMs <= 0)
54015
54504
  break;
54016
54505
  await new Promise((resolve28) => setTimeout(resolve28, Math.min(delayMs, remainingMs)));
54506
+ if (windowsPrivateFiles2 && performance.now() >= deadline)
54507
+ break;
54017
54508
  delayMs = Math.min(delayMs * 2, 50);
54018
54509
  }
54019
54510
  if (windowsPrivateFiles2)
54020
- throw new PrivateFileError2(lockPath, "release-not-confirmed", {
54511
+ throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
54021
54512
  code: "ETIMEDOUT"
54022
54513
  });
54023
54514
  }
@@ -54060,7 +54551,7 @@ var RETRYABLE_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
54060
54551
  "pending_queue_full"
54061
54552
  ]);
54062
54553
  function classifyEnrollmentError2(error) {
54063
- if (!(error instanceof ClaustrumCredentialError5))
54554
+ if (!(error instanceof ClaustrumCredentialError6))
54064
54555
  return void 0;
54065
54556
  if (TERMINAL_ENROLLMENT_CODES2.has(error.code))
54066
54557
  return { code: error.code, disposition: "terminal" };
@@ -54271,7 +54762,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
54271
54762
  }
54272
54763
  let privateGroup;
54273
54764
  for (; ; ) {
54274
- const metadata = await stat12(component).catch(() => void 0);
54765
+ const metadata = await stat14(component).catch(() => void 0);
54275
54766
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
54276
54767
  if (privateGroup === void 0) {
54277
54768
  privateGroup = gid !== void 0 && await isPrivateGroup2(uid, gid, options);
@@ -54300,7 +54791,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
54300
54791
  return;
54301
54792
  }
54302
54793
  await mkdir15(directory, { recursive: true, mode: 448 });
54303
- const metadata = await stat12(directory);
54794
+ const metadata = await stat14(directory);
54304
54795
  const uid = process.geteuid?.();
54305
54796
  if (uid !== void 0 && metadata.uid !== uid) {
54306
54797
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -54889,7 +55380,7 @@ function setupPaths(io = {}) {
54889
55380
  }
54890
55381
 
54891
55382
  // src/common-auth-embedded/setup/detect.js
54892
- function stat13(path5, kind) {
55383
+ function stat15(path5, kind) {
54893
55384
  try {
54894
55385
  return statSync5(path5)[kind]();
54895
55386
  } catch {
@@ -54898,12 +55389,12 @@ function stat13(path5, kind) {
54898
55389
  }
54899
55390
  var defaultSetupFileSystem = {
54900
55391
  exists: existsSync12,
54901
- isFile: (path5) => stat13(path5, "isFile"),
54902
- isDirectory: (path5) => stat13(path5, "isDirectory"),
55392
+ isFile: (path5) => stat15(path5, "isFile"),
55393
+ isDirectory: (path5) => stat15(path5, "isDirectory"),
54903
55394
  isExecutable(path5) {
54904
55395
  try {
54905
55396
  accessSync(path5, constants3.X_OK);
54906
- return stat13(path5, "isFile");
55397
+ return stat15(path5, "isFile");
54907
55398
  } catch {
54908
55399
  return false;
54909
55400
  }
@@ -55402,6 +55893,12 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
55402
55893
  await writeEnrollmentTokenFile3(path5, file);
55403
55894
  }
55404
55895
  });
55896
+ await fence();
55897
+ const initial = await manager.status();
55898
+ if (initial.state === "approved") {
55899
+ printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
55900
+ return;
55901
+ }
55405
55902
  printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
55406
55903
  const deadline = now() + ENROLLMENT_WAIT_MS;
55407
55904
  let printedRequest;
@@ -55409,7 +55906,6 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
55409
55906
  let reportedCode;
55410
55907
  let failedProposals = 0;
55411
55908
  for (; ; ) {
55412
- await fence();
55413
55909
  const status = await manager.reconcile();
55414
55910
  if (status.state === "approved") {
55415
55911
  printLine2(terminal, `Connected ${host} to Claustrum.`);
@@ -55455,6 +55951,7 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
55455
55951
  if (remaining <= 0)
55456
55952
  break;
55457
55953
  await wait2(Math.min(pause, remaining));
55954
+ await fence();
55458
55955
  }
55459
55956
  if (printedRequest)
55460
55957
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -55609,7 +56106,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
55609
56106
 
55610
56107
  // src/common-auth-embedded/setup/config-write.js
55611
56108
  import { randomUUID as randomUUID20 } from "node:crypto";
55612
- import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat14, unlink as unlink12 } from "node:fs/promises";
56109
+ import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat16, unlink as unlink12 } from "node:fs/promises";
55613
56110
  import { basename as basename7, dirname as dirname23, join as join28 } from "node:path";
55614
56111
  import { setTimeout as delay2 } from "node:timers/promises";
55615
56112
  async function writeHostConfigAtomic(file, content, options = {}) {
@@ -55619,7 +56116,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
55619
56116
  let mode;
55620
56117
  if (!windows2) {
55621
56118
  try {
55622
- mode = (await stat14(file)).mode & 4095;
56119
+ mode = (await stat16(file)).mode & 4095;
55623
56120
  } catch (error) {
55624
56121
  if (error.code !== "ENOENT")
55625
56122
  throw error;
@@ -56251,7 +56748,13 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56251
56748
  }
56252
56749
  };
56253
56750
  let openCodeLogin;
56254
- let hasLocalPool = false;
56751
+ const nativeNextStep = (label) => {
56752
+ deps.stdout.write(
56753
+ `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
56754
+ Setup has not completed the OpenCode 2 native Google connection.
56755
+ `
56756
+ );
56757
+ };
56255
56758
  const manifest = JSON.parse(
56256
56759
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
56257
56760
  );
@@ -56309,18 +56812,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56309
56812
  await assertLocal(host, context);
56310
56813
  if (host === "opencode" && context.opencodeGeneration === "2") {
56311
56814
  if (!forceLogin) {
56312
- try {
56313
- const source2 = await deps.accountStore.read(
56314
- deps.accountStore.legacyPath()
56315
- );
56316
- const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
56317
- if (candidateAccounts.some(
56318
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
56319
- )) {
56320
- hasLocalPool = true;
56321
- }
56322
- } catch {
56323
- }
56815
+ const source2 = await deps.accountStore.read(
56816
+ deps.accountStore.legacyPath()
56817
+ );
56818
+ if (source2.kind === "unavailable") throw new Error(source2.reason);
56324
56819
  }
56325
56820
  return;
56326
56821
  }
@@ -56335,11 +56830,6 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56335
56830
  `Using existing local Antigravity login for ${host}.
56336
56831
  `
56337
56832
  );
56338
- if (host === "opencode" && accounts.some(
56339
- (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
56340
- )) {
56341
- hasLocalPool = true;
56342
- }
56343
56833
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
56344
56834
  const account = accounts[0];
56345
56835
  await writeNativeSlot(
@@ -56372,18 +56862,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
56372
56862
  );
56373
56863
  if (host === "opencode") {
56374
56864
  openCodeLogin = result;
56375
- hasLocalPool = true;
56376
56865
  }
56377
56866
  },
56378
56867
  beforeRegister: async (host, mode, context) => {
56379
56868
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
56380
- const nativeNextStep = (label) => {
56381
- deps.stdout.write(
56382
- `In OpenCode 2, run opencode auth login, select Google, then choose ${label}.
56383
- Setup has not completed the OpenCode 2 native Google connection.
56384
- `
56385
- );
56386
- };
56387
56869
  if (mode === "local") {
56388
56870
  await assertLocal(host, context);
56389
56871
  if (host === "opencode" && context.opencodeGeneration !== "2" && openCodeLogin)
@@ -56397,10 +56879,6 @@ Setup has not completed the OpenCode 2 native Google connection.
56397
56879
  },
56398
56880
  context
56399
56881
  );
56400
- if (needsOpenCode2)
56401
- nativeNextStep(
56402
- hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
56403
- );
56404
56882
  return;
56405
56883
  }
56406
56884
  if (await authority(host) !== "vault")
@@ -56471,11 +56949,28 @@ Setup has not completed the OpenCode 2 native Google connection.
56471
56949
  await publishedGeneration(stateAnchor),
56472
56950
  stateAnchor
56473
56951
  );
56474
- return;
56952
+ } else {
56953
+ if (await migrateOpenCode() !== 0)
56954
+ throw new Error("Offline Antigravity account migration failed.");
56955
+ await deps.prepareVaultFolder?.();
56956
+ }
56957
+ if (context.mode === "local" && context.opencodeGeneration !== "1") {
56958
+ let reconnectReady = false;
56959
+ if (!forceLogin || context.opencodeGeneration !== "2") {
56960
+ if (source.kind === "store") {
56961
+ reconnectReady = source.reconnectReady;
56962
+ } else if (source.kind === "legacy") {
56963
+ const post = await deps.accountStore.read(
56964
+ deps.accountStore.legacyPath()
56965
+ );
56966
+ if (post.kind === "unavailable") throw new Error(post.reason);
56967
+ reconnectReady = post.kind === "store" && post.reconnectReady;
56968
+ }
56969
+ }
56970
+ nativeNextStep(
56971
+ reconnectReady ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
56972
+ );
56475
56973
  }
56476
- if (await migrateOpenCode() !== 0)
56477
- throw new Error("Offline Antigravity account migration failed.");
56478
- await deps.prepareVaultFolder?.();
56479
56974
  } else {
56480
56975
  deps.stdout.write(
56481
56976
  "Pi uses its native auth.json; no Antigravity account-pool migration is needed.\n"
@@ -57067,6 +57562,7 @@ async function readAccountStore(legacyPath) {
57067
57562
  case "bound":
57068
57563
  break;
57069
57564
  }
57565
+ const generationId = admission.receipt.id;
57070
57566
  const repository = createAccountRepositoryFactory(modules)({
57071
57567
  paths: admission.paths,
57072
57568
  now: Date.now,
@@ -57080,6 +57576,12 @@ async function readAccountStore(legacyPath) {
57080
57576
  }
57081
57577
  });
57082
57578
  try {
57579
+ const servingBefore = await readAccountStoreAdmission(
57580
+ legacyPath,
57581
+ modules,
57582
+ Date.now,
57583
+ generationId
57584
+ );
57083
57585
  const read = await repository.read();
57084
57586
  if (read.status !== "ready") {
57085
57587
  return {
@@ -57087,7 +57589,20 @@ async function readAccountStore(legacyPath) {
57087
57589
  reason: `the account store is ${read.status}`
57088
57590
  };
57089
57591
  }
57090
- return { kind: "store", accounts: read.rows.map(cliAccountOf) };
57592
+ const servingAfter = servingBefore.status === "active" ? await readAccountStoreAdmission(
57593
+ legacyPath,
57594
+ modules,
57595
+ Date.now,
57596
+ generationId
57597
+ ) : servingBefore;
57598
+ const reconnectReady = servingBefore.status === "active" && servingAfter.status === "active" && read.rows.some(
57599
+ (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
57600
+ );
57601
+ return {
57602
+ kind: "store",
57603
+ accounts: read.rows.map(cliAccountOf),
57604
+ reconnectReady
57605
+ };
57091
57606
  } finally {
57092
57607
  await repository.dispose();
57093
57608
  }
@@ -57305,8 +57820,8 @@ function getLocalDevPath(directory) {
57305
57820
  }
57306
57821
  function findPackageJsonUp(startPath) {
57307
57822
  try {
57308
- const stat16 = fs4.statSync(startPath);
57309
- let dir = stat16.isDirectory() ? startPath : path4.dirname(startPath);
57823
+ const stat18 = fs4.statSync(startPath);
57824
+ let dir = stat18.isDirectory() ? startPath : path4.dirname(startPath);
57310
57825
  for (let i = 0; i < 10; i++) {
57311
57826
  const pkgPath = path4.join(dir, "package.json");
57312
57827
  if (fs4.existsSync(pkgPath)) {
@@ -57636,8 +58151,31 @@ function isSessionId(value) {
57636
58151
  // src/common-auth-embedded/rpc/port-file.js
57637
58152
  init_private_files2();
57638
58153
  import { createHash as createHash21, randomUUID as randomUUID21 } from "node:crypto";
57639
- 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";
58154
+ 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";
58155
+ import { uptime as uptime2 } from "node:os";
57640
58156
  import { join as join35, resolve as resolve26 } from "node:path";
58157
+ function staleBefore(clock2) {
58158
+ return (clock2.now ?? Date.now)() - (clock2.uptime ?? uptime2)() * 1e3 - 3e5;
58159
+ }
58160
+ function isStalePortFile(entry, info, cutoff) {
58161
+ const time = entry.startedAt === void 0 ? info?.mtimeMs : entry.startedAt;
58162
+ return typeof time === "number" && Number.isFinite(time) && time < cutoff;
58163
+ }
58164
+ async function removeStalePortFile(path5, raw, info, beforeRemove2) {
58165
+ if (!info)
58166
+ return;
58167
+ await beforeRemove2?.(path5);
58168
+ try {
58169
+ const current = await readPrivateText2(path5);
58170
+ const identity3 = await stat17(path5);
58171
+ if (current === raw && identity3.dev === info.dev && identity3.ino === info.ino && identity3.mtimeMs === info.mtimeMs && identity3.size === info.size)
58172
+ await unlink13(path5).catch(() => {
58173
+ });
58174
+ } catch (error) {
58175
+ if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
58176
+ throw error;
58177
+ }
58178
+ }
57641
58179
  function isProbeablePid(pid) {
57642
58180
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
57643
58181
  }
@@ -57715,7 +58253,8 @@ async function writePortFile(dir, entry, options = {}) {
57715
58253
  throw error;
57716
58254
  }
57717
58255
  }
57718
- async function sweepRpcState(root, activeDir, isManagedDir, log17) {
58256
+ async function sweepRpcState(root, activeDir, isManagedDir, log17, options = {}) {
58257
+ const cutoff = staleBefore(options);
57719
58258
  let projectDirs;
57720
58259
  try {
57721
58260
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -57742,6 +58281,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
57742
58281
  if (!name.startsWith("port-") || !name.endsWith(".json"))
57743
58282
  continue;
57744
58283
  const portFile = join35(dir, name);
58284
+ const info = await stat17(portFile).catch(() => void 0);
57745
58285
  let raw;
57746
58286
  try {
57747
58287
  raw = await readPrivateText2(portFile);
@@ -57767,6 +58307,8 @@ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
57767
58307
  if (!pidAlive2(entry.pid))
57768
58308
  await unlink13(portFile).catch(() => {
57769
58309
  });
58310
+ else if (isStalePortFile(entry, info, cutoff))
58311
+ await removeStalePortFile(portFile, raw, info, options.beforeRemove);
57770
58312
  }
57771
58313
  if (resolve26(dir) !== active2)
57772
58314
  await rmdir3(dir).catch(() => {