@cortexkit/opencode-antigravity-auth 3.1.9 → 3.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +4 -0
  2. package/dist/cli.js +502 -160
  3. package/dist/cli.js.map +3 -3
  4. package/dist/cli.meta.json +52 -42
  5. package/dist/index.js +1306 -656
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +102 -74
  8. package/dist/server.js +1437 -767
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/cli.d.ts +3 -1
  12. package/dist/src/cli.d.ts.map +1 -1
  13. package/dist/src/cli.js +19 -6
  14. package/dist/src/cli.js.map +1 -1
  15. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  16. package/dist/src/common-auth-embedded/claustrum/consumer.js +32 -0
  17. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +54 -5
  18. package/dist/src/common-auth-embedded/claustrum/custody.js +176 -22
  19. package/dist/src/common-auth-embedded/claustrum/host.js +8 -0
  20. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  21. package/dist/src/common-auth-embedded/claustrum/hub.js +10 -0
  22. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  23. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +6 -1
  24. package/dist/src/common-auth-embedded/routing-accessor/index.js +5 -3
  25. package/dist/src/common-auth-embedded/setup/process-fence.js +20 -3
  26. package/dist/src/common-auth-embedded/source-output.json +41 -41
  27. package/dist/src/ga/rpc/protocol.d.ts +11 -5
  28. package/dist/src/ga/rpc/protocol.d.ts.map +1 -1
  29. package/dist/src/ga/rpc/protocol.js +11 -3
  30. package/dist/src/ga/rpc/protocol.js.map +1 -1
  31. package/dist/src/ga/server/index.d.ts.map +1 -1
  32. package/dist/src/ga/server/index.js +30 -14
  33. package/dist/src/ga/server/index.js.map +1 -1
  34. package/dist/src/ga/tui/host-ga.d.ts +2 -1
  35. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  36. package/dist/src/ga/tui/host-ga.js +9 -4
  37. package/dist/src/ga/tui/host-ga.js.map +1 -1
  38. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  39. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  40. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  41. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  42. package/dist/src/plugin/account-access.d.ts +1 -0
  43. package/dist/src/plugin/account-access.d.ts.map +1 -1
  44. package/dist/src/plugin/account-access.js +28 -0
  45. package/dist/src/plugin/account-access.js.map +1 -1
  46. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  47. package/dist/src/plugin/auth-loader.js +21 -12
  48. package/dist/src/plugin/auth-loader.js.map +1 -1
  49. package/dist/src/plugin/background-quota-refresh.d.ts +11 -24
  50. package/dist/src/plugin/background-quota-refresh.d.ts.map +1 -1
  51. package/dist/src/plugin/background-quota-refresh.js +54 -60
  52. package/dist/src/plugin/background-quota-refresh.js.map +1 -1
  53. package/dist/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  54. package/dist/src/plugin/background-vault-quota-refresh.js +6 -3
  55. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  56. package/dist/src/plugin/cache/signature-cache.d.ts +3 -0
  57. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -1
  58. package/dist/src/plugin/cache/signature-cache.js +73 -46
  59. package/dist/src/plugin/cache/signature-cache.js.map +1 -1
  60. package/dist/src/plugin/cache.d.ts.map +1 -1
  61. package/dist/src/plugin/cache.js +17 -7
  62. package/dist/src/plugin/cache.js.map +1 -1
  63. package/dist/src/plugin/config/models.d.ts +1 -1
  64. package/dist/src/plugin/config/models.d.ts.map +1 -1
  65. package/dist/src/plugin/config/models.js +10 -5
  66. package/dist/src/plugin/config/models.js.map +1 -1
  67. package/dist/src/plugin/core/streaming/displayed-thinking.d.ts +23 -0
  68. package/dist/src/plugin/core/streaming/displayed-thinking.d.ts.map +1 -0
  69. package/dist/src/plugin/core/streaming/displayed-thinking.js +58 -0
  70. package/dist/src/plugin/core/streaming/displayed-thinking.js.map +1 -0
  71. package/dist/src/plugin/fetch/warmup.d.ts +9 -2
  72. package/dist/src/plugin/fetch/warmup.d.ts.map +1 -1
  73. package/dist/src/plugin/fetch/warmup.js +22 -14
  74. package/dist/src/plugin/fetch/warmup.js.map +1 -1
  75. package/dist/src/plugin/quota.d.ts +10 -2
  76. package/dist/src/plugin/quota.d.ts.map +1 -1
  77. package/dist/src/plugin/quota.js +38 -10
  78. package/dist/src/plugin/quota.js.map +1 -1
  79. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  80. package/dist/src/plugin/request-helpers.js +51 -19
  81. package/dist/src/plugin/request-helpers.js.map +1 -1
  82. package/dist/src/plugin/request.d.ts +12 -1
  83. package/dist/src/plugin/request.d.ts.map +1 -1
  84. package/dist/src/plugin/request.js +34 -49
  85. package/dist/src/plugin/request.js.map +1 -1
  86. package/dist/src/plugin/shared/request-services.d.ts +4 -1
  87. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  88. package/dist/src/plugin/shared/request-services.js +142 -24
  89. package/dist/src/plugin/shared/request-services.js.map +1 -1
  90. package/dist/src/plugin/shared/runtime.d.ts +3 -4
  91. package/dist/src/plugin/shared/runtime.d.ts.map +1 -1
  92. package/dist/src/plugin/shared/runtime.js +2 -2
  93. package/dist/src/plugin/shared/runtime.js.map +1 -1
  94. package/dist/src/plugin/shared/vault-request-credentials.d.ts +13 -7
  95. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  96. package/dist/src/plugin/shared/vault-request-credentials.js +24 -18
  97. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  98. package/dist/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  99. package/dist/src/setup.d.ts +3 -0
  100. package/dist/src/setup.d.ts.map +1 -1
  101. package/dist/src/setup.js +18 -6
  102. package/dist/src/setup.js.map +1 -1
  103. package/dist/src/sidebar-state.d.ts +20 -7
  104. package/dist/src/sidebar-state.d.ts.map +1 -1
  105. package/dist/src/sidebar-state.js +57 -8
  106. package/dist/src/sidebar-state.js.map +1 -1
  107. package/dist/src/tui.d.ts.map +1 -1
  108. package/dist/src/tui.js +43 -23
  109. package/dist/src/tui.js.map +1 -1
  110. package/dist/tui-build-map.json +9 -9
  111. package/dist/tui-ga-build-map.json +5 -5
  112. package/dist/types/src/cli.d.ts +3 -1
  113. package/dist/types/src/cli.d.ts.map +1 -1
  114. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  115. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +54 -5
  116. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  117. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  118. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +6 -1
  119. package/dist/types/src/ga/rpc/protocol.d.ts +11 -5
  120. package/dist/types/src/ga/rpc/protocol.d.ts.map +1 -1
  121. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  122. package/dist/types/src/plugin/account-access.d.ts +1 -0
  123. package/dist/types/src/plugin/account-access.d.ts.map +1 -1
  124. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  125. package/dist/types/src/plugin/background-quota-refresh.d.ts +11 -24
  126. package/dist/types/src/plugin/background-quota-refresh.d.ts.map +1 -1
  127. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  128. package/dist/types/src/plugin/cache/signature-cache.d.ts +3 -0
  129. package/dist/types/src/plugin/cache/signature-cache.d.ts.map +1 -1
  130. package/dist/types/src/plugin/cache.d.ts.map +1 -1
  131. package/dist/types/src/plugin/config/models.d.ts +1 -1
  132. package/dist/types/src/plugin/config/models.d.ts.map +1 -1
  133. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts +23 -0
  134. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts.map +1 -0
  135. package/dist/types/src/plugin/fetch/warmup.d.ts +9 -2
  136. package/dist/types/src/plugin/fetch/warmup.d.ts.map +1 -1
  137. package/dist/types/src/plugin/quota.d.ts +10 -2
  138. package/dist/types/src/plugin/quota.d.ts.map +1 -1
  139. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  140. package/dist/types/src/plugin/request.d.ts +12 -1
  141. package/dist/types/src/plugin/request.d.ts.map +1 -1
  142. package/dist/types/src/plugin/shared/request-services.d.ts +4 -1
  143. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  144. package/dist/types/src/plugin/shared/runtime.d.ts +3 -4
  145. package/dist/types/src/plugin/shared/runtime.d.ts.map +1 -1
  146. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +13 -7
  147. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  148. package/dist/types/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  149. package/dist/types/src/setup.d.ts +3 -0
  150. package/dist/types/src/setup.d.ts.map +1 -1
  151. package/dist/types/src/sidebar-state.d.ts +20 -7
  152. package/dist/types/src/sidebar-state.d.ts.map +1 -1
  153. package/package.json +3 -3
  154. package/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  155. package/src/common-auth-embedded/claustrum/consumer.js +32 -0
  156. package/src/common-auth-embedded/claustrum/custody.d.ts +54 -5
  157. package/src/common-auth-embedded/claustrum/custody.js +176 -22
  158. package/src/common-auth-embedded/claustrum/host.js +8 -0
  159. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  160. package/src/common-auth-embedded/claustrum/hub.js +10 -0
  161. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  162. package/src/common-auth-embedded/routing-accessor/index.d.ts +6 -1
  163. package/src/common-auth-embedded/routing-accessor/index.js +5 -3
  164. package/src/common-auth-embedded/setup/process-fence.js +20 -3
  165. package/src/common-auth-embedded/source-output.json +41 -41
  166. package/src/sidebar-state.ts +77 -8
  167. package/src/tui-compiled/sidebar-state.js +40 -1
  168. package/src/tui-compiled/tui.js +49 -24
  169. package/src/tui-ga-compiled/host-ga.js +11 -5
  170. package/src/tui-ga-raw/host-ga.tsx +17 -6
  171. package/src/tui-raw/sidebar-state.js +40 -1
  172. package/src/tui-raw/tui.tsx +40 -24
  173. package/src/tui.tsx +40 -24
package/dist/index.js CHANGED
@@ -385,6 +385,11 @@ function mergeQuotaState(stored, observation) {
385
385
  if (stored === void 0)
386
386
  return incoming;
387
387
  const prior = encodeQuotaState(decodeQuotaState(stored));
388
+ const previousAt = prior.cachedQuotaUpdatedAt;
389
+ const observedAt = incoming.cachedQuotaUpdatedAt;
390
+ if (typeof previousAt === "number" && typeof observedAt === "number" && observedAt < previousAt) {
391
+ throw new StaleQuotaObservationError();
392
+ }
388
393
  return encodeQuotaState(decodeQuotaState({ ...prior, ...incoming }));
389
394
  }
390
395
  function decodeRoutingSettings(raw) {
@@ -420,7 +425,7 @@ function createProviderStateCodec(policy) {
420
425
  }
421
426
  };
422
427
  }
423
- var AccountCodecError, MAX_JSON_DEPTH, IDENTIFIER, jsonValue, string, nonEmptyString, finiteNumber, count, credentialEpoch, boolean, rowId, required, optional, EXTENSIONS, CREDENTIAL_REFUSAL, CREDENTIAL_KEYS, POOL_FIELD_REFUSAL, QUOTA_FIELD_REFUSAL, LEGACY_FIELD_REFUSAL, METADATA_FIELD_REFUSAL, clientMetadataCodec, fingerprintCodec, fingerprintVersionCodec, dailyRequestCountsCodec, metadataShape, quotaShape, metadataForbidden, quotaForbidden, metadataCodec, providerStateCodec, quotaCodec, rowRefCodec, routingCodec, QUOTA_CODEC;
428
+ var AccountCodecError, MAX_JSON_DEPTH, IDENTIFIER, jsonValue, string, nonEmptyString, finiteNumber, count, credentialEpoch, boolean, rowId, required, optional, EXTENSIONS, CREDENTIAL_REFUSAL, CREDENTIAL_KEYS, POOL_FIELD_REFUSAL, QUOTA_FIELD_REFUSAL, LEGACY_FIELD_REFUSAL, METADATA_FIELD_REFUSAL, clientMetadataCodec, fingerprintCodec, fingerprintVersionCodec, dailyRequestCountsCodec, metadataShape, quotaShape, metadataForbidden, quotaForbidden, metadataCodec, providerStateCodec, quotaCodec, rowRefCodec, routingCodec, StaleQuotaObservationError, QUOTA_CODEC;
424
429
  var init_account_repository_codecs = __esm({
425
430
  "../core/dist/account-repository-codecs.js"() {
426
431
  "use strict";
@@ -590,6 +595,11 @@ var init_account_repository_codecs = __esm({
590
595
  gemini: optional(nullable(rowRefCodec))
591
596
  })))
592
597
  }, { forbidden: CREDENTIAL_KEYS });
598
+ StaleQuotaObservationError = class extends Error {
599
+ constructor() {
600
+ super("A newer quota observation is already stored");
601
+ }
602
+ };
593
603
  QUOTA_CODEC = {
594
604
  validate: isValidQuotaState,
595
605
  merge: mergeQuotaState
@@ -4129,6 +4139,8 @@ function getGemini38FlashAntigravityModel(tier) {
4129
4139
  }
4130
4140
  function getQuotaGroupForModel(modelId, hasArgonPool = false) {
4131
4141
  const normalized = modelId.toLowerCase();
4142
+ if (isGeminiNeonModel(normalized))
4143
+ return "gemini";
4132
4144
  if (isGeminiHydrogenModel(normalized))
4133
4145
  return "gemini";
4134
4146
  if (isGeminiCarbonModel(normalized))
@@ -4162,6 +4174,23 @@ function getGeminiHydrogenAntigravityModel(tier) {
4162
4174
  }
4163
4175
  }, tier);
4164
4176
  }
4177
+ function isGeminiNeonModel(model) {
4178
+ return /^(?:antigravity-)?gemini-4-neon(?:-(?:low|medium|high|xhigh))?$/i.test(model);
4179
+ }
4180
+ function supportsGeminiXHigh(model) {
4181
+ return isGeminiHydrogenModel(model) || isGeminiNeonModel(model);
4182
+ }
4183
+ function getGeminiNeonAntigravityModel(tier) {
4184
+ return getTieredAntigravityModel({
4185
+ defaultModel: "gemini-4-neon-high",
4186
+ byTier: {
4187
+ low: "gemini-4-neon-low",
4188
+ medium: "gemini-4-neon-medium",
4189
+ high: "gemini-4-neon-high",
4190
+ xhigh: "gemini-4-neon-xhigh"
4191
+ }
4192
+ }, tier);
4193
+ }
4165
4194
  function getGeminiCarbonAntigravityModel(tier) {
4166
4195
  return getTieredAntigravityModel({
4167
4196
  defaultModel: "gemini-4-carbon-medium",
@@ -4194,6 +4223,35 @@ var init_model_registry = __esm({
4194
4223
  DEFAULT_COST = { input: 0, output: 0 };
4195
4224
  DEFAULT_OPTIONS = {};
4196
4225
  AGY_NATIVE_MODEL_DEFINITIONS = {
4226
+ // Native CLI 1.5.9 catalog: all four Neon routes share the same limits.
4227
+ "gemini-4-neon-low": {
4228
+ displayName: "Gemini 4 Neon (Low)",
4229
+ maxTokens: 1048576,
4230
+ maxOutputTokens: 262144,
4231
+ model: "MODEL_PLACEHOLDER_M534",
4232
+ supportsThinking: true
4233
+ },
4234
+ "gemini-4-neon-medium": {
4235
+ displayName: "Gemini 4 Neon (Medium)",
4236
+ maxTokens: 1048576,
4237
+ maxOutputTokens: 262144,
4238
+ model: "MODEL_PLACEHOLDER_M533",
4239
+ supportsThinking: true
4240
+ },
4241
+ "gemini-4-neon-high": {
4242
+ displayName: "Gemini 4 Neon (High)",
4243
+ maxTokens: 1048576,
4244
+ maxOutputTokens: 262144,
4245
+ model: "MODEL_PLACEHOLDER_M532",
4246
+ supportsThinking: true
4247
+ },
4248
+ "gemini-4-neon-xhigh": {
4249
+ displayName: "Gemini 4 Neon (XHigh)",
4250
+ maxTokens: 1048576,
4251
+ maxOutputTokens: 262144,
4252
+ model: "MODEL_PLACEHOLDER_M535",
4253
+ supportsThinking: true
4254
+ },
4197
4255
  // Context: Google's "Introducing Gemini 4 Hydrogen" announcement (12 Nov 2026).
4198
4256
  // Output caps and route enums: native CLI 1.5.5 capture (13 Nov 2026).
4199
4257
  "gemini-4-hydrogen-low": {
@@ -4378,6 +4436,18 @@ var init_model_registry = __esm({
4378
4436
  };
4379
4437
  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.";
4380
4438
  ALL_MODEL_DEFINITIONS = {
4439
+ "antigravity-gemini-4-neon": defineModel("antigravity-gemini-4-neon", {
4440
+ name: "Gemini 4 Neon (Antigravity)",
4441
+ reasoning: true,
4442
+ limit: { context: 1048576, output: 262144 },
4443
+ modalities: DEFAULT_MODALITIES,
4444
+ variants: {
4445
+ low: { thinkingLevel: "low" },
4446
+ medium: { thinkingLevel: "medium" },
4447
+ high: { thinkingLevel: "high" },
4448
+ xhigh: { thinkingLevel: "xhigh" }
4449
+ }
4450
+ }),
4381
4451
  "antigravity-gemini-4-hydrogen": defineModel("antigravity-gemini-4-hydrogen", {
4382
4452
  name: "Gemini 4 Hydrogen (Antigravity)",
4383
4453
  reasoning: true,
@@ -4559,6 +4629,7 @@ var init_model_registry = __esm({
4559
4629
  "antigravity-gemini-4-argon",
4560
4630
  "antigravity-gemini-4-carbon",
4561
4631
  "antigravity-gemini-4-hydrogen",
4632
+ "antigravity-gemini-4-neon",
4562
4633
  "antigravity-gemini-3.8-flash",
4563
4634
  "antigravity-gemini-3.1-flash-image",
4564
4635
  "antigravity-claude-sonnet-5-5",
@@ -4997,9 +5068,7 @@ function reconcileRateLimitsFromReading(account, reading, now2) {
4997
5068
  function quotaRetryAfter(account, family, model, reason, retryAfterMs, now2) {
4998
5069
  if (reason !== "QUOTA_EXHAUSTED" || !(retryAfterMs && retryAfterMs > MAX_QUOTA_EXHAUSTED_BACKOFF_MS))
4999
5070
  return retryAfterMs;
5000
- const at = account.cachedQuotaUpdatedAt;
5001
- const group = resolveQuotaGroup(family, model, account.cachedQuota);
5002
- return at !== void 0 && Number.isFinite(at) && at > 0 && at <= now2 && account.cachedQuota?.[group]?.remainingFraction === 0 ? retryAfterMs : void 0;
5071
+ return quotaExhaustedUntil(account, family, model, now2) > now2 ? retryAfterMs : void 0;
5003
5072
  }
5004
5073
  function quotaExhaustedUntil(account, family, model, now2) {
5005
5074
  const at = account.cachedQuotaUpdatedAt;
@@ -7624,11 +7693,21 @@ var init_account_repository = __esm({
7624
7693
  rowId: ref.id
7625
7694
  });
7626
7695
  }
7627
- await this.store.recordQuota(ref.id, credentialFenceOf(ref), encoded);
7628
- await this.updateMetadata(ref, (metadata) => metadata ? {
7629
- kind: "set",
7630
- metadata: applyRateLimitReadingUpdate(metadata, rateLimitReadingUpdateOf(observation), this.now())
7631
- } : { kind: "keep" });
7696
+ try {
7697
+ await this.store.recordQuota(ref.id, credentialFenceOf(ref), encoded);
7698
+ } catch (error) {
7699
+ if (error instanceof StaleQuotaObservationError || error instanceof this.storeFailure && error.cause instanceof StaleQuotaObservationError)
7700
+ return;
7701
+ throw error;
7702
+ }
7703
+ await this.updateMetadata(ref, (metadata, row) => {
7704
+ if (!metadata || observation.cachedQuotaUpdatedAt == null || row.quota.status !== "present" || row.quota.quota.cachedQuotaUpdatedAt !== observation.cachedQuotaUpdatedAt)
7705
+ return { kind: "keep" };
7706
+ return {
7707
+ kind: "set",
7708
+ metadata: applyRateLimitReadingUpdate(metadata, rateLimitReadingUpdateOf(observation), this.now())
7709
+ };
7710
+ });
7632
7711
  });
7633
7712
  }
7634
7713
  // ---- selection and roster ---------------------------------------------
@@ -8243,7 +8322,7 @@ async function rmEvictingDir(evictingPath) {
8243
8322
  });
8244
8323
  }
8245
8324
  async function sleep(ms) {
8246
- await new Promise((resolve33) => setTimeout(resolve33, ms));
8325
+ await new Promise((resolve34) => setTimeout(resolve34, ms));
8247
8326
  }
8248
8327
  async function acquireFencedFileLock(options) {
8249
8328
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -8359,8 +8438,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now2) {
8359
8438
  let released = false;
8360
8439
  let lost = false;
8361
8440
  let lostResolve = null;
8362
- let lostPromise = new Promise((resolve33) => {
8363
- lostResolve = resolve33;
8441
+ let lostPromise = new Promise((resolve34) => {
8442
+ lostResolve = resolve34;
8364
8443
  });
8365
8444
  const markLost = () => {
8366
8445
  if (lost)
@@ -8370,9 +8449,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now2) {
8370
8449
  clearInterval(renewTimer);
8371
8450
  renewTimer = null;
8372
8451
  }
8373
- const resolve33 = lostResolve;
8452
+ const resolve34 = lostResolve;
8374
8453
  lostResolve = null;
8375
- resolve33?.();
8454
+ resolve34?.();
8376
8455
  };
8377
8456
  const setupRenew = () => {
8378
8457
  if (options.renew === false)
@@ -8575,7 +8654,7 @@ function writeConsoleLog(level, ...args) {
8575
8654
  }
8576
8655
  function createLogger(module) {
8577
8656
  const service = `antigravity.${module}`;
8578
- const log18 = (level, message, extra) => {
8657
+ const log19 = (level, message, extra) => {
8579
8658
  if (_sink) {
8580
8659
  try {
8581
8660
  _sink({ service, level, message, extra });
@@ -8589,10 +8668,10 @@ function createLogger(module) {
8589
8668
  }
8590
8669
  };
8591
8670
  return {
8592
- debug: (message, extra) => log18("debug", message, extra),
8593
- info: (message, extra) => log18("info", message, extra),
8594
- warn: (message, extra) => log18("warn", message, extra),
8595
- error: (message, extra) => log18("error", message, extra)
8671
+ debug: (message, extra) => log19("debug", message, extra),
8672
+ info: (message, extra) => log19("info", message, extra),
8673
+ warn: (message, extra) => log19("warn", message, extra),
8674
+ error: (message, extra) => log19("error", message, extra)
8596
8675
  };
8597
8676
  }
8598
8677
  var ENV_CONSOLE_LOG, _sink;
@@ -8995,7 +9074,7 @@ async function saveAccountStorageReplace(path5, incoming) {
8995
9074
  return mutateAccountStorage(path5, () => incoming);
8996
9075
  }
8997
9076
  async function clearAccountStorage(path5) {
8998
- const sleep5 = (ms) => new Promise((resolve33) => setTimeout(resolve33, ms));
9077
+ const sleep5 = (ms) => new Promise((resolve34) => setTimeout(resolve34, ms));
8999
9078
  const lock = await acquireWithRetry(path5, sleep5);
9000
9079
  try {
9001
9080
  await assertLegacyAccountStorageWritable(path5);
@@ -9043,7 +9122,7 @@ var init_account_storage = __esm({
9043
9122
  }
9044
9123
  };
9045
9124
  RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
9046
- DEFAULT_SLEEP = (ms) => new Promise((resolve33) => setTimeout(resolve33, ms));
9125
+ DEFAULT_SLEEP = (ms) => new Promise((resolve34) => setTimeout(resolve34, ms));
9047
9126
  DEFAULT_BUILD_BACKUP_PATH = (path5, now2) => `${path5}.corrupt-${now2.toISOString().replace(/[:.]/g, "-")}`;
9048
9127
  }
9049
9128
  });
@@ -9141,7 +9220,7 @@ function isStorageLockContention(error) {
9141
9220
  function quotaAccountIdentity(refreshToken) {
9142
9221
  return createHash3("sha256").update(refreshToken).digest("hex").slice(0, 16);
9143
9222
  }
9144
- function applyPendingRowWrite(metadata, pending, now2) {
9223
+ function applyPendingRowWrite(metadata, pending, now2, storedReadingAt) {
9145
9224
  let next = metadata;
9146
9225
  const resets = {};
9147
9226
  const cleared = [];
@@ -9163,7 +9242,7 @@ function applyPendingRowWrite(metadata, pending, now2) {
9163
9242
  delete written[key2];
9164
9243
  next = { ...next, rateLimitResetTimes: rates, rateLimitWrittenAt: written };
9165
9244
  }
9166
- if (pending.readingUpdate)
9245
+ if (storedReadingAt != null && pending.readingUpdate?.checkedAt === storedReadingAt)
9167
9246
  next = applyRateLimitReadingUpdate(next, pending.readingUpdate, now2);
9168
9247
  if (pending.cooldown !== void 0) {
9169
9248
  next = applyCooldownObservation(next, pending.cooldown.value);
@@ -9918,7 +9997,7 @@ var init_account_manager = __esm({
9918
9997
  for (const pending of rows) {
9919
9998
  repository.updateMetadata(pending.ref, (current, row) => ({
9920
9999
  kind: "set",
9921
- metadata: applyPendingRowWrite(current ?? { addedAt: row.storeAddedAt ?? this.now(), lastUsed: 0 }, pending, this.now())
10000
+ metadata: applyPendingRowWrite(current ?? { addedAt: row.storeAddedAt ?? this.now(), lastUsed: 0 }, pending, this.now(), row.quota.status === "present" ? row.quota.quota.cachedQuotaUpdatedAt : void 0)
9922
10001
  })).catch((error) => {
9923
10002
  if (error instanceof AccountRepositoryError && error.failure.kind === "lock-contention" && !error.failure.ambiguous) {
9924
10003
  this.requeueRowWrite(pending);
@@ -10297,8 +10376,8 @@ var init_account_manager = __esm({
10297
10376
  await this.saveInFlight;
10298
10377
  return;
10299
10378
  }
10300
- return new Promise((resolve33, reject) => {
10301
- this.savePromiseResolvers.push({ resolve: resolve33, reject });
10379
+ return new Promise((resolve34, reject) => {
10380
+ this.savePromiseResolvers.push({ resolve: resolve34, reject });
10302
10381
  });
10303
10382
  }
10304
10383
  async dispose() {
@@ -10341,8 +10420,8 @@ var init_account_manager = __esm({
10341
10420
  reject(error);
10342
10421
  throw error;
10343
10422
  }
10344
- for (const { resolve: resolve33 } of resolvers)
10345
- resolve33();
10423
+ for (const { resolve: resolve34 } of resolvers)
10424
+ resolve34();
10346
10425
  }
10347
10426
  async executeSave() {
10348
10427
  this.savePending = false;
@@ -10356,16 +10435,16 @@ var init_account_manager = __esm({
10356
10435
  }
10357
10436
  try {
10358
10437
  await this.saveToDisk();
10359
- for (const { resolve: resolve33 } of resolvers) {
10360
- resolve33();
10438
+ for (const { resolve: resolve34 } of resolvers) {
10439
+ resolve34();
10361
10440
  }
10362
10441
  } catch (error) {
10363
10442
  if (isStorageLockContention(error)) {
10364
10443
  this.onDiagnostic?.("Skipped account-state persist due to storage lock contention", {
10365
10444
  error: String(error)
10366
10445
  });
10367
- for (const { resolve: resolve33 } of resolvers) {
10368
- resolve33();
10446
+ for (const { resolve: resolve34 } of resolvers) {
10447
+ resolve34();
10369
10448
  }
10370
10449
  return;
10371
10450
  }
@@ -10403,13 +10482,13 @@ var init_account_manager = __esm({
10403
10482
  getAccountFingerprintHistory(accountIndex) {
10404
10483
  return this.selection.getAccountFingerprintHistory(accountIndex);
10405
10484
  }
10406
- updateQuotaCache(accountIndex, quotaGroups, expectedRefreshToken) {
10485
+ updateQuotaCache(accountIndex, quotaGroups, expectedRefreshToken, checkedAt = this.now()) {
10407
10486
  const account = this.accounts[accountIndex];
10408
- if (!account || account.parts.refreshToken !== expectedRefreshToken && expectedRefreshToken !== void 0)
10409
- return;
10487
+ if (!account || account.parts.refreshToken !== expectedRefreshToken && expectedRefreshToken !== void 0 || !Number.isFinite(checkedAt) || account.cachedQuotaUpdatedAt !== void 0 && checkedAt < account.cachedQuotaUpdatedAt)
10488
+ return false;
10410
10489
  account.cachedQuota = quotaGroups;
10411
10490
  account.cachedQuotaAccountId = quotaAccountIdentity(account.parts.refreshToken);
10412
- account.cachedQuotaUpdatedAt = this.now();
10491
+ account.cachedQuotaUpdatedAt = checkedAt;
10413
10492
  this.selection.reconcileQuotaReading(account, this.repository === void 0);
10414
10493
  const pending = account.ref ? this.pendingRowWrites.get(rowRefKey(account.ref)) : void 0;
10415
10494
  if (pending)
@@ -10425,6 +10504,7 @@ var init_account_manager = __esm({
10425
10504
  cachedQuotaUpdatedAt: account.cachedQuotaUpdatedAt
10426
10505
  };
10427
10506
  this.dispatch(account, "quota reading", (repository, ref) => repository.recordQuota(ref, reading));
10507
+ return true;
10428
10508
  }
10429
10509
  /**
10430
10510
  * Apply a subset of fields from a quota-fetch `updatedAccount` result onto
@@ -10549,6 +10629,35 @@ var init_account_manager = __esm({
10549
10629
  }
10550
10630
  return targets;
10551
10631
  }
10632
+ /** Fresh durable observations for poll admission, without flushing local writes. */
10633
+ async readAccountsForQuotaPoll() {
10634
+ if (!this.repository) {
10635
+ const accounts = new Map(this.accounts.map((a) => [a.parts.refreshToken, a]));
10636
+ return this.getAccountsForQuotaCheck().map((target) => {
10637
+ const account = accounts.get(target.refreshToken);
10638
+ return {
10639
+ ...target,
10640
+ cachedQuotaUpdatedAt: account?.cachedQuota && account.cachedQuotaUpdatedAt
10641
+ };
10642
+ });
10643
+ }
10644
+ const read = await this.repository.read();
10645
+ if (read.status !== "ready")
10646
+ throw new Error("The account store is not ready for quota polling");
10647
+ const rows = new Map(read.rows.filter((row) => row.usable && row.enabled).map((row) => [rowRefKey(row.ref), row]));
10648
+ return this.getAccountsForQuotaCheck().flatMap((target) => {
10649
+ const row = target.rowRef && rows.get(rowRefKey(target.rowRef));
10650
+ if (!row)
10651
+ return [];
10652
+ const quota = row.quota.status === "present" ? row.quota.quota : void 0;
10653
+ return [
10654
+ {
10655
+ ...target,
10656
+ cachedQuotaUpdatedAt: quota?.cachedQuota == null ? void 0 : quota.cachedQuotaUpdatedAt ?? void 0
10657
+ }
10658
+ ];
10659
+ });
10660
+ }
10552
10661
  getOldestQuotaCacheAge() {
10553
10662
  return this.selection.getOldestQuotaCacheAge();
10554
10663
  }
@@ -10627,6 +10736,14 @@ function orderAgyRequestPayloadInPlace(payload) {
10627
10736
  function countAgyRequestSteps(payload) {
10628
10737
  return Array.isArray(payload.contents) ? payload.contents.length : 0;
10629
10738
  }
10739
+ function appendAgyContinuation(contents, wireModel) {
10740
+ const last = contents.at(-1);
10741
+ if (last?.role !== "model" && last?.role !== "assistant")
10742
+ return;
10743
+ if (last.role === "model" && wireModel.startsWith("gemini-") && Array.isArray(last.parts) && last.parts.length > 0 && last.parts.every((part) => part?.functionResponse))
10744
+ return;
10745
+ contents.push({ role: "user", parts: [{ text: "[Continue]" }] });
10746
+ }
10630
10747
  function hasSecondUserTurn(payload) {
10631
10748
  if (!Array.isArray(payload.contents))
10632
10749
  return false;
@@ -10872,7 +10989,7 @@ function getHttpsProxy(url) {
10872
10989
  }
10873
10990
  }
10874
10991
  function waitForHead(socket, timeoutMs, onTimeout) {
10875
- return new Promise((resolve33, reject) => {
10992
+ return new Promise((resolve34, reject) => {
10876
10993
  let buffer = Buffer3.alloc(0);
10877
10994
  const timeout = setTimeout(() => {
10878
10995
  onTimeout();
@@ -10895,7 +11012,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
10895
11012
  return;
10896
11013
  const head = buffer.subarray(0, marker).toString("latin1");
10897
11014
  const leftover = buffer.subarray(marker + 4);
10898
- cleanup2(() => resolve33({ head, leftover }));
11015
+ cleanup2(() => resolve34({ head, leftover }));
10899
11016
  };
10900
11017
  socket.on("data", onData);
10901
11018
  socket.once("error", onError);
@@ -10909,7 +11026,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
10909
11026
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
10910
11027
  signal: signal ?? void 0
10911
11028
  });
10912
- await new Promise((resolve33, reject) => {
11029
+ await new Promise((resolve34, reject) => {
10913
11030
  const timeout = setTimeout(() => {
10914
11031
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
10915
11032
  proxySocket.destroy();
@@ -10918,7 +11035,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
10918
11035
  const cleanup2 = () => clearTimeout(timeout);
10919
11036
  proxySocket.once("connect", () => {
10920
11037
  cleanup2();
10921
- resolve33();
11038
+ resolve34();
10922
11039
  });
10923
11040
  proxySocket.once("error", (error) => {
10924
11041
  cleanup2();
@@ -10943,7 +11060,7 @@ Host: ${targetHost}:${targetPort}\r
10943
11060
  if (leftover.length > 0) {
10944
11061
  proxySocket.unshift(leftover);
10945
11062
  }
10946
- return await new Promise((resolve33, reject) => {
11063
+ return await new Promise((resolve34, reject) => {
10947
11064
  const tlsOptions = {
10948
11065
  socket: proxySocket,
10949
11066
  servername: targetHost,
@@ -10959,7 +11076,7 @@ Host: ${targetHost}:${targetPort}\r
10959
11076
  const cleanup2 = () => clearTimeout(timeout);
10960
11077
  tlsSocket.once("secureConnect", () => {
10961
11078
  cleanup2();
10962
- resolve33(tlsSocket);
11079
+ resolve34(tlsSocket);
10963
11080
  });
10964
11081
  tlsSocket.once("error", (error) => {
10965
11082
  cleanup2();
@@ -10968,7 +11085,7 @@ Host: ${targetHost}:${targetPort}\r
10968
11085
  });
10969
11086
  }
10970
11087
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
10971
- return await new Promise((resolve33, reject) => {
11088
+ return await new Promise((resolve34, reject) => {
10972
11089
  const tlsOptions = {
10973
11090
  host: targetUrl.hostname,
10974
11091
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -10985,7 +11102,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
10985
11102
  const cleanup2 = () => clearTimeout(timeout);
10986
11103
  socket.once("secureConnect", () => {
10987
11104
  cleanup2();
10988
- resolve33(socket);
11105
+ resolve34(socket);
10989
11106
  });
10990
11107
  socket.once("error", (error) => {
10991
11108
  cleanup2();
@@ -11071,15 +11188,24 @@ function buildResponseStream(socket, leftover, head, signal, idleTimeoutMs, onDe
11071
11188
  source.write(leftover);
11072
11189
  }
11073
11190
  socket.pipe(source);
11191
+ const stages = [source];
11192
+ let framing;
11074
11193
  let responseBody = source;
11075
11194
  if (head.chunked) {
11076
- responseBody = responseBody.pipe(new ChunkedDecodeStream());
11195
+ framing = new ChunkedDecodeStream();
11077
11196
  } else if (typeof head.contentLength === "number") {
11078
- responseBody = responseBody.pipe(new ContentLengthStream(head.contentLength));
11197
+ framing = new ContentLengthStream(head.contentLength);
11198
+ }
11199
+ if (framing) {
11200
+ responseBody = responseBody.pipe(framing);
11201
+ stages.push(framing);
11079
11202
  }
11080
11203
  if (head.gzip) {
11081
11204
  responseBody = responseBody.pipe(createGunzip());
11205
+ stages.push(responseBody);
11082
11206
  }
11207
+ let settled = false;
11208
+ let socketEnded = false;
11083
11209
  let idleTimer;
11084
11210
  const clearIdle = () => {
11085
11211
  if (idleTimer) {
@@ -11093,31 +11219,55 @@ function buildResponseStream(socket, leftover, head, signal, idleTimeoutMs, onDe
11093
11219
  clearIdle();
11094
11220
  idleTimer = setTimeout(() => {
11095
11221
  onDebug?.(`agy transport idle timeout after ${idleTimeoutMs}ms with no body data`);
11096
- socket.destroy(new Error(`Antigravity response stalled: no data for ${idleTimeoutMs}ms`));
11222
+ settle(new Error("Antigravity response stalled: no body data within the limit"));
11097
11223
  }, idleTimeoutMs);
11098
11224
  };
11099
- socket.on("data", armIdle);
11100
- armIdle();
11101
- const abort = () => socket.destroy(new DOMException("The operation was aborted", "AbortError"));
11102
- const cleanup2 = () => {
11225
+ const abort = () => settle(new DOMException("The operation was aborted", "AbortError"));
11226
+ const onSocketEnd = () => {
11227
+ socketEnded = true;
11228
+ };
11229
+ const onSocketClose = () => {
11230
+ if (!socketEnded && !framing?.complete) {
11231
+ settle(new Error("Antigravity response connection closed before the body ended"));
11232
+ }
11233
+ };
11234
+ const fail2 = (error) => settle(error instanceof Error ? error : new Error(String(error)));
11235
+ function settle(error) {
11236
+ if (settled)
11237
+ return;
11238
+ settled = true;
11103
11239
  clearIdle();
11104
11240
  socket.off("data", armIdle);
11241
+ socket.off("end", onSocketEnd);
11242
+ socket.off("close", onSocketClose);
11105
11243
  signal?.removeEventListener("abort", abort);
11106
- };
11244
+ socket.unpipe(source);
11245
+ socket.destroy();
11246
+ for (const stage of stages) {
11247
+ if (stage !== responseBody && !stage.destroyed)
11248
+ stage.destroy();
11249
+ }
11250
+ if (!responseBody.destroyed) {
11251
+ if (error)
11252
+ responseBody.destroy(error);
11253
+ else if (!responseBody.readableEnded)
11254
+ responseBody.destroy();
11255
+ }
11256
+ }
11257
+ socket.on("error", fail2);
11258
+ socket.on("data", armIdle);
11259
+ socket.once("end", onSocketEnd);
11260
+ socket.once("close", onSocketClose);
11261
+ for (const stage of stages)
11262
+ stage.on("error", fail2);
11263
+ responseBody.once("end", () => settle());
11264
+ responseBody.once("close", () => settle());
11265
+ armIdle();
11107
11266
  if (signal?.aborted) {
11108
11267
  abort();
11109
11268
  } else {
11110
11269
  signal?.addEventListener("abort", abort, { once: true });
11111
11270
  }
11112
- responseBody.once("end", () => {
11113
- cleanup2();
11114
- socket.destroy();
11115
- });
11116
- responseBody.once("error", () => {
11117
- cleanup2();
11118
- socket.destroy();
11119
- });
11120
- responseBody.once("close", cleanup2);
11121
11271
  return Readable.toWeb(responseBody);
11122
11272
  }
11123
11273
  async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
@@ -11175,6 +11325,11 @@ var init_agy_transport = __esm({
11175
11325
  constructor(contentLength) {
11176
11326
  super();
11177
11327
  this.remaining = contentLength;
11328
+ if (this.remaining <= 0)
11329
+ this.push(null);
11330
+ }
11331
+ get complete() {
11332
+ return this.remaining <= 0;
11178
11333
  }
11179
11334
  _transform(chunk, _encoding, callback) {
11180
11335
  if (this.remaining <= 0) {
@@ -11193,10 +11348,21 @@ var init_agy_transport = __esm({
11193
11348
  }
11194
11349
  callback();
11195
11350
  }
11351
+ _flush(callback) {
11352
+ callback(this.remaining > 0 ? new Error("Antigravity response ended before its declared length") : null);
11353
+ }
11196
11354
  };
11197
11355
  ChunkedDecodeStream = class extends Transform {
11198
11356
  buffer = Buffer3.alloc(0);
11357
+ finished = false;
11358
+ get complete() {
11359
+ return this.finished;
11360
+ }
11199
11361
  _transform(chunk, _encoding, callback) {
11362
+ if (this.finished) {
11363
+ callback();
11364
+ return;
11365
+ }
11200
11366
  this.buffer = Buffer3.concat([this.buffer, chunk]);
11201
11367
  try {
11202
11368
  this.flushAvailableChunks();
@@ -11207,8 +11373,9 @@ var init_agy_transport = __esm({
11207
11373
  }
11208
11374
  _flush(callback) {
11209
11375
  try {
11210
- this.flushAvailableChunks();
11211
- callback();
11376
+ if (!this.finished)
11377
+ this.flushAvailableChunks();
11378
+ callback(this.finished ? null : new Error("Antigravity response ended before its final chunk"));
11212
11379
  } catch (error) {
11213
11380
  callback(error instanceof Error ? error : new Error(String(error)));
11214
11381
  }
@@ -11224,16 +11391,19 @@ var init_agy_transport = __esm({
11224
11391
  if (!Number.isFinite(size)) {
11225
11392
  throw new Error(`Invalid chunk size: ${sizeLine}`);
11226
11393
  }
11227
- const chunkStart = lineEnd + 2;
11228
- const chunkEnd = chunkStart + size;
11229
- const nextOffset = chunkEnd + 2;
11230
- if (this.buffer.length < nextOffset)
11231
- return;
11232
11394
  if (size === 0) {
11395
+ if (this.buffer.indexOf("\r\n\r\n", lineEnd) === -1)
11396
+ return;
11397
+ this.finished = true;
11233
11398
  this.buffer = Buffer3.alloc(0);
11234
11399
  this.push(null);
11235
11400
  return;
11236
11401
  }
11402
+ const chunkStart = lineEnd + 2;
11403
+ const chunkEnd = chunkStart + size;
11404
+ const nextOffset = chunkEnd + 2;
11405
+ if (this.buffer.length < nextOffset)
11406
+ return;
11237
11407
  this.push(this.buffer.subarray(chunkStart, chunkEnd));
11238
11408
  this.buffer = this.buffer.subarray(nextOffset);
11239
11409
  }
@@ -13794,8 +13964,8 @@ async function acquireRefreshFileLockWithClock(options) {
13794
13964
  let releaseConfirmed = false;
13795
13965
  let loss;
13796
13966
  let resolveLoss;
13797
- const lostPromise = new Promise((resolve33) => {
13798
- resolveLoss = resolve33;
13967
+ const lostPromise = new Promise((resolve34) => {
13968
+ resolveLoss = resolve34;
13799
13969
  });
13800
13970
  function notifyTimerStep(event) {
13801
13971
  try {
@@ -13959,7 +14129,7 @@ async function acquireRefreshFileLockWithClock(options) {
13959
14129
  }
13960
14130
  }
13961
14131
  async function backoff() {
13962
- await new Promise((resolve33) => setTimeout(resolve33, Math.floor(Math.random() * 4)));
14132
+ await new Promise((resolve34) => setTimeout(resolve34, Math.floor(Math.random() * 4)));
13963
14133
  }
13964
14134
  async function readLockState(notifyReady = true) {
13965
14135
  if (notifyReady && options.onStep)
@@ -14052,7 +14222,7 @@ async function acquireRefreshFileLockWithClock(options) {
14052
14222
  const remainingMs = deadline - performance.now();
14053
14223
  if (remainingMs <= 0)
14054
14224
  throw original;
14055
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
14225
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
14056
14226
  if (performance.now() >= deadline)
14057
14227
  throw original;
14058
14228
  delayMs = Math.min(delayMs * 2, 50);
@@ -14555,7 +14725,7 @@ async function acquireRefreshFileLockWithClock(options) {
14555
14725
  const remainingMs = deadline - performance.now();
14556
14726
  if (remainingMs <= 0)
14557
14727
  break;
14558
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
14728
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
14559
14729
  if (windowsPrivateFiles && performance.now() >= deadline)
14560
14730
  break;
14561
14731
  delayMs = Math.min(delayMs * 2, 50);
@@ -14640,7 +14810,7 @@ async function withLock(target, options, fn) {
14640
14810
  timeoutMs: options.timeoutMs
14641
14811
  });
14642
14812
  }
14643
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(25, Math.ceil(remaining))));
14813
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(25, Math.ceil(remaining))));
14644
14814
  }
14645
14815
  }
14646
14816
  var LockContentionError, LockOwnershipError;
@@ -14730,7 +14900,7 @@ async function acquirePoolLock(spec, defaults2, env3) {
14730
14900
  });
14731
14901
  }
14732
14902
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
14733
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(options.retryMs + jitter, remaining)));
14903
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(options.retryMs + jitter, remaining)));
14734
14904
  }
14735
14905
  }
14736
14906
  function definedOnly(spec) {
@@ -17643,11 +17813,11 @@ var init_quota_writer = __esm({
17643
17813
  const left = deadline - performance.now();
17644
17814
  if (left <= 0)
17645
17815
  throw refusal2("pull", id, "lock-contention", `pool quota queue for ${id} is full (${POOL_QUOTA_QUEUE_LIMIT} readings) and the store locks stayed held`, true);
17646
- await new Promise((resolve33) => {
17816
+ await new Promise((resolve34) => {
17647
17817
  const done = () => {
17648
17818
  clearTimeout(timer);
17649
17819
  this.wake.delete(done);
17650
- resolve33();
17820
+ resolve34();
17651
17821
  };
17652
17822
  const timer = setTimeout(done, left);
17653
17823
  this.wake.add(done);
@@ -20379,6 +20549,8 @@ async function request(operation) {
20379
20549
  function wrapHostClient(client) {
20380
20550
  const watchScoped = client.watchScoped?.bind(client);
20381
20551
  const reportUsageScoped = client.reportUsageScoped?.bind(client);
20552
+ const reportCondition = client.reportCondition?.bind(client);
20553
+ const clearCondition = client.clearCondition?.bind(client);
20382
20554
  return {
20383
20555
  listScoped: (...args) => request(() => client.listScoped(...args)),
20384
20556
  getScoped: (...args) => request(() => client.getScoped(...args)),
@@ -20399,6 +20571,12 @@ function wrapHostClient(client) {
20399
20571
  ...reportUsageScoped && {
20400
20572
  reportUsageScoped: (...args) => request(() => reportUsageScoped(...args))
20401
20573
  },
20574
+ ...reportCondition && {
20575
+ reportCondition: (...args) => request(() => reportCondition(...args))
20576
+ },
20577
+ ...clearCondition && {
20578
+ clearCondition: (...args) => request(() => clearCondition(...args))
20579
+ },
20402
20580
  ...client.insula && {
20403
20581
  insula: wrapInsula(client.insula)
20404
20582
  }
@@ -20770,7 +20948,7 @@ async function select(terminal, items, options) {
20770
20948
  writeLine("");
20771
20949
  renderedLines = lines;
20772
20950
  };
20773
- return new Promise((resolve33) => {
20951
+ return new Promise((resolve34) => {
20774
20952
  const wasRaw = stdin.isRaw ?? false;
20775
20953
  const cleanup2 = () => {
20776
20954
  if (cleaned)
@@ -20790,7 +20968,7 @@ async function select(terminal, items, options) {
20790
20968
  };
20791
20969
  const finish = (value) => {
20792
20970
  cleanup2();
20793
- resolve33(value);
20971
+ resolve34(value);
20794
20972
  };
20795
20973
  const onSignal = () => finish(null);
20796
20974
  const onKey = (data) => {
@@ -20830,7 +21008,7 @@ async function select(terminal, items, options) {
20830
21008
  stdin.setRawMode(true);
20831
21009
  } catch {
20832
21010
  cleanup2();
20833
- resolve33(null);
21011
+ resolve34(null);
20834
21012
  return;
20835
21013
  }
20836
21014
  stdin.resume();
@@ -22856,10 +23034,10 @@ async function drainShutdown(pending, onTimeout) {
22856
23034
  try {
22857
23035
  await Promise.race([
22858
23036
  drained,
22859
- new Promise((resolve33) => {
23037
+ new Promise((resolve34) => {
22860
23038
  timer = setTimeout(() => {
22861
23039
  expired = true;
22862
- resolve33();
23040
+ resolve34();
22863
23041
  }, 2e3);
22864
23042
  })
22865
23043
  ]);
@@ -23077,22 +23255,22 @@ function credentialTypeOf(row, family) {
23077
23255
  return notMine;
23078
23256
  if ("classify" in family) {
23079
23257
  const metadata = rowFactsOf(row);
23080
- let type;
23258
+ let type2;
23081
23259
  switch (metadata.authMethod) {
23082
23260
  case "apikey":
23083
- type = "api_key";
23261
+ type2 = "api_key";
23084
23262
  break;
23085
23263
  case "chatgpt":
23086
23264
  case "antigravity":
23087
23265
  case "oauth":
23088
- type = "oauth";
23266
+ type2 = "oauth";
23089
23267
  break;
23090
23268
  default:
23091
23269
  return { kind: "refused", code: "unknown-auth-method" };
23092
23270
  }
23093
23271
  const facts = {
23094
23272
  credentialId: row.id,
23095
- credentialType: type,
23273
+ credentialType: type2,
23096
23274
  categories: row.categories,
23097
23275
  refreshAdapter: row.refreshAdapter,
23098
23276
  ...metadata
@@ -23104,24 +23282,59 @@ function credentialTypeOf(row, family) {
23104
23282
  if (result.kind === "not-mine")
23105
23283
  return notMine;
23106
23284
  if (result.kind === "mine" && typeof result.member === "string")
23107
- return { kind: "mine", type, member: result.member };
23285
+ return { kind: "mine", type: type2, member: result.member };
23108
23286
  if (result.kind === "refused" && typeof result.code === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(result.code) && !result.code.includes("\n") && family.refusalCodes.includes(result.code))
23109
23287
  return { kind: "refused", code: result.code };
23110
23288
  } catch {
23111
23289
  }
23112
23290
  return { kind: "refused", code: "unclassified" };
23113
23291
  }
23114
- if (row.credentialType !== "oauth" && row.credentialType !== "api_key")
23292
+ const type = row.credentialType;
23293
+ if (type === "oauth") {
23294
+ if (row.refreshAdapter !== family.refreshAdapter)
23295
+ return notMine;
23296
+ } else if (type === "api_key") {
23297
+ if (!family.apiKeys || row.refreshAdapter !== void 0)
23298
+ return notMine;
23299
+ } else {
23115
23300
  return notMine;
23116
- if (row.credentialType === "oauth")
23117
- return row.refreshAdapter === family.refreshAdapter ? { kind: "mine", type: "oauth" } : notMine;
23118
- if (row.credentialType === "api_key" && family.apiKeys)
23119
- return row.refreshAdapter === void 0 ? { kind: "mine", type: "api_key" } : notMine;
23120
- return notMine;
23301
+ }
23302
+ const { authMethod } = rowFactsOf(row, { includeProviderIds: false });
23303
+ if (authMethod !== void 0) {
23304
+ const matchesType = type === "oauth" ? authMethod === "chatgpt" || authMethod === "antigravity" || authMethod === "oauth" : authMethod === "apikey";
23305
+ if (!matchesType)
23306
+ return { kind: "refused", code: "unknown-auth-method" };
23307
+ }
23308
+ return { kind: "mine", type };
23121
23309
  }
23122
- function rowFactsOf(row) {
23310
+ function rowFactsOf(row, { includeProviderIds = true } = {}) {
23123
23311
  const metadata = row;
23124
- return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
23312
+ return {
23313
+ providerIds: includeProviderIds ? metadata.providerIds : void 0,
23314
+ authMethod: metadata.authMethod
23315
+ };
23316
+ }
23317
+ function isVaultConditionReason(reason) {
23318
+ return reason === "provider_verification_required" || reason === "provider_ineligible";
23319
+ }
23320
+ function vaultConditionOf(row) {
23321
+ const condition = row.condition;
23322
+ if (!condition)
23323
+ return void 0;
23324
+ const { reason, sinceMs } = condition;
23325
+ if (isVaultConditionReason(reason) && Number.isSafeInteger(sinceMs) && sinceMs > 0)
23326
+ return Object.freeze({ reason, sinceMs });
23327
+ return void 0;
23328
+ }
23329
+ function httpsActionUrl(actionUrl) {
23330
+ if (typeof actionUrl !== "string")
23331
+ return void 0;
23332
+ try {
23333
+ if (new URL(actionUrl).protocol === "https:")
23334
+ return actionUrl;
23335
+ } catch {
23336
+ }
23337
+ return void 0;
23125
23338
  }
23126
23339
  function grantReachOf(listed) {
23127
23340
  const { grants, grantTuples } = listed;
@@ -23161,6 +23374,10 @@ var init_custody = __esm({
23161
23374
  #logger;
23162
23375
  #provenance = /* @__PURE__ */ new WeakMap();
23163
23376
  #reports = /* @__PURE__ */ new WeakMap();
23377
+ #conditionReports = /* @__PURE__ */ new Map();
23378
+ #conditionClears = /* @__PURE__ */ new Map();
23379
+ #conditionsUnsupported = false;
23380
+ #pendingConditionCalls = 0;
23164
23381
  #kept = /* @__PURE__ */ new Map();
23165
23382
  #keptAttempts = /* @__PURE__ */ new WeakMap();
23166
23383
  #usage;
@@ -23179,8 +23396,9 @@ var init_custody = __esm({
23179
23396
  #closed = false;
23180
23397
  /** The view of the last successful `discover()`, for `watchRoster`. */
23181
23398
  #discoveredView;
23399
+ #discoveredConditions = /* @__PURE__ */ new Map();
23182
23400
  #watches = /* @__PURE__ */ new Set();
23183
- #tokenReads = /* @__PURE__ */ new Set();
23401
+ #shutdownWork = /* @__PURE__ */ new Set();
23184
23402
  #warnShutdown;
23185
23403
  #onDrainTimeout;
23186
23404
  #disposing;
@@ -23239,6 +23457,7 @@ var init_custody = __esm({
23239
23457
  if (hasVaultHost() && !isVaultHostClient(next))
23240
23458
  throw new ClaustrumUnreachableError();
23241
23459
  this.#client = next;
23460
+ this.#conditionsUnsupported = false;
23242
23461
  for (const watch2 of this.#watches)
23243
23462
  watch2.restart();
23244
23463
  }
@@ -23307,12 +23526,12 @@ var init_custody = __esm({
23307
23526
  phase: "token read begin"
23308
23527
  });
23309
23528
  const pending = this.#readToken();
23310
- this.#tokenReads.add(pending);
23529
+ this.#shutdownWork.add(pending);
23311
23530
  let value;
23312
23531
  try {
23313
23532
  value = await pending;
23314
23533
  } finally {
23315
- this.#tokenReads.delete(pending);
23534
+ this.#shutdownWork.delete(pending);
23316
23535
  if (phaseDiagnostics.hasSubscribers)
23317
23536
  phaseDiagnostics.publish({
23318
23537
  logger: this.#logger,
@@ -23365,6 +23584,11 @@ var init_custody = __esm({
23365
23584
  async discover(signal) {
23366
23585
  const inventory = await this.#list(signal);
23367
23586
  this.#discoveredView = inventory.view;
23587
+ this.#discoveredConditions.clear();
23588
+ for (const { credentialId, condition } of inventory.credentials) {
23589
+ if (condition)
23590
+ this.#discoveredConditions.set(credentialId, condition);
23591
+ }
23368
23592
  return inventory;
23369
23593
  }
23370
23594
  async #list(signal) {
@@ -23438,6 +23662,7 @@ var init_custody = __esm({
23438
23662
  });
23439
23663
  continue;
23440
23664
  }
23665
+ const condition = vaultConditionOf(row);
23441
23666
  credentials.push(Object.freeze({
23442
23667
  credentialId: row.id,
23443
23668
  credentialType: type,
@@ -23447,20 +23672,22 @@ var init_custody = __esm({
23447
23672
  },
23448
23673
  state: row.state,
23449
23674
  ...row.email !== void 0 && { email: row.email },
23450
- ...row.orgName !== void 0 && { orgName: row.orgName }
23675
+ ...row.orgName !== void 0 && { orgName: row.orgName },
23676
+ ...condition && { condition }
23451
23677
  }));
23452
23678
  }
23453
23679
  for (const record5 of skipped)
23454
23680
  this.#logger.warn("skipped malformed vault record", record5);
23455
23681
  const grantReach = grantReachOf(inventory);
23682
+ const classifying = "classify" in this.#family;
23456
23683
  return {
23457
23684
  view: inventory.view,
23458
23685
  credentials: Object.freeze(credentials),
23459
23686
  skipped: Object.freeze(skipped),
23460
- ..."classify" in this.#family && {
23461
- refused: Object.freeze(refused2),
23462
- notMine
23687
+ ...(classifying || refused2.length > 0) && {
23688
+ refused: Object.freeze(refused2)
23463
23689
  },
23690
+ ...classifying && { notMine },
23464
23691
  ...grantReach && { grantReach }
23465
23692
  };
23466
23693
  }
@@ -23654,7 +23881,7 @@ var init_custody = __esm({
23654
23881
  }
23655
23882
  #receiptBackoff(delay5, signal) {
23656
23883
  this.#check(signal);
23657
- return new Promise((resolve33, reject) => {
23884
+ return new Promise((resolve34, reject) => {
23658
23885
  const abort = () => {
23659
23886
  this.#clearTimeout(timer);
23660
23887
  signal.removeEventListener("abort", abort);
@@ -23662,7 +23889,7 @@ var init_custody = __esm({
23662
23889
  };
23663
23890
  const timer = this.#setTimeout(() => {
23664
23891
  signal.removeEventListener("abort", abort);
23665
- resolve33();
23892
+ resolve34();
23666
23893
  }, delay5);
23667
23894
  timer.unref?.();
23668
23895
  signal.addEventListener("abort", abort, { once: true });
@@ -23791,6 +24018,90 @@ var init_custody = __esm({
23791
24018
  throw error;
23792
24019
  }
23793
24020
  }
24021
+ /**
24022
+ * Report a provider login condition as bookkeeping after handing back the
24023
+ * reply, never on the request path. Pass the receipt actually sent with it.
24024
+ */
24025
+ reportCondition(attempt, input2) {
24026
+ const provenance = this.#provenance.get(attempt);
24027
+ if (!provenance)
24028
+ return Promise.reject(new ClaustrumConsumerError("no-receipt", "Claustrum condition report requires an original dispatch receipt"));
24029
+ const { reason, providerStatus } = input2 ?? {};
24030
+ if (this.#closed || this.#keptAttempts.has(attempt) || providerStatus !== 403 || !isVaultConditionReason(reason))
24031
+ return Promise.resolve("skipped");
24032
+ const { credentialId, recordVersion } = attempt;
24033
+ const actionUrl = reason === "provider_verification_required" ? httpsActionUrl(input2.actionUrl) : void 0;
24034
+ return this.#conditionOnce(this.#conditionReports, JSON.stringify([credentialId, recordVersion, reason]), { credentialId, recordVersion, reason }, (client) => client.reportCondition?.({
24035
+ credentialId,
24036
+ recordVersion,
24037
+ reason,
24038
+ providerStatus,
24039
+ ...actionUrl !== void 0 && { actionUrl },
24040
+ enrollmentToken: provenance.token
24041
+ }));
24042
+ }
24043
+ /**
24044
+ * Clear a listed condition as bookkeeping after handing back a successful
24045
+ * reply, never on the request path. Pass the receipt actually sent with it.
24046
+ */
24047
+ clearCondition(attempt) {
24048
+ const provenance = this.#provenance.get(attempt);
24049
+ if (!provenance)
24050
+ return Promise.reject(new ClaustrumConsumerError("no-receipt", "Claustrum condition clear requires an original dispatch receipt"));
24051
+ if (this.#closed || this.#keptAttempts.has(attempt))
24052
+ return Promise.resolve("skipped");
24053
+ const { credentialId, recordVersion } = attempt;
24054
+ const condition = this.#discoveredConditions.get(credentialId);
24055
+ if (!condition)
24056
+ return Promise.resolve("skipped");
24057
+ return this.#conditionOnce(this.#conditionClears, JSON.stringify([credentialId, condition.sinceMs]), { credentialId, recordVersion, reason: condition.reason }, (client) => client.clearCondition?.({
24058
+ credentialId,
24059
+ recordVersion,
24060
+ enrollmentToken: provenance.token
24061
+ }));
24062
+ }
24063
+ #conditionOnce(outcomes, key2, details, send) {
24064
+ const previous = outcomes.get(key2);
24065
+ if (previous)
24066
+ return previous;
24067
+ if (this.#conditionsUnsupported)
24068
+ return Promise.resolve("unsupported");
24069
+ const pending = Promise.resolve().then(async () => {
24070
+ const client = this.#client;
24071
+ if (this.#conditionsUnsupported)
24072
+ return "unsupported";
24073
+ try {
24074
+ const sent = send(client);
24075
+ if (!sent)
24076
+ return "unsupported";
24077
+ if (await sent === false)
24078
+ this.#debugCondition("scoped login condition not cleared", details);
24079
+ return "reported";
24080
+ } catch (error) {
24081
+ if (error instanceof ClaustrumCredentialError5 && error.code === "unknown_method") {
24082
+ if (client === this.#client)
24083
+ this.#conditionsUnsupported = true;
24084
+ return "unsupported";
24085
+ }
24086
+ this.#debugCondition("scoped login condition update failed", details);
24087
+ return "failed";
24088
+ }
24089
+ });
24090
+ outcomes.set(key2, pending);
24091
+ this.#pendingConditionCalls++;
24092
+ this.#shutdownWork.add(pending);
24093
+ void pending.then(() => {
24094
+ this.#pendingConditionCalls--;
24095
+ this.#shutdownWork.delete(pending);
24096
+ });
24097
+ return pending;
24098
+ }
24099
+ #debugCondition(message, details) {
24100
+ try {
24101
+ this.#logger.debug(message, details);
24102
+ } catch {
24103
+ }
24104
+ }
23794
24105
  /**
23795
24106
  * Watch this consumer's visible vault accounts instead of listing them on a
23796
24107
  * short timer. Opens one `watchScoped` on this custody's client and calls
@@ -23906,15 +24217,17 @@ var init_custody = __esm({
23906
24217
  this.#watches.clear();
23907
24218
  this.#kept.clear();
23908
24219
  const usage = this.#usage.close();
24220
+ const keepClientOpen = usage !== void 0 || this.#pendingConditionCalls > 0;
23909
24221
  if (usage) {
23910
- this.#tokenReads.add(usage);
23911
- void usage.then(() => this.#tokenReads.delete(usage));
23912
- } else
24222
+ this.#shutdownWork.add(usage);
24223
+ void usage.then(() => this.#shutdownWork.delete(usage));
24224
+ }
24225
+ if (!keepClientOpen)
23913
24226
  this.#client.close();
23914
- this.#disposing = drainShutdown(this.#tokenReads, (count4) => (this.#onDrainTimeout ?? this.#warnShutdown)(count4)).finally(() => {
24227
+ this.#disposing = drainShutdown(this.#shutdownWork, (count4) => (this.#onDrainTimeout ?? this.#warnShutdown)(count4)).finally(() => {
23915
24228
  this.#usage.drop();
23916
24229
  this.#usageServed.clear();
23917
- if (usage)
24230
+ if (keepClientOpen)
23918
24231
  this.#client.close();
23919
24232
  });
23920
24233
  }
@@ -24898,7 +25211,7 @@ var init_consumer = __esm({
24898
25211
  this.#shutdown.signal,
24899
25212
  ...signal ? [signal] : []
24900
25213
  ]);
24901
- return new Promise((resolve33, reject) => {
25214
+ return new Promise((resolve34, reject) => {
24902
25215
  const cleanup2 = () => {
24903
25216
  combined.signal.removeEventListener("abort", abort);
24904
25217
  combined.dispose();
@@ -24913,7 +25226,7 @@ var init_consumer = __esm({
24913
25226
  if (combined.signal.aborted)
24914
25227
  reject(combined.signal.reason);
24915
25228
  else
24916
- resolve33(value);
25229
+ resolve34(value);
24917
25230
  }, (error) => {
24918
25231
  cleanup2();
24919
25232
  reject(error);
@@ -25509,6 +25822,36 @@ var init_consumer = __esm({
25509
25822
  throw new ClaustrumConsumerError("no-receipt", "Claustrum dispatch receipt has no active owner");
25510
25823
  await this.#custody.reportFailure(attempt, status, source);
25511
25824
  }
25825
+ /** The custody (or hub lease) that issued `attempt`, or a `no-receipt` refusal. */
25826
+ #issuingCustody(attempt) {
25827
+ const custody = this.#hub ? this.#issuedBy.get(attempt)?.custody : this.#custody;
25828
+ if (!custody)
25829
+ throw new ClaustrumConsumerError("no-receipt", "Claustrum dispatch receipt has no active owner");
25830
+ return custody;
25831
+ }
25832
+ /**
25833
+ * Report a provider login condition through the custody that issued the
25834
+ * receipt; see `ClaustrumScopedCustody.reportCondition`. Bookkeeping: call it
25835
+ * after handing back the reply, never on the request path. It resolves
25836
+ * `skipped` after shutdown and rejects only with `no-receipt` for a receipt
25837
+ * no live custody of this consumer issued.
25838
+ */
25839
+ async reportCondition(attempt, input2) {
25840
+ if (this.#shutdown.signal.aborted)
25841
+ return "skipped";
25842
+ return this.#issuingCustody(attempt).reportCondition(attempt, input2);
25843
+ }
25844
+ /**
25845
+ * Clear a listed login condition through the custody that issued the
25846
+ * receipt; see `ClaustrumScopedCustody.clearCondition`. Safe to call after
25847
+ * every successful reply: it sends nothing unless the login is marked.
25848
+ * Same `skipped` and `no-receipt` rules as `reportCondition`.
25849
+ */
25850
+ async clearCondition(attempt) {
25851
+ if (this.#shutdown.signal.aborted)
25852
+ return "skipped";
25853
+ return this.#issuingCustody(attempt).clearCondition(attempt);
25854
+ }
25512
25855
  /**
25513
25856
  * Send on a vault route. `dispatch` builds and sends the request with the
25514
25857
  * receipt's token and may be called twice, so it must be able to rebuild
@@ -25719,12 +26062,12 @@ function unreachableConnect2() {
25719
26062
  return new ClaustrumUnreachableError();
25720
26063
  }
25721
26064
  function untilAborted(pending, signal) {
25722
- return new Promise((resolve33, reject) => {
26065
+ return new Promise((resolve34, reject) => {
25723
26066
  const abort = () => reject(signal.reason);
25724
26067
  signal.addEventListener("abort", abort, { once: true });
25725
26068
  pending.then((value) => {
25726
26069
  signal.removeEventListener("abort", abort);
25727
- resolve33(value);
26070
+ resolve34(value);
25728
26071
  }, (error) => {
25729
26072
  signal.removeEventListener("abort", abort);
25730
26073
  reject(error);
@@ -26115,6 +26458,16 @@ var init_hub = __esm({
26115
26458
  check();
26116
26459
  return custody.reportFailure(attempt, status, source);
26117
26460
  },
26461
+ reportCondition: async (attempt, input2) => {
26462
+ if (state2.released || generation.ended)
26463
+ return "skipped";
26464
+ return custody.reportCondition(attempt, input2);
26465
+ },
26466
+ clearCondition: async (attempt) => {
26467
+ if (state2.released || generation.ended)
26468
+ return "skipped";
26469
+ return custody.clearCondition(attempt);
26470
+ },
26118
26471
  reportUsage: (input2) => {
26119
26472
  if (!state2.released && !generation.ended)
26120
26473
  custody.reportUsage(input2);
@@ -27789,9 +28142,11 @@ var init_pre_response_deadline = __esm({
27789
28142
  this.cancelTimer = void 0;
27790
28143
  }
27791
28144
  resume() {
28145
+ const paused = !this.active;
27792
28146
  this.active = true;
27793
28147
  this.check();
27794
- this.arm();
28148
+ if (paused)
28149
+ this.arm();
27795
28150
  }
27796
28151
  /** Cancel a response that arrives after its sender lost the abort race. */
27797
28152
  open(work) {
@@ -27930,11 +28285,11 @@ function diagnostics(chain, error) {
27930
28285
  }) : [String(error)];
27931
28286
  return redactCredentialText([...new Set(messages)].join("; caused by "));
27932
28287
  }
27933
- function hostFailure(error, log18) {
28288
+ function hostFailure(error, log19) {
27934
28289
  if (error instanceof HostRefusalError || error instanceof AccountStoreBusyError || error instanceof PreResponseTimeoutError || isUpstreamFailure(error) || error instanceof Error && error.name === "ClaustrumUnreachableError" && error.message === "Claustrum vault could not be reached")
27935
28290
  return error;
27936
28291
  const chain = errorChain(error);
27937
- log18(diagnostics(chain, error));
28292
+ log19(diagnostics(chain, error));
27938
28293
  if (error instanceof Error && error.name === "ClaustrumCredentialError" && "code" in error && error.code === "grant_denied") {
27939
28294
  return Object.assign(new HostRefusalError("The vault refused access to the selected account. Check the plugin log for details."), { code: "grant_denied" });
27940
28295
  }
@@ -28004,8 +28359,8 @@ function getDefaultTierId(allowedTiers) {
28004
28359
  return allowedTiers[0]?.id;
28005
28360
  }
28006
28361
  function wait(ms) {
28007
- return new Promise((resolve33) => {
28008
- setTimeout(resolve33, ms);
28362
+ return new Promise((resolve34) => {
28363
+ setTimeout(resolve34, ms);
28009
28364
  });
28010
28365
  }
28011
28366
  function extractManagedProjectId(payload) {
@@ -28046,7 +28401,7 @@ function invalidateProjectContextCache(refresh) {
28046
28401
  function clearProvisionFailedKeys() {
28047
28402
  provisionFailedKeys.clear();
28048
28403
  }
28049
- async function loadManagedProject(accessToken, _projectId) {
28404
+ async function loadManagedProject(accessToken, _projectId, admit2) {
28050
28405
  const requestBody = buildBootstrapRequestBody();
28051
28406
  const loadHeaders = buildAntigravityHarnessBootstrapHeaders(accessToken);
28052
28407
  const loadEndpoints = Array.from(/* @__PURE__ */ new Set([
@@ -28054,6 +28409,8 @@ async function loadManagedProject(accessToken, _projectId) {
28054
28409
  ...ANTIGRAVITY_ENDPOINT_FALLBACKS
28055
28410
  ]));
28056
28411
  for (const baseEndpoint of loadEndpoints) {
28412
+ if (admit2)
28413
+ await admit2();
28057
28414
  try {
28058
28415
  const response = await fetchWithAgyCliTransport(`${baseEndpoint}/v1internal:loadCodeAssist`, {
28059
28416
  method: "POST",
@@ -28073,7 +28430,7 @@ async function loadManagedProject(accessToken, _projectId) {
28073
28430
  }
28074
28431
  return null;
28075
28432
  }
28076
- async function onboardManagedProject(accessToken, tierId, projectId, attempts2 = 10, delayMs = 5e3) {
28433
+ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 = 10, delayMs = 5e3, admit2) {
28077
28434
  const requestBody = { tierId };
28078
28435
  const onboardEndpoints = Array.from(/* @__PURE__ */ new Set([
28079
28436
  ANTIGRAVITY_ENDPOINT_PROD,
@@ -28082,6 +28439,8 @@ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 =
28082
28439
  ]));
28083
28440
  for (const baseEndpoint of onboardEndpoints) {
28084
28441
  for (let attempt = 0; attempt < attempts2; attempt += 1) {
28442
+ if (admit2)
28443
+ await admit2();
28085
28444
  try {
28086
28445
  const response = await fetchWithAgyCliTransport(`${baseEndpoint}/v1internal:onboardUser`, {
28087
28446
  method: "POST",
@@ -28116,7 +28475,7 @@ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 =
28116
28475
  }
28117
28476
  return void 0;
28118
28477
  }
28119
- async function ensureProjectContext(auth) {
28478
+ async function ensureProjectContext(auth, admit2) {
28120
28479
  const accessToken = auth.access;
28121
28480
  if (!accessToken) {
28122
28481
  return { auth, effectiveProjectId: "" };
@@ -28160,7 +28519,7 @@ async function ensureProjectContext(auth) {
28160
28519
  capturedTier
28161
28520
  };
28162
28521
  };
28163
- const loadPayload = await loadManagedProject(accessToken, parts.projectId ?? fallbackProjectId);
28522
+ const loadPayload = await loadManagedProject(accessToken, parts.projectId ?? fallbackProjectId, admit2);
28164
28523
  const capturedTierId = loadPayload?.currentTier?.id;
28165
28524
  const paidTierId = typeof loadPayload?.paidTier === "string" ? loadPayload.paidTier : loadPayload?.paidTier?.id;
28166
28525
  const tierFromPayload = capturedTierId ? {
@@ -28177,7 +28536,7 @@ async function ensureProjectContext(auth) {
28177
28536
  tierId,
28178
28537
  projectId: parts.projectId
28179
28538
  });
28180
- const provisionedProjectId = await onboardManagedProject(accessToken, tierId, parts.projectId);
28539
+ const provisionedProjectId = await onboardManagedProject(accessToken, tierId, parts.projectId, void 0, void 0, admit2);
28181
28540
  if (provisionedProjectId) {
28182
28541
  log3.debug("Successfully provisioned managed project", {
28183
28542
  provisionedProjectId
@@ -28832,7 +29191,7 @@ function applyAgyNativeGenerationConfig(wireModel, generationConfig, options = {
28832
29191
  includeThoughts: true,
28833
29192
  ...typeof budget === "number" ? { thinkingBudget: budget } : { thinkingLevel: capturedTier.toUpperCase() }
28834
29193
  };
28835
- } else if (isGeminiHydrogenModel(wireModel)) {
29194
+ } else if (supportsGeminiXHigh(wireModel)) {
28836
29195
  const tier = wireModel.toLowerCase().split("-").at(-1);
28837
29196
  generationConfig.thinkingConfig = {
28838
29197
  includeThoughts: true,
@@ -29709,10 +30068,10 @@ function getAgyGemini31ProThinkingBudget(tier) {
29709
30068
  function resolveModelWithTier(requestedModel) {
29710
30069
  const isAntigravity = QUOTA_PREFIX_REGEX.test(requestedModel);
29711
30070
  const modelWithoutQuota = requestedModel.replace(QUOTA_PREFIX_REGEX, "");
29712
- if (isGeminiHydrogenModel(modelWithoutQuota)) {
29713
- const tier2 = modelWithoutQuota.toLowerCase().match(HYDROGEN_TIER_REGEX)?.[1];
30071
+ if (supportsGeminiXHigh(modelWithoutQuota)) {
30072
+ const tier2 = modelWithoutQuota.toLowerCase().match(XHIGH_TIER_REGEX)?.[1];
29714
30073
  return {
29715
- actualModel: getGeminiHydrogenAntigravityModel(tier2),
30074
+ actualModel: isGeminiNeonModel(modelWithoutQuota) ? getGeminiNeonAntigravityModel(tier2) : getGeminiHydrogenAntigravityModel(tier2),
29716
30075
  thinkingLevel: tier2 ?? "high",
29717
30076
  tier: tier2 ?? "high",
29718
30077
  isThinkingModel: true
@@ -29890,7 +30249,7 @@ function resolveAntigravityModel(requestedModel) {
29890
30249
  const prefixedModel = `antigravity-${transformedModel}`;
29891
30250
  return resolveModelWithTier(prefixedModel);
29892
30251
  }
29893
- var THINKING_TIER_BUDGETS, MODEL_ALIASES, TIER_REGEX, HYDROGEN_TIER_REGEX, QUOTA_PREFIX_REGEX, GEMINI_3_PRO_REGEX, GEMINI_3_FLASH_REGEX, IMAGE_GENERATION_MODELS;
30252
+ var THINKING_TIER_BUDGETS, MODEL_ALIASES, TIER_REGEX, XHIGH_TIER_REGEX, QUOTA_PREFIX_REGEX, GEMINI_3_PRO_REGEX, GEMINI_3_FLASH_REGEX, IMAGE_GENERATION_MODELS;
29894
30253
  var init_model_resolver = __esm({
29895
30254
  "../core/dist/transform/model-resolver.js"() {
29896
30255
  "use strict";
@@ -29903,7 +30262,7 @@ var init_model_resolver = __esm({
29903
30262
  };
29904
30263
  MODEL_ALIASES = getResolverAliasMap();
29905
30264
  TIER_REGEX = /-(minimal|low|medium|high)$/;
29906
- HYDROGEN_TIER_REGEX = /-(low|medium|high|xhigh)$/i;
30265
+ XHIGH_TIER_REGEX = /-(low|medium|high|xhigh)$/i;
29907
30266
  QUOTA_PREFIX_REGEX = /^antigravity-/i;
29908
30267
  GEMINI_3_PRO_REGEX = /^gemini-3(?:\.\d+)?-pro/i;
29909
30268
  GEMINI_3_FLASH_REGEX = /^gemini-3(?:\.\d+)?-flash/i;
@@ -30417,12 +30776,12 @@ var init_vault_provider_state = __esm({
30417
30776
  function untilAborted2(pending, signal) {
30418
30777
  if (!signal)
30419
30778
  return pending;
30420
- return new Promise((resolve33, reject) => {
30779
+ return new Promise((resolve34, reject) => {
30421
30780
  const abort = () => reject(signal.reason);
30422
30781
  signal.addEventListener("abort", abort, { once: true });
30423
30782
  if (signal.aborted)
30424
30783
  abort();
30425
- pending.then(resolve33, reject).finally(() => signal.removeEventListener("abort", abort));
30784
+ pending.then(resolve34, reject).finally(() => signal.removeEventListener("abort", abort));
30426
30785
  });
30427
30786
  }
30428
30787
  async function resolveClaustrumConnectionPath(explicit) {
@@ -30604,6 +30963,8 @@ function createAntigravityVaultAccountSource(options) {
30604
30963
  return response;
30605
30964
  },
30606
30965
  reportServedStatus,
30966
+ reportCondition: async (admission, input2) => consumer.reportCondition(issuedEntry(admission).receipt, input2),
30967
+ clearCondition: async (admission) => consumer.clearCondition(issuedEntry(admission).receipt),
30607
30968
  attribution: (admission) => {
30608
30969
  issuedEntry(admission);
30609
30970
  return Object.freeze({
@@ -30760,7 +31121,7 @@ function getAntigravityVersionResolution() {
30760
31121
  return lastResolution ?? { version: getAntigravityVersion(), source: "fallback" };
30761
31122
  }
30762
31123
  async function initAntigravityVersion() {
30763
- const log18 = createLogger("version");
31124
+ const log19 = createLogger("version");
30764
31125
  const fallback = getAntigravityVersion();
30765
31126
  let version;
30766
31127
  let source;
@@ -30774,15 +31135,15 @@ async function initAntigravityVersion() {
30774
31135
  } else {
30775
31136
  source = "fallback";
30776
31137
  setAntigravityVersion(fallback);
30777
- log18.info("version-fetch-failed", { fallback });
31138
+ log19.info("version-fetch-failed", { fallback });
30778
31139
  lastResolution = { version: fallback, source };
30779
31140
  return lastResolution;
30780
31141
  }
30781
31142
  }
30782
31143
  if (version !== fallback) {
30783
- log18.info("version-updated", { version, source, previous: fallback });
31144
+ log19.info("version-updated", { version, source, previous: fallback });
30784
31145
  } else {
30785
- log18.debug("version-unchanged", { version, source });
31146
+ log19.debug("version-unchanged", { version, source });
30786
31147
  }
30787
31148
  setAntigravityVersion(version);
30788
31149
  lastResolution = { version, source };
@@ -32858,13 +33219,13 @@ function closeDebugStream(state2) {
32858
33219
  state2.logWriter = () => {
32859
33220
  };
32860
33221
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
32861
- return new Promise((resolve33) => {
32862
- current.once("close", () => resolve33());
32863
- current.once("error", () => resolve33());
33222
+ return new Promise((resolve34) => {
33223
+ current.once("close", () => resolve34());
33224
+ current.once("error", () => resolve34());
32864
33225
  try {
32865
33226
  current.end();
32866
33227
  } catch {
32867
- resolve33();
33228
+ resolve34();
32868
33229
  }
32869
33230
  });
32870
33231
  }
@@ -33129,13 +33490,13 @@ function closeDebugLog() {
33129
33490
  if (!state2 || !current) return Promise.resolve();
33130
33491
  state2.logStream = null;
33131
33492
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
33132
- return new Promise((resolve33) => {
33133
- current.once("close", () => resolve33());
33134
- current.once("error", () => resolve33());
33493
+ return new Promise((resolve34) => {
33494
+ current.once("close", () => resolve34());
33495
+ current.once("error", () => resolve34());
33135
33496
  try {
33136
33497
  current.end();
33137
33498
  } catch {
33138
- resolve33();
33499
+ resolve34();
33139
33500
  }
33140
33501
  });
33141
33502
  }
@@ -33319,19 +33680,19 @@ function initLogger3(client) {
33319
33680
  }
33320
33681
  function createLogger4(module) {
33321
33682
  let channel3;
33322
- const log18 = (level, message, extra) => {
33683
+ const log19 = (level, message, extra) => {
33323
33684
  channel3 ??= getLegacyLogger().createLogger(module);
33324
33685
  channel3[level](message, extra);
33325
33686
  };
33326
33687
  return {
33327
- debug: (message, extra) => log18("debug", message, extra),
33328
- info: (message, extra) => log18("info", message, extra),
33688
+ debug: (message, extra) => log19("debug", message, extra),
33689
+ info: (message, extra) => log19("info", message, extra),
33329
33690
  hostInfo: (message, extra) => {
33330
33691
  channel3 ??= getLegacyLogger().createLogger(module);
33331
33692
  channel3.hostInfo?.(message, extra);
33332
33693
  },
33333
- warn: (message, extra) => log18("warn", message, extra),
33334
- error: (message, extra) => log18("error", message, extra)
33694
+ warn: (message, extra) => log19("warn", message, extra),
33695
+ error: (message, extra) => log19("error", message, extra)
33335
33696
  };
33336
33697
  }
33337
33698
  var ENV_CONSOLE_LOG2, LOG_LEVEL_FROM_OPERATOR, legacyClient, legacyLogger;
@@ -33403,10 +33764,7 @@ function createVaultRequestCredentials(source, onAdmitted) {
33403
33764
  const admission = await source.admit(account.route, signal);
33404
33765
  if (onAdmitted)
33405
33766
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
33406
- const grant = new VaultSendGrant(
33407
- admission,
33408
- (status) => source.reportServedStatus(admission, status)
33409
- );
33767
+ const grant = new VaultSendGrant(admission, source);
33410
33768
  issued.set(grant, admission);
33411
33769
  return grant;
33412
33770
  }
@@ -33825,12 +34183,12 @@ function createVaultAccountPool(options) {
33825
34183
  try {
33826
34184
  return await Promise.race([
33827
34185
  read.then(() => true),
33828
- new Promise((resolve33, reject) => {
34186
+ new Promise((resolve34, reject) => {
33829
34187
  const abort = () => reject(signal?.reason);
33830
34188
  signal?.addEventListener("abort", abort, { once: true });
33831
34189
  detachAbort = () => signal?.removeEventListener("abort", abort);
33832
34190
  if (remaining !== void 0)
33833
- cancelTimer2 = schedule2(() => resolve33(false), remaining);
34191
+ cancelTimer2 = schedule2(() => resolve34(false), remaining);
33834
34192
  if (signal?.aborted) abort();
33835
34193
  })
33836
34194
  ]);
@@ -33919,7 +34277,7 @@ function vaultQuotaState(quota, at) {
33919
34277
  }
33920
34278
  async function checkVaultQuota(input2) {
33921
34279
  const state2 = input2.pool.state;
33922
- const rows = [...input2.pool.selector.rows];
34280
+ const routes = input2.routes ?? input2.pool.selector.rows.map((row) => row.route);
33923
34281
  const now2 = input2.now ?? (() => Date.now());
33924
34282
  const reportError = (error) => {
33925
34283
  try {
@@ -33930,11 +34288,11 @@ async function checkVaultQuota(input2) {
33930
34288
  let checked = 0;
33931
34289
  if (state2 === void 0) input2.onOutcome?.("state-invalid");
33932
34290
  const readings = [];
33933
- for (const row of rows) {
34291
+ for (const route of routes) {
33934
34292
  if (input2.signal.aborted || state2 === void 0) break;
33935
34293
  try {
33936
34294
  input2.onStage?.("fetch");
33937
- const answer = await input2.fetchReading(row.route, input2.signal);
34295
+ const answer = await input2.fetchReading(route, input2.signal);
33938
34296
  input2.signal.throwIfAborted();
33939
34297
  if (answer === void 0) {
33940
34298
  input2.onOutcome?.("fetch-failed");
@@ -33958,7 +34316,7 @@ async function checkVaultQuota(input2) {
33958
34316
  }
33959
34317
  }
33960
34318
  if (state2 === void 0 || readings.length === 0 || input2.signal.aborted)
33961
- return { checked, notChecked: rows.length - checked };
34319
+ return { checked, notChecked: routes.length - checked };
33962
34320
  let results;
33963
34321
  try {
33964
34322
  input2.onStage?.("commit");
@@ -33966,8 +34324,11 @@ async function checkVaultQuota(input2) {
33966
34324
  results = await state2.recordQuotas(readings, input2.signal);
33967
34325
  } catch (error) {
33968
34326
  for (const _ of readings) reportError(error);
33969
- return { checked, notChecked: rows.length - checked };
34327
+ return { checked, notChecked: routes.length - checked };
33970
34328
  }
34329
+ const liveByRoute = new Map(
34330
+ input2.pool.selector.rows.map((row) => [row.route.routeId, row])
34331
+ );
33971
34332
  for (const [at, { attribution, quota: reading }] of readings.entries()) {
33972
34333
  const result = results[at];
33973
34334
  if (result === void 0 || result.status === "refused") {
@@ -33985,17 +34346,15 @@ async function checkVaultQuota(input2) {
33985
34346
  }
33986
34347
  checked += 1;
33987
34348
  input2.onOutcome?.("recorded");
33988
- const live = input2.pool.selector.rows.find(
33989
- (candidate) => candidate.route.routeId === attribution.routeId && candidate.route.credentialId === attribution.credentialId && candidate.route.accountIdentity === attribution.accountIdentity
33990
- );
33991
- if (live !== void 0) {
34349
+ const live = liveByRoute.get(attribution.routeId);
34350
+ if (live?.route.credentialId === attribution.credentialId && live.route.accountIdentity === attribution.accountIdentity) {
33992
34351
  const cached = cachedQuotaOf(reading);
33993
34352
  if (cached !== void 0) live.cachedQuota = cached;
33994
34353
  live.cachedQuotaUpdatedAt = reading.cachedQuotaUpdatedAt ?? void 0;
33995
34354
  input2.pool.selector.reconcileQuotaReading(live);
33996
34355
  }
33997
34356
  }
33998
- return { checked, notChecked: rows.length - checked };
34357
+ return { checked, notChecked: routes.length - checked };
33999
34358
  }
34000
34359
  var VaultSendGrant, VAULT_REFRESH_STALL_MS, VAULT_DISPLAY_ROSTER_WAIT_MS;
34001
34360
  var init_vault_request_credentials = __esm({
@@ -34009,7 +34368,9 @@ var init_vault_request_credentials = __esm({
34009
34368
  recordVersion;
34010
34369
  projectId;
34011
34370
  report401;
34012
- constructor(admission, report) {
34371
+ reportCondition;
34372
+ clearCondition;
34373
+ constructor(admission, source) {
34013
34374
  Object.defineProperty(this, "accessToken", {
34014
34375
  value: admission.accessToken,
34015
34376
  enumerable: false
@@ -34019,7 +34380,9 @@ var init_vault_request_credentials = __esm({
34019
34380
  this.recordVersion = admission.recordVersion;
34020
34381
  this.projectId = admission.projectId;
34021
34382
  this.fromKeptReceipt = admission.fromKeptReceipt;
34022
- this.report401 = report;
34383
+ this.report401 = (status) => source.reportServedStatus(admission, status);
34384
+ this.reportCondition = source.reportCondition?.bind(source, admission);
34385
+ this.clearCondition = source.clearCondition?.bind(source, admission);
34023
34386
  }
34024
34387
  };
34025
34388
  VAULT_REFRESH_STALL_MS = 3e4;
@@ -34356,11 +34719,11 @@ function createOpenCodeVaultCustody(options) {
34356
34719
  ].join("\n");
34357
34720
  const waitForApproval = async () => {
34358
34721
  while (!closed2) {
34359
- await new Promise((resolve33) => {
34722
+ await new Promise((resolve34) => {
34360
34723
  const done = () => {
34361
34724
  clearTimeout(timer);
34362
34725
  cancelWait = void 0;
34363
- resolve33();
34726
+ resolve34();
34364
34727
  };
34365
34728
  const timer = setTimeout(done, 2e3);
34366
34729
  timer.unref?.();
@@ -34787,7 +35150,7 @@ async function prepareVaultFolder(options) {
34787
35150
  const kept = refusals.get(key2);
34788
35151
  if (kept)
34789
35152
  return override ? { ...override, refusal: kept } : refused(accountFile, kept);
34790
- const log18 = options.log ?? createLogger4("runtime-layout");
35153
+ const log19 = options.log ?? createLogger4("runtime-layout");
34791
35154
  const version = options.version ?? await pluginPackageVersion().catch(() => "unknown");
34792
35155
  try {
34793
35156
  if (override) {
@@ -34796,11 +35159,11 @@ async function prepareVaultFolder(options) {
34796
35159
  await prepareRuntimeLayout({
34797
35160
  version,
34798
35161
  accountFile,
34799
- log: log18,
35162
+ log: log19,
34800
35163
  ...options.layoutLockWaitMs === void 0 ? {} : { layoutLockWaitMs: options.layoutLockWaitMs }
34801
35164
  });
34802
35165
  if (options.accountStore !== false)
34803
- await prepareAccountStore({ version, log: log18 });
35166
+ await prepareAccountStore({ version, log: log19 });
34804
35167
  } catch (error) {
34805
35168
  const refusal3 = error instanceof RuntimeLayoutRefusal ? error : new RuntimeLayoutRefusal(
34806
35169
  override?.vaultDir ?? runtimeLayoutLocation().stateHomeDir,
@@ -34808,7 +35171,7 @@ async function prepareVaultFolder(options) {
34808
35171
  );
34809
35172
  if (!refusals.has(key2)) {
34810
35173
  refusals.set(key2, refusal3);
34811
- log18.warn(refusal3.message, {
35174
+ log19.warn(refusal3.message, {
34812
35175
  stateDir: refusal3.stateDir,
34813
35176
  errorClass: refusal3.errorClass
34814
35177
  });
@@ -34929,10 +35292,10 @@ function errorFile(error) {
34929
35292
  ...typeof stage === "string" && stage ? { stage } : {}
34930
35293
  };
34931
35294
  }
34932
- function logCleanupFailure(location, log18, step, error) {
35295
+ function logCleanupFailure(location, log19, step, error) {
34933
35296
  logOnce(
34934
35297
  `${location.key}\0cleanup`,
34935
- () => log18.warn(
35298
+ () => log19.warn(
34936
35299
  "antigravity-auth could not finish removing its old vault files from OpenCode's config folder; it tries again at the next start",
34937
35300
  {
34938
35301
  configDir: location.configDir,
@@ -34961,13 +35324,13 @@ function prepareRuntimeLayout(options) {
34961
35324
  return run;
34962
35325
  }
34963
35326
  async function decide(location, options) {
34964
- const log18 = options.log ?? createLogger4("runtime-layout");
35327
+ const log19 = options.log ?? createLogger4("runtime-layout");
34965
35328
  const stateDir = location.stateHomeDir;
34966
35329
  const markerPath = join18(stateDir, RUNTIME_LAYOUT_MARKER_FILE);
34967
35330
  const files = layoutFiles(location, options.accountFile);
34968
35331
  const fence = options.fence ?? defaultFence(options.version);
34969
35332
  const stateHome = async () => {
34970
- await settleVault(location, options, "state-home", log18);
35333
+ await settleVault(location, options, "state-home", log19);
34971
35334
  return "state-home";
34972
35335
  };
34973
35336
  let marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -34978,7 +35341,7 @@ async function decide(location, options) {
34978
35341
  join18(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)
34979
35342
  ).catch(() => true);
34980
35343
  if (!manifestLeft) {
34981
- await settleVault(location, options, "state-home", log18);
35344
+ await settleVault(location, options, "state-home", log19);
34982
35345
  return stateHome();
34983
35346
  }
34984
35347
  }
@@ -34990,7 +35353,7 @@ async function decide(location, options) {
34990
35353
  RUNTIME_LAYOUT_LOCK_NAME,
34991
35354
  markerPath,
34992
35355
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
34993
- log18
35356
+ log19
34994
35357
  );
34995
35358
  } catch (error) {
34996
35359
  marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -35010,7 +35373,7 @@ async function decide(location, options) {
35010
35373
  const legacy = async () => {
35011
35374
  try {
35012
35375
  await lock.assertOwned();
35013
- await settleVault(location, options, "legacy", log18);
35376
+ await settleVault(location, options, "legacy", log19);
35014
35377
  } catch (error) {
35015
35378
  throw new RuntimeLayoutRefusal(stateDir, errorClass(error));
35016
35379
  }
@@ -35024,20 +35387,20 @@ async function decide(location, options) {
35024
35387
  if (!marker.oldFilesRemoved && !aliased)
35025
35388
  await finishOldFiles(location, files, markerPath, marker, lock, {
35026
35389
  fence,
35027
- log: log18,
35390
+ log: log19,
35028
35391
  steps: options.steps,
35029
35392
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile()
35030
35393
  });
35031
35394
  else if (marker.oldFilesRemoved) {
35032
35395
  await refuseReappearedFiles(location, files);
35033
- await removeLeftoverManifest(location, lock, options.steps, log18);
35396
+ await removeLeftoverManifest(location, lock, options.steps, log19);
35034
35397
  }
35035
35398
  return await stateHome();
35036
35399
  }
35037
35400
  if (aliased) {
35038
35401
  logOnce(
35039
35402
  `${location.key}\0aliased`,
35040
- () => log18.warn(
35403
+ () => log19.warn(
35041
35404
  "antigravity-auth keeps its vault files in OpenCode's config folder: its state folder is that same folder",
35042
35405
  { configDir: location.configDir, stateDir }
35043
35406
  )
@@ -35046,14 +35409,14 @@ async function decide(location, options) {
35046
35409
  }
35047
35410
  const gate = await fence();
35048
35411
  if (!gate.open) {
35049
- logDeferral(location, gate.blockers, log18);
35412
+ logDeferral(location, gate.blockers, log19);
35050
35413
  return await legacy();
35051
35414
  }
35052
35415
  let markerStarted = false;
35053
35416
  try {
35054
35417
  const outcome = await moveFiles(location, files, markerPath, lock, {
35055
35418
  fence,
35056
- log: log18,
35419
+ log: log19,
35057
35420
  steps: options.steps,
35058
35421
  destinationPrivate: options.destinationPrivate ?? defaultDestinationPrivate,
35059
35422
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile(),
@@ -35062,13 +35425,13 @@ async function decide(location, options) {
35062
35425
  }
35063
35426
  });
35064
35427
  if (outcome.kind === "deferred") {
35065
- logDeferral(location, outcome.blockers, log18);
35428
+ logDeferral(location, outcome.blockers, log19);
35066
35429
  return await legacy();
35067
35430
  }
35068
35431
  if (outcome.kind === "refused") {
35069
35432
  logOnce(
35070
35433
  `${location.key}\0refused`,
35071
- () => log18.warn(
35434
+ () => log19.warn(
35072
35435
  outcome.reason === "destination-not-private" ? "antigravity-auth keeps its vault files in OpenCode's config folder: the vault folder in its state folder already exists and is not private to your user. It was left unchanged; remove it if it holds nothing you need, then restart OpenCode." : "antigravity-auth keeps its vault files in OpenCode's config folder: it will not move them",
35073
35436
  { reason: outcome.reason, paths: outcome.paths, stateDir }
35074
35437
  )
@@ -35076,7 +35439,7 @@ async function decide(location, options) {
35076
35439
  return await legacy();
35077
35440
  }
35078
35441
  if (outcome.moved)
35079
- log18.info(
35442
+ log19.info(
35080
35443
  "antigravity-auth moved its vault files out of OpenCode's config folder",
35081
35444
  { from: files.vault.old, to: files.vault.next }
35082
35445
  );
@@ -35087,7 +35450,7 @@ async function decide(location, options) {
35087
35450
  return await stateHome();
35088
35451
  logOnce(
35089
35452
  `${location.key}\0failed`,
35090
- () => log18.warn(
35453
+ () => log19.warn(
35091
35454
  "antigravity-auth's vault files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",
35092
35455
  {
35093
35456
  configDir: location.configDir,
@@ -35136,7 +35499,7 @@ async function prepareAccountStore(options) {
35136
35499
  if (!await localAccountStoreAuthorized()) return void 0;
35137
35500
  const decided = decidedAccountStoreAnchor(location);
35138
35501
  if (decided) return decided;
35139
- const log18 = options.log ?? createLogger4("runtime-layout");
35502
+ const log19 = options.log ?? createLogger4("runtime-layout");
35140
35503
  const runKey = `${location.stateHomeDir}\0${location.key}`;
35141
35504
  let run = processState.storeRuns.get(runKey);
35142
35505
  if (!run) {
@@ -35147,12 +35510,12 @@ async function prepareAccountStore(options) {
35147
35510
  RUNTIME_LAYOUT_LOCK_NAME,
35148
35511
  join18(location.stateHomeDir, RUNTIME_LAYOUT_MARKER_FILE),
35149
35512
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
35150
- log18
35513
+ log19
35151
35514
  );
35152
35515
  try {
35153
35516
  await lock.assertOwned();
35154
35517
  if (!await localAccountStoreAuthorized()) return void 0;
35155
- return await settleAccountStore(location, options, log18);
35518
+ return await settleAccountStore(location, options, log19);
35156
35519
  } finally {
35157
35520
  await lock.release();
35158
35521
  }
@@ -35163,20 +35526,20 @@ async function prepareAccountStore(options) {
35163
35526
  }
35164
35527
  return run;
35165
35528
  }
35166
- async function settleAccountStore(location, options, log18) {
35529
+ async function settleAccountStore(location, options, log19) {
35167
35530
  const decided = decidedAccountStoreAnchor(location);
35168
35531
  if (decided) return decided;
35169
- const anchor = await decideAccountStore(location, options, log18);
35532
+ const anchor = await decideAccountStore(location, options, log19);
35170
35533
  setAccountStoreAnchor(location, anchor);
35171
35534
  return anchor;
35172
35535
  }
35173
- async function decideAccountStore(location, options, log18) {
35174
- const keepConfig = () => recordAnchor(location, options, "config", log18);
35536
+ async function decideAccountStore(location, options, log19) {
35537
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
35175
35538
  if (processHasOlderGeneration()) {
35176
35539
  logOnce(
35177
35540
  "older-generation-account-store",
35178
35541
  () => showLog(
35179
- log18,
35542
+ log19,
35180
35543
  "antigravity-auth keeps the account store in OpenCode's config folder until OpenCode restarts, because an older version of the plugin ran in this process.",
35181
35544
  { accountStore: "config" }
35182
35545
  )
@@ -35190,7 +35553,7 @@ async function decideAccountStore(location, options, log18) {
35190
35553
  if (!sameSpelling(forward.legacyPath, stateAnchor)) {
35191
35554
  logOnce(
35192
35555
  `${location.key}\0store-forward-elsewhere`,
35193
- () => log18.warn(
35556
+ () => log19.warn(
35194
35557
  "the account store moved to another folder than this process resolved; check XDG_STATE_HOME",
35195
35558
  { movedTo: forward.legacyPath, expected: stateAnchor }
35196
35559
  )
@@ -35201,9 +35564,9 @@ async function decideAccountStore(location, options, log18) {
35201
35564
  options,
35202
35565
  configAnchor,
35203
35566
  stateAnchor,
35204
- log18
35567
+ log19
35205
35568
  );
35206
- return recordAnchor(location, options, "state-home", log18);
35569
+ return recordAnchor(location, options, "state-home", log19);
35207
35570
  }
35208
35571
  if (decidedRuntimeLayout(location) === "legacy") return keepConfig();
35209
35572
  const configStore = await presentAccountStore(configAnchor);
@@ -35215,9 +35578,9 @@ async function decideAccountStore(location, options, log18) {
35215
35578
  `antigravity-auth cannot start: two account stores exist, one at ${configAnchor} and one at ${stateAnchor}, and neither is marked as moved. Keep the one you want and move the other one aside, then restart OpenCode.`
35216
35579
  );
35217
35580
  }
35218
- if (stateStore) return recordAnchor(location, options, "state-home", log18);
35581
+ if (stateStore) return recordAnchor(location, options, "state-home", log19);
35219
35582
  if (configStore) {
35220
- if (!await storeMovePathResolves(stateAnchor, location, log18))
35583
+ if (!await storeMovePathResolves(stateAnchor, location, log19))
35221
35584
  return keepConfig();
35222
35585
  return moveStore(
35223
35586
  location,
@@ -35225,21 +35588,21 @@ async function decideAccountStore(location, options, log18) {
35225
35588
  configAnchor,
35226
35589
  stateAnchor,
35227
35590
  false,
35228
- log18,
35591
+ log19,
35229
35592
  false
35230
35593
  );
35231
35594
  }
35232
- if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log18))
35595
+ if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log19))
35233
35596
  return keepConfig();
35234
- if (!await storeMovePathResolves(stateAnchor, location, log18))
35597
+ if (!await storeMovePathResolves(stateAnchor, location, log19))
35235
35598
  return keepConfig();
35236
- return initializeStore(location, options, stateAnchor, log18);
35599
+ return initializeStore(location, options, stateAnchor, log19);
35237
35600
  }
35238
- function showLog(log18, message, meta) {
35239
- if (log18.log) log18.log(message, meta);
35240
- else log18.info(message, meta);
35601
+ function showLog(log19, message, meta) {
35602
+ if (log19.log) log19.log(message, meta);
35603
+ else log19.info(message, meta);
35241
35604
  }
35242
- async function recordAnchor(location, options, anchor, log18) {
35605
+ async function recordAnchor(location, options, anchor, log19) {
35243
35606
  try {
35244
35607
  await recordProcessAnchor({
35245
35608
  key: location.key,
@@ -35251,32 +35614,32 @@ async function recordAnchor(location, options, anchor, log18) {
35251
35614
  }
35252
35615
  if (anchor === "state-home")
35253
35616
  showLog(
35254
- log18,
35617
+ log19,
35255
35618
  "antigravity-auth keeps its account store in its state folder",
35256
35619
  { accountStore: anchor }
35257
35620
  );
35258
35621
  return anchor;
35259
35622
  }
35260
- async function storeMovePathResolves(stateAnchor, location, log18) {
35623
+ async function storeMovePathResolves(stateAnchor, location, log19) {
35261
35624
  if (folderResolvesToItself(
35262
35625
  join18(location.stateHomeDir, "antigravity-accounts.json")
35263
35626
  ))
35264
35627
  return true;
35265
35628
  logOnce(
35266
35629
  `${location.key}\0store-linked-path`,
35267
- () => log18.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
35630
+ () => log19.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
35268
35631
  accountStore: stateAnchor,
35269
35632
  stateFolder: location.stateHomeDir
35270
35633
  })
35271
35634
  );
35272
35635
  return false;
35273
35636
  }
35274
- async function storeFenceOpen(location, options, log18) {
35637
+ async function storeFenceOpen(location, options, log19) {
35275
35638
  const gate = await (options.storeFence ?? defaultStoreFence(options.version))();
35276
35639
  if (gate.open) return true;
35277
35640
  logOnce(
35278
35641
  `${location.key}\0store-version-fence`,
35279
- () => log18.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
35642
+ () => log19.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
35280
35643
  configDir: location.configDir,
35281
35644
  blockers: gate.blockers
35282
35645
  })
@@ -35303,7 +35666,7 @@ async function storeArtefacts(anchor) {
35303
35666
  (name) => name === store || name.startsWith(`${pool}.store.`) || name.startsWith(pool) && name.endsWith(".tmp")
35304
35667
  ).length;
35305
35668
  }
35306
- async function abandonUnpublishedStore(location, stateAnchor, log18) {
35669
+ async function abandonUnpublishedStore(location, stateAnchor, log19) {
35307
35670
  const store = await loadCommonAuthStoreModules();
35308
35671
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
35309
35672
  if (binding.status === "bound") return false;
@@ -35314,7 +35677,7 @@ async function abandonUnpublishedStore(location, stateAnchor, log18) {
35314
35677
  });
35315
35678
  await unlink11(accountStorePointerPath(stateAnchor)).catch(() => {
35316
35679
  });
35317
- log18.info(
35680
+ log19.info(
35318
35681
  "antigravity-auth set an unfinished account store aside before starting its move again",
35319
35682
  { configDir: location.configDir, archived }
35320
35683
  );
@@ -35336,9 +35699,9 @@ async function runStoreMove(input2) {
35336
35699
  return { status: "pending", reason: outcome.reason };
35337
35700
  return { status: "cancelled" };
35338
35701
  }
35339
- async function moveStore(location, options, source, target, back, log18, forwarded) {
35340
- const keepConfig = () => recordAnchor(location, options, "config", log18);
35341
- if (!await storeFenceOpen(location, options, log18)) return keepConfig();
35702
+ async function moveStore(location, options, source, target, back, log19, forwarded) {
35703
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
35704
+ if (!await storeFenceOpen(location, options, log19)) return keepConfig();
35342
35705
  try {
35343
35706
  const result = await (options.relocate ?? runStoreMove)({
35344
35707
  source,
@@ -35348,7 +35711,7 @@ async function moveStore(location, options, source, target, back, log18, forward
35348
35711
  if (result.status !== "completed") {
35349
35712
  logOnce(
35350
35713
  `${location.key}\0store-move-unfinished`,
35351
- () => log18.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
35714
+ () => log19.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
35352
35715
  configDir: location.configDir,
35353
35716
  reason: result.status === "pending" ? result.reason : result.status
35354
35717
  })
@@ -35356,14 +35719,14 @@ async function moveStore(location, options, source, target, back, log18, forward
35356
35719
  return forwarded ? "state-home" : keepConfig();
35357
35720
  }
35358
35721
  showLog(
35359
- log18,
35722
+ log19,
35360
35723
  "antigravity-auth moved the account store out of OpenCode's config folder",
35361
35724
  { from: source, to: target, generation: result.id }
35362
35725
  );
35363
35726
  } catch (error) {
35364
35727
  logOnce(
35365
35728
  `${location.key}\0store-move-failed`,
35366
- () => log18.warn(
35729
+ () => log19.warn(
35367
35730
  "antigravity-auth's account store stays in OpenCode's config folder: moving it failed; the move is tried again at the next start",
35368
35731
  {
35369
35732
  configDir: location.configDir,
@@ -35374,9 +35737,9 @@ async function moveStore(location, options, source, target, back, log18, forward
35374
35737
  );
35375
35738
  return forwarded ? "state-home" : keepConfig();
35376
35739
  }
35377
- return recordAnchor(location, options, "state-home", log18);
35740
+ return recordAnchor(location, options, "state-home", log19);
35378
35741
  }
35379
- async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log18) {
35742
+ async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log19) {
35380
35743
  const store = await loadCommonAuthStoreModules();
35381
35744
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
35382
35745
  if (binding.status === "bound") return;
@@ -35387,13 +35750,13 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
35387
35750
  configAnchor,
35388
35751
  stateAnchor,
35389
35752
  false,
35390
- log18,
35753
+ log19,
35391
35754
  true
35392
35755
  );
35393
35756
  } catch (error) {
35394
35757
  logOnce(
35395
35758
  `${location.key}\0store-resume-failed`,
35396
- () => log18.warn(
35759
+ () => log19.warn(
35397
35760
  "antigravity-auth's account store is still moving; it could not be finished at this start",
35398
35761
  {
35399
35762
  configDir: location.configDir,
@@ -35404,9 +35767,9 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
35404
35767
  );
35405
35768
  }
35406
35769
  }
35407
- async function initializeStore(location, options, stateAnchor, log18) {
35408
- const keepConfig = () => recordAnchor(location, options, "config", log18);
35409
- if (!await storeFenceOpen(location, options, log18)) return keepConfig();
35770
+ async function initializeStore(location, options, stateAnchor, log19) {
35771
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
35772
+ if (!await storeFenceOpen(location, options, log19)) return keepConfig();
35410
35773
  try {
35411
35774
  const store = await loadCommonAuthStoreModules();
35412
35775
  const created = await initializeFreshAccountStore(store, {
@@ -35419,7 +35782,7 @@ async function initializeStore(location, options, stateAnchor, log18) {
35419
35782
  } catch (error) {
35420
35783
  logOnce(
35421
35784
  `${location.key}\0store-init-failed`,
35422
- () => log18.warn(
35785
+ () => log19.warn(
35423
35786
  "antigravity-auth's account store stays in OpenCode's config folder: creating it in its state folder failed; it is tried again at the next start",
35424
35787
  {
35425
35788
  configDir: location.configDir,
@@ -35431,13 +35794,13 @@ async function initializeStore(location, options, stateAnchor, log18) {
35431
35794
  return keepConfig();
35432
35795
  }
35433
35796
  showLog(
35434
- log18,
35797
+ log19,
35435
35798
  "antigravity-auth created its account store in its state folder",
35436
35799
  {
35437
35800
  accountStore: stateAnchor
35438
35801
  }
35439
35802
  );
35440
- return recordAnchor(location, options, "state-home", log18);
35803
+ return recordAnchor(location, options, "state-home", log19);
35441
35804
  }
35442
35805
  async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacyAccountFile(runtimeLayoutLocation().configDir)) {
35443
35806
  const forward = {
@@ -35452,10 +35815,10 @@ async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacy
35452
35815
  durability: "file-only-on-windows"
35453
35816
  });
35454
35817
  }
35455
- function logDeferral(location, blockers, log18) {
35818
+ function logDeferral(location, blockers, log19) {
35456
35819
  logOnce(
35457
35820
  `${location.key}\0deferred`,
35458
- () => log18.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
35821
+ () => log19.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
35459
35822
  configDir: location.configDir,
35460
35823
  blockers
35461
35824
  })
@@ -35613,13 +35976,13 @@ async function finishOldFiles(location, files, markerPath, marker, layoutLock, i
35613
35976
  if (done) await removeOldVaultFolder(files, layoutLock, input2.steps);
35614
35977
  }
35615
35978
  }
35616
- async function removeLeftoverManifest(location, layoutLock, steps, log18) {
35979
+ async function removeLeftoverManifest(location, layoutLock, steps, log19) {
35617
35980
  try {
35618
35981
  await removeManifestOwned(location.stateHomeDir, layoutLock, steps);
35619
35982
  } catch (error) {
35620
35983
  logOnce(
35621
35984
  `${location.key}\0manifest`,
35622
- () => log18.warn(
35985
+ () => log19.warn(
35623
35986
  `antigravity-auth could not remove ${RUNTIME_LAYOUT_MANIFEST_FILE} from its state folder; it tries again at the next start`,
35624
35987
  { stateDir: location.stateHomeDir, errorClass: errorClass(error) }
35625
35988
  )
@@ -35639,7 +36002,7 @@ async function removeOldVaultFolder(files, layoutLock, steps) {
35639
36002
  } catch {
35640
36003
  }
35641
36004
  }
35642
- async function removeOldSignatureCache(location, path5, layoutLock, steps, log18) {
36005
+ async function removeOldSignatureCache(location, path5, layoutLock, steps, log19) {
35643
36006
  try {
35644
36007
  if (!await exists2(path5)) return;
35645
36008
  await beforeRemove(path5, layoutLock, steps);
@@ -35648,7 +36011,7 @@ async function removeOldSignatureCache(location, path5, layoutLock, steps, log18
35648
36011
  if (error?.code === "ENOENT") return;
35649
36012
  logOnce(
35650
36013
  `${location.key}\0signature-cache`,
35651
- () => log18.warn(
36014
+ () => log19.warn(
35652
36015
  "antigravity-auth could not remove its old signature cache from OpenCode's config folder; it is no longer used and can be deleted",
35653
36016
  { path: path5, errorClass: errorClass(error) }
35654
36017
  )
@@ -35659,7 +36022,7 @@ async function beforeRemove(path5, layoutLock, steps) {
35659
36022
  await steps?.beforeRemove?.(path5);
35660
36023
  await layoutLock.assertOwned();
35661
36024
  }
35662
- async function takeDataLocks(files, log18) {
36025
+ async function takeDataLocks(files, log19) {
35663
36026
  const locks = [];
35664
36027
  try {
35665
36028
  if (await exists2(files.vault.old))
@@ -35669,7 +36032,7 @@ async function takeDataLocks(files, log18) {
35669
36032
  lock.name,
35670
36033
  join18(files.vault.old, lock.file),
35671
36034
  lock.waitMs,
35672
- log18
36035
+ log19
35673
36036
  )
35674
36037
  );
35675
36038
  return locks;
@@ -36020,7 +36383,7 @@ async function ensureOwnerOnlyDir(path5) {
36020
36383
  await mkdir13(path5, { recursive: true, mode: 448 });
36021
36384
  await chmod5(path5, 448);
36022
36385
  }
36023
- async function takeLock(name, path5, waitMs, log18) {
36386
+ async function takeLock(name, path5, waitMs, log19) {
36024
36387
  const fs7 = await loadCommonAuthFs();
36025
36388
  const started = performance.now();
36026
36389
  let announced = false;
@@ -36045,7 +36408,7 @@ async function takeLock(name, path5, waitMs, log18) {
36045
36408
  );
36046
36409
  if (!announced && waited >= LOCK_WAIT_NOTICE_MS) {
36047
36410
  announced = true;
36048
- log18.info(
36411
+ log19.info(
36049
36412
  `antigravity-auth is waiting up to ${Math.round(waitMs / 1e3)} s for the ${name} lock at ${path5}.${lockHolderText(name)}`,
36050
36413
  { lock: name, path: path5 }
36051
36414
  );
@@ -36156,7 +36519,7 @@ var init_runtime_layout = __esm({
36156
36519
  init_dist();
36157
36520
  init_runtime_layout();
36158
36521
  import { createHash as createHash24, randomUUID as randomUUID25 } from "node:crypto";
36159
- import { join as join46, resolve as resolve32 } from "node:path";
36522
+ import { join as join45, resolve as resolve33 } from "node:path";
36160
36523
 
36161
36524
  // src/cli.ts
36162
36525
  init_dist();
@@ -36400,9 +36763,9 @@ init_dist();
36400
36763
  init_dist();
36401
36764
 
36402
36765
  // src/sidebar-state.ts
36766
+ import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, statSync as statSync5 } from "node:fs";
36403
36767
  init_atomic_write();
36404
36768
  init_file_lock();
36405
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
36406
36769
  import { homedir as homedir6 } from "node:os";
36407
36770
  import { dirname as dirname19, join as join19 } from "node:path";
36408
36771
 
@@ -36473,6 +36836,9 @@ function readSidebarState(path5 = getSidebarStateFile()) {
36473
36836
  } catch {
36474
36837
  return { ...DEFAULT_SIDEBAR_STATE };
36475
36838
  }
36839
+ return parseSidebarState(raw);
36840
+ }
36841
+ function parseSidebarState(raw) {
36476
36842
  let parsed;
36477
36843
  try {
36478
36844
  parsed = JSON.parse(raw);
@@ -36813,7 +37179,7 @@ function drainSidebarWrites() {
36813
37179
  return sidebarWriteChain;
36814
37180
  }
36815
37181
  async function sleep3(ms) {
36816
- await new Promise((resolve33) => setTimeout(resolve33, ms));
37182
+ await new Promise((resolve34) => setTimeout(resolve34, ms));
36817
37183
  }
36818
37184
  async function acquireSidebarLockWithRetry(stateFile) {
36819
37185
  const start = Date.now();
@@ -37353,7 +37719,8 @@ function withSidebarPushAfterRefresh(manager, push) {
37353
37719
  refreshOptions
37354
37720
  );
37355
37721
  const lastAccount = accounts[accounts.length - 1];
37356
- if (shouldPush && lastAccount) await pushAfterRefresh(lastAccount);
37722
+ if (shouldPush && refreshOptions.publishSidebar !== false && lastAccount)
37723
+ await pushAfterRefresh(lastAccount);
37357
37724
  return results;
37358
37725
  })()
37359
37726
  );
@@ -37388,10 +37755,29 @@ async function checkAccountsQuotaStandalone(accounts, options) {
37388
37755
  }
37389
37756
  }));
37390
37757
  }
37391
- return checkAccountsQuotaWith(
37758
+ const refused2 = new AbortController();
37759
+ const admit2 = options.assertAdmission;
37760
+ const assertAdmission = admit2 && (async () => {
37761
+ refused2.signal.throwIfAborted();
37762
+ try {
37763
+ await admit2();
37764
+ } catch (error) {
37765
+ refused2.abort(error);
37766
+ throw error;
37767
+ }
37768
+ refused2.signal.throwIfAborted();
37769
+ });
37770
+ const results = await checkAccountsQuotaWith(
37392
37771
  accounts,
37393
- makeFetchAccountQuota(void 0, ANTIGRAVITY_PROVIDER_ID)
37772
+ makeFetchAccountQuota(
37773
+ void 0,
37774
+ ANTIGRAVITY_PROVIDER_ID,
37775
+ void 0,
37776
+ assertAdmission
37777
+ )
37394
37778
  );
37779
+ refused2.signal.throwIfAborted();
37780
+ return results;
37395
37781
  }
37396
37782
  async function pushSidebarQuotaSnapshot(getAccounts, backoffUntil = 0, getActiveIndexByFamily, options = {}) {
37397
37783
  const accounts = getAccounts();
@@ -37665,14 +38051,14 @@ var LocalQuotaGrantStaleError = class extends Error {
37665
38051
  name = "LocalQuotaGrantStaleError";
37666
38052
  };
37667
38053
  function untilQuotaAborted(pending, signal) {
37668
- return new Promise((resolve33, reject) => {
38054
+ return new Promise((resolve34, reject) => {
37669
38055
  const abort = () => reject(signal.reason);
37670
38056
  if (signal.aborted) abort();
37671
38057
  else signal.addEventListener("abort", abort, { once: true });
37672
38058
  void pending.then(
37673
38059
  (value) => {
37674
38060
  signal.removeEventListener("abort", abort);
37675
- resolve33(value);
38061
+ resolve34(value);
37676
38062
  },
37677
38063
  (error) => {
37678
38064
  signal.removeEventListener("abort", abort);
@@ -37770,7 +38156,7 @@ function createAuthorizedFetchAccountQuota(options) {
37770
38156
  }
37771
38157
  };
37772
38158
  }
37773
- function makeFetchAccountQuota(client, providerId, fetchVia) {
38159
+ function makeFetchAccountQuota(client, providerId, fetchVia, assertAdmission) {
37774
38160
  return async (account, signal, purpose = "required") => {
37775
38161
  const index = 0;
37776
38162
  const disabled = account.enabled === false;
@@ -37852,6 +38238,8 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37852
38238
  }
37853
38239
  try {
37854
38240
  if (accessTokenExpired(auth)) {
38241
+ if (assertAdmission) await assertAdmission();
38242
+ signal.throwIfAborted();
37855
38243
  const refreshed = await refreshAccessToken(
37856
38244
  auth,
37857
38245
  client,
@@ -37865,7 +38253,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37865
38253
  }
37866
38254
  auth = refreshed;
37867
38255
  }
37868
- const projectContext = await ensureProjectContext(auth);
38256
+ const projectContext = await ensureProjectContext(auth, assertAdmission);
37869
38257
  auth = projectContext.auth;
37870
38258
  const updatedAccount = applyAccountUpdates(
37871
38259
  account,
@@ -37880,11 +38268,20 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37880
38268
  let fellBackToLegacy = false;
37881
38269
  const authParts = parseRefreshParts(auth.refresh);
37882
38270
  const managedProjectId = authParts.managedProjectId ?? account.managedProjectId;
38271
+ const guarded = assertAdmission ? async (url, init, extra) => {
38272
+ await assertAdmission();
38273
+ signal.throwIfAborted();
38274
+ return fetchWithActiveTimeout(
38275
+ url,
38276
+ { ...init, signal },
38277
+ { timeoutMs: extra.timeoutMs }
38278
+ );
38279
+ } : fetchVia;
37883
38280
  const payloads = await fetchQuotaPayloads({
37884
38281
  accessToken: auth.access ?? "",
37885
38282
  managedProjectId,
37886
38283
  projectId: projectContext.effectiveProjectId,
37887
- fetchVia,
38284
+ fetchVia: guarded,
37888
38285
  logger: log8
37889
38286
  });
37890
38287
  quotaResult = payloads.quota;
@@ -38129,12 +38526,13 @@ function createStoreQuotaService(options) {
38129
38526
  if (options.mayRun && !await options.mayRun())
38130
38527
  return { status: "discarded", result };
38131
38528
  const held2 = target.rowRef === void 0 ? void 0 : heldAccount(manager, target.rowRef);
38132
- if (held2 === void 0) return { status: "discarded", result };
38133
- manager.updateQuotaCache(
38529
+ if (held2 === void 0 || result.checkedAt === void 0 || !manager.updateQuotaCache(
38134
38530
  held2.index,
38135
38531
  result.quota.groups,
38136
- held2.parts.refreshToken
38137
- );
38532
+ held2.parts.refreshToken,
38533
+ result.checkedAt
38534
+ ))
38535
+ return { status: "discarded", result };
38138
38536
  return {
38139
38537
  status: "recorded",
38140
38538
  result,
@@ -38293,12 +38691,12 @@ async function startOAuthListener({
38293
38691
  let resolveCallback;
38294
38692
  let rejectCallback;
38295
38693
  let timeoutHandle;
38296
- const callbackPromise = new Promise((resolve33, reject) => {
38694
+ const callbackPromise = new Promise((resolve34, reject) => {
38297
38695
  resolveCallback = (url) => {
38298
38696
  if (settled) return;
38299
38697
  settled = true;
38300
38698
  if (timeoutHandle) clearTimeout(timeoutHandle);
38301
- resolve33(url);
38699
+ resolve34(url);
38302
38700
  };
38303
38701
  rejectCallback = (error) => {
38304
38702
  if (settled) return;
@@ -38457,7 +38855,7 @@ async function startOAuthListener({
38457
38855
  });
38458
38856
  });
38459
38857
  const bindAddress = getBindAddress();
38460
- await new Promise((resolve33, reject) => {
38858
+ await new Promise((resolve34, reject) => {
38461
38859
  const handleError = (error) => {
38462
38860
  server.off("error", handleError);
38463
38861
  if (error.code === "EADDRINUSE") {
@@ -38473,7 +38871,7 @@ async function startOAuthListener({
38473
38871
  server.once("error", handleError);
38474
38872
  server.listen(port, bindAddress, () => {
38475
38873
  server.off("error", handleError);
38476
- resolve33();
38874
+ resolve34();
38477
38875
  });
38478
38876
  });
38479
38877
  server.on("error", (error) => {
@@ -38481,7 +38879,7 @@ async function startOAuthListener({
38481
38879
  });
38482
38880
  return {
38483
38881
  waitForCallback: () => callbackPromise,
38484
- close: () => new Promise((resolve33, reject) => {
38882
+ close: () => new Promise((resolve34, reject) => {
38485
38883
  server.close((error) => {
38486
38884
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
38487
38885
  reject(error);
@@ -38490,7 +38888,7 @@ async function startOAuthListener({
38490
38888
  if (!settled) {
38491
38889
  rejectCallback(new Error("OAuth listener closed before callback"));
38492
38890
  }
38493
- resolve33();
38891
+ resolve34();
38494
38892
  });
38495
38893
  })
38496
38894
  };
@@ -38682,7 +39080,7 @@ async function select2(terminal, items, options) {
38682
39080
  writeLine("");
38683
39081
  renderedLines = lines;
38684
39082
  };
38685
- return new Promise((resolve33) => {
39083
+ return new Promise((resolve34) => {
38686
39084
  const wasRaw = stdin.isRaw ?? false;
38687
39085
  const cleanup2 = () => {
38688
39086
  if (cleaned)
@@ -38702,7 +39100,7 @@ async function select2(terminal, items, options) {
38702
39100
  };
38703
39101
  const finish = (value) => {
38704
39102
  cleanup2();
38705
- resolve33(value);
39103
+ resolve34(value);
38706
39104
  };
38707
39105
  const onSignal = () => finish(null);
38708
39106
  const onKey = (data) => {
@@ -38742,7 +39140,7 @@ async function select2(terminal, items, options) {
38742
39140
  stdin.setRawMode(true);
38743
39141
  } catch {
38744
39142
  cleanup2();
38745
- resolve33(null);
39143
+ resolve34(null);
38746
39144
  return;
38747
39145
  }
38748
39146
  stdin.resume();
@@ -39054,8 +39452,8 @@ async function acquireRefreshFileLockWithClock2(options) {
39054
39452
  let releaseConfirmed = false;
39055
39453
  let loss;
39056
39454
  let resolveLoss;
39057
- const lostPromise = new Promise((resolve33) => {
39058
- resolveLoss = resolve33;
39455
+ const lostPromise = new Promise((resolve34) => {
39456
+ resolveLoss = resolve34;
39059
39457
  });
39060
39458
  function notifyTimerStep(event) {
39061
39459
  try {
@@ -39219,7 +39617,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39219
39617
  }
39220
39618
  }
39221
39619
  async function backoff() {
39222
- await new Promise((resolve33) => setTimeout(resolve33, Math.floor(Math.random() * 4)));
39620
+ await new Promise((resolve34) => setTimeout(resolve34, Math.floor(Math.random() * 4)));
39223
39621
  }
39224
39622
  async function readLockState(notifyReady = true) {
39225
39623
  if (notifyReady && options.onStep)
@@ -39312,7 +39710,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39312
39710
  const remainingMs = deadline - performance.now();
39313
39711
  if (remainingMs <= 0)
39314
39712
  throw original;
39315
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
39713
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
39316
39714
  if (performance.now() >= deadline)
39317
39715
  throw original;
39318
39716
  delayMs = Math.min(delayMs * 2, 50);
@@ -39815,7 +40213,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39815
40213
  const remainingMs = deadline - performance.now();
39816
40214
  if (remainingMs <= 0)
39817
40215
  break;
39818
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
40216
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
39819
40217
  if (windowsPrivateFiles2 && performance.now() >= deadline)
39820
40218
  break;
39821
40219
  delayMs = Math.min(delayMs * 2, 50);
@@ -40696,7 +41094,7 @@ var ByteTail = class {
40696
41094
  };
40697
41095
  var defaultCommandRunner = {
40698
41096
  run(file, args, options = {}) {
40699
- return new Promise((resolve33) => {
41097
+ return new Promise((resolve34) => {
40700
41098
  const started = performance.now();
40701
41099
  const timeoutMs = options.timeoutMs ?? 15e3;
40702
41100
  const stderr = new ByteTail();
@@ -40714,7 +41112,7 @@ var defaultCommandRunner = {
40714
41112
  stdio: ["ignore", "pipe", "pipe"]
40715
41113
  });
40716
41114
  } catch {
40717
- resolve33({
41115
+ resolve34({
40718
41116
  exitCode: 1,
40719
41117
  stdout: "",
40720
41118
  stderr: "",
@@ -40749,7 +41147,7 @@ var defaultCommandRunner = {
40749
41147
  settled = true;
40750
41148
  if (timer)
40751
41149
  clearTimeout(timer);
40752
- resolve33({
41150
+ resolve34({
40753
41151
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
40754
41152
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
40755
41153
  stderr: stderr.toString(),
@@ -40905,7 +41303,7 @@ function recordSetupEnrollment(failure2, enrollment) {
40905
41303
  }
40906
41304
 
40907
41305
  // src/common-auth-embedded/setup/detect.js
40908
- import { accessSync, constants as constants3, existsSync as existsSync6, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync5 } from "node:fs";
41306
+ import { accessSync, constants as constants3, existsSync as existsSync6, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync6 } from "node:fs";
40909
41307
  import { mkdtemp, rm as rm7 } from "node:fs/promises";
40910
41308
  import { tmpdir as tmpdir3 } from "node:os";
40911
41309
  import { join as join22 } from "node:path";
@@ -40945,7 +41343,7 @@ function setupPaths(io = {}) {
40945
41343
  // src/common-auth-embedded/setup/detect.js
40946
41344
  function stat15(path5, kind) {
40947
41345
  try {
40948
- return statSync5(path5)[kind]();
41346
+ return statSync6(path5)[kind]();
40949
41347
  } catch {
40950
41348
  return false;
40951
41349
  }
@@ -41145,13 +41543,15 @@ import { setTimeout as delay2 } from "node:timers/promises";
41145
41543
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexkit/claustrum-client";
41146
41544
 
41147
41545
  // src/common-auth-embedded/setup/process-fence.js
41148
- import { statSync as statSync6 } from "node:fs";
41546
+ init_logger3();
41547
+ import { statSync as statSync7 } from "node:fs";
41149
41548
  import { win32 as win323 } from "node:path";
41150
41549
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
41550
+ var log9 = createLogger3("setup-process-fence");
41151
41551
  var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
41152
41552
  function isFile(file) {
41153
41553
  try {
41154
- return statSync6(file).isFile();
41554
+ return statSync7(file).isFile();
41155
41555
  } catch {
41156
41556
  return false;
41157
41557
  }
@@ -41307,14 +41707,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41307
41707
  options.onStep?.({ ...inspection });
41308
41708
  }
41309
41709
  };
41310
- const inspectCim = (args) => {
41710
+ const inspectCim = async (args) => {
41311
41711
  const pwsh = win323.resolve(windowsEnv(env3, "ProgramFiles") ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
41312
41712
  const program = (options.isFile ?? isFile)(pwsh) ? "pwsh" : "powershell";
41313
41713
  const arm64 = (windowsEnv(env3, "PROCESSOR_ARCHITEW6432") ?? windowsEnv(env3, "PROCESSOR_ARCHITECTURE"))?.toUpperCase() === "ARM64";
41314
41714
  const slow = program === "powershell" && arm64;
41315
41715
  if (slow)
41316
41716
  options.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");
41317
- return inspect("CIM", program === "pwsh" ? pwsh : win323.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
41717
+ const file = program === "pwsh" ? pwsh : win323.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe");
41718
+ const timeoutMs = slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS;
41719
+ const started = performance.now();
41720
+ const result = await inspect("CIM", file, args, timeoutMs, program);
41721
+ const remaining = Math.floor(timeoutMs - (performance.now() - started));
41722
+ if ((result.exitCode === 3221225477 || result.exitCode === -1073741819) && !result.timedOut && !result.signal && !result.spawnError && remaining > 0) {
41723
+ log9.warn("Windows process query crashed with an access violation; retrying once");
41724
+ return inspect("CIM", file, args, remaining, program);
41725
+ }
41726
+ return result;
41318
41727
  };
41319
41728
  try {
41320
41729
  if (windows2 && options.hostImagesOnly) {
@@ -42312,19 +42721,31 @@ async function readNativeAuth(path5) {
42312
42721
  throw error;
42313
42722
  }
42314
42723
  }
42724
+ async function readOpenCodeAuthority(legacyPath) {
42725
+ try {
42726
+ const claustrum = await loadCommonAuthClaustrum();
42727
+ if (claustrum.hasVaultHost()) return "host";
42728
+ return await vaultAuthority2(
42729
+ claustrum.hostEnrollmentPaths({
42730
+ stateDir: openCodeVaultDir(
42731
+ legacyPath ?? resolve23(accountFileForVault())
42732
+ ),
42733
+ host: "opencode"
42734
+ }),
42735
+ OPENCODE_VAULT_ENROLLMENT_NAME,
42736
+ claustrum
42737
+ );
42738
+ } catch {
42739
+ return "unreadable";
42740
+ }
42741
+ }
42315
42742
  async function assertLocalOpenCodeLogin(legacyPath, generation) {
42316
- const claustrum = await loadCommonAuthClaustrum();
42317
- if (await claustrum.vaultAuthority(
42318
- claustrum.hostEnrollmentPaths({
42319
- stateDir: openCodeVaultDir(legacyPath),
42320
- host: "opencode"
42321
- }),
42322
- OPENCODE_VAULT_ENROLLMENT_NAME
42323
- ) !== "local")
42743
+ if (await readOpenCodeAuthority(legacyPath) !== "local")
42324
42744
  throw new Error(
42325
42745
  "Vault enrollment excludes local sign-in. Resolve vault access before choosing local setup."
42326
42746
  );
42327
42747
  if (generation === "2") return;
42748
+ const claustrum = await loadCommonAuthClaustrum();
42328
42749
  claustrum.assertHostSlotMatchesMode({
42329
42750
  mode: "local",
42330
42751
  auth: (await readNativeAuth(nativeOpenCodeAuthPath()))[OPENCODE_VAULT_PROVIDER],
@@ -42940,6 +43361,16 @@ async function runCli(argv, deps) {
42940
43361
  return 0;
42941
43362
  }
42942
43363
  try {
43364
+ const assertLocalAccounts = async () => {
43365
+ const authority = await (deps.readAuthority ?? readOpenCodeAuthority)();
43366
+ if (authority === "local") return;
43367
+ const source2 = authority === "vault" ? "Accounts are served by the vault, not this computer's local sign-ins." : authority === "host" ? "Accounts are served by Thalamus, not this computer's local sign-ins." : "Account authority could not be read, so this computer's local sign-ins were not used.";
43368
+ throw new Error(
43369
+ `${source2} Use the /antigravity menu in OpenCode to see them and their quota.`
43370
+ );
43371
+ };
43372
+ if (parsed.value.command === "list" || parsed.value.command === "quota")
43373
+ await assertLocalAccounts();
42943
43374
  if (parsed.value.command !== "setup") {
42944
43375
  if (parsed.value.command === "login") await deps.prepareVaultFolder?.();
42945
43376
  await deps.processHeartbeat?.();
@@ -43044,7 +43475,8 @@ async function runCli(argv, deps) {
43044
43475
  return 0;
43045
43476
  }
43046
43477
  const results = await deps.getQuota(storage?.accounts ?? [], {
43047
- refresh: parsed.value.refresh
43478
+ refresh: parsed.value.refresh,
43479
+ ...parsed.value.refresh ? { assertAdmission: assertLocalAccounts } : {}
43048
43480
  });
43049
43481
  deps.stdout.write(
43050
43482
  parsed.value.json ? `${JSON.stringify(quotaSummary(results))}
@@ -43887,8 +44319,8 @@ function isUsablePortFileEntry(value, name) {
43887
44319
  const { pid, port, token } = value;
43888
44320
  return isProbeablePid(pid) && filenamePid(name) === pid && typeof port === "number" && Number.isInteger(port) && port >= 1 && port <= 65535 && typeof token === "string" && token.length > 0;
43889
44321
  }
43890
- async function removeCorruptPortFile(portFile, log18) {
43891
- log18?.debug("rpc corrupt port file", { pid: process.pid, portFile });
44322
+ async function removeCorruptPortFile(portFile, log19) {
44323
+ log19?.debug("rpc corrupt port file", { pid: process.pid, portFile });
43892
44324
  await unlink15(portFile).catch(() => {
43893
44325
  });
43894
44326
  }
@@ -43938,11 +44370,11 @@ async function writePortFile(dir, entry, options = {}) {
43938
44370
  } catch (error) {
43939
44371
  if (error.code !== "ENOENT" || attempt === 5)
43940
44372
  throw error;
43941
- await new Promise((resolve33) => setTimeout(resolve33, 25));
44373
+ await new Promise((resolve34) => setTimeout(resolve34, 25));
43942
44374
  }
43943
44375
  }
43944
44376
  }
43945
- async function sweepRpcState(root, activeDir, isManagedDir, log18, options = {}) {
44377
+ async function sweepRpcState(root, activeDir, isManagedDir, log19, options = {}) {
43946
44378
  const cutoff = staleBefore(options);
43947
44379
  let projectDirs;
43948
44380
  try {
@@ -43958,14 +44390,14 @@ async function sweepRpcState(root, activeDir, isManagedDir, log18, options = {})
43958
44390
  continue;
43959
44391
  }
43960
44392
  const dir = join30(root, projectDir.name);
43961
- if (!await sweepRpcDirectory(dir, log18, options, cutoff))
44393
+ if (!await sweepRpcDirectory(dir, log19, options, cutoff))
43962
44394
  continue;
43963
44395
  if (resolve26(dir) !== active2)
43964
44396
  await rmdir3(dir).catch(() => {
43965
44397
  });
43966
44398
  }
43967
44399
  }
43968
- async function sweepRpcDirectory(dir, log18, options = {}, cutoff = staleBefore(options)) {
44400
+ async function sweepRpcDirectory(dir, log19, options = {}, cutoff = staleBefore(options)) {
43969
44401
  let names;
43970
44402
  try {
43971
44403
  names = await readdir6(dir);
@@ -43993,11 +44425,11 @@ async function sweepRpcDirectory(dir, log18, options = {}, cutoff = staleBefore(
43993
44425
  try {
43994
44426
  parsed = JSON.parse(raw);
43995
44427
  } catch {
43996
- await removeCorruptPortFile(portFile, log18);
44428
+ await removeCorruptPortFile(portFile, log19);
43997
44429
  continue;
43998
44430
  }
43999
44431
  if (!isUsablePortFileEntry(parsed, name)) {
44000
- await removeCorruptPortFile(portFile, log18);
44432
+ await removeCorruptPortFile(portFile, log19);
44001
44433
  continue;
44002
44434
  }
44003
44435
  const entry = parsed;
@@ -44028,7 +44460,7 @@ var key = /* @__PURE__ */ Symbol.for("common-auth.rpc.startup-sweep");
44028
44460
  globals[key] ??= {};
44029
44461
  var state = globals[key];
44030
44462
  var now = Date.now;
44031
- async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log18) {
44463
+ async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log19) {
44032
44464
  const time = now();
44033
44465
  if (state.lastSweepAt !== void 0 && time - state.lastSweepAt < 6e4) {
44034
44466
  const active2 = resolve27(activeDir);
@@ -44037,11 +44469,11 @@ async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log18) {
44037
44469
  throw error;
44038
44470
  return void 0;
44039
44471
  }))?.isDirectory())
44040
- await sweepRpcDirectory(active2, log18);
44472
+ await sweepRpcDirectory(active2, log19);
44041
44473
  return;
44042
44474
  }
44043
44475
  state.lastSweepAt = time;
44044
- await sweepRpcState(root, activeDir, isManagedDir, log18);
44476
+ await sweepRpcState(root, activeDir, isManagedDir, log19);
44045
44477
  }
44046
44478
 
44047
44479
  // src/common-auth-embedded/rpc/rpc-server.js
@@ -44064,7 +44496,7 @@ var BodyTooLargeError = class extends Error {
44064
44496
  }
44065
44497
  };
44066
44498
  function readBody(req) {
44067
- return new Promise((resolve33, reject) => {
44499
+ return new Promise((resolve34, reject) => {
44068
44500
  const tooLarge = (declaredOversize = false) => {
44069
44501
  req.removeAllListeners("data");
44070
44502
  req.on("data", () => {
@@ -44087,7 +44519,7 @@ function readBody(req) {
44087
44519
  }
44088
44520
  chunks.push(chunk);
44089
44521
  });
44090
- req.on("end", () => resolve33(Buffer.concat(chunks).toString("utf8")));
44522
+ req.on("end", () => resolve34(Buffer.concat(chunks).toString("utf8")));
44091
44523
  req.on("error", reject);
44092
44524
  });
44093
44525
  }
@@ -44117,7 +44549,7 @@ function tokenOk(header, token) {
44117
44549
  async function startRpcServer(options) {
44118
44550
  if (typeof options.drain === "function" === (typeof options.drainAsync === "function"))
44119
44551
  throw new TypeError("exactly one of drain or drainAsync must be provided");
44120
- const log18 = options.log ?? { warn() {
44552
+ const log19 = options.log ?? { warn() {
44121
44553
  }, debug() {
44122
44554
  } };
44123
44555
  const token = randomBytes6(32).toString("hex");
@@ -44218,7 +44650,7 @@ async function startRpcServer(options) {
44218
44650
  return json(400, { error: "session required" });
44219
44651
  if (sessionId === void 0 && !warnedMissingNotificationSession) {
44220
44652
  warnedMissingNotificationSession = true;
44221
- log18.warn("rpc notification drain missing session id", {
44653
+ log19.warn("rpc notification drain missing session id", {
44222
44654
  pid: process.pid
44223
44655
  });
44224
44656
  }
@@ -44227,7 +44659,7 @@ async function startRpcServer(options) {
44227
44659
  try {
44228
44660
  messages = await options.drainAsync(lastReceivedId, sessionId);
44229
44661
  } catch (error) {
44230
- log18.warn("rpc notification drain failed", {
44662
+ log19.warn("rpc notification drain failed", {
44231
44663
  pid: process.pid,
44232
44664
  error: error instanceof Error ? error.message : String(error)
44233
44665
  });
@@ -44246,32 +44678,32 @@ async function startRpcServer(options) {
44246
44678
  return json(404, { error: "unknown method" });
44247
44679
  } catch (error) {
44248
44680
  if (error instanceof RpcRequestError) {
44249
- log18.debug("rpc request refused", {
44681
+ log19.debug("rpc request refused", {
44250
44682
  pid: process.pid,
44251
44683
  status: error.status
44252
44684
  });
44253
44685
  return json(error.status, { error: error.message });
44254
44686
  }
44255
44687
  if (error instanceof ApplyDeadlineError) {
44256
- log18.warn("rpc apply deadline exceeded", {
44688
+ log19.warn("rpc apply deadline exceeded", {
44257
44689
  pid: process.pid,
44258
44690
  deadlineMs: options.applyDeadlineMs
44259
44691
  });
44260
44692
  return json(504, { error: "handler deadline exceeded" });
44261
44693
  }
44262
- log18.warn("rpc request failed", {
44694
+ log19.warn("rpc request failed", {
44263
44695
  pid: process.pid,
44264
44696
  error: error instanceof Error ? error.message : String(error)
44265
44697
  });
44266
44698
  json(500, { error: "internal error" });
44267
44699
  }
44268
44700
  }
44269
- const port = await new Promise((resolve33, reject) => {
44701
+ const port = await new Promise((resolve34, reject) => {
44270
44702
  server.on("error", reject);
44271
44703
  server.listen(0, "127.0.0.1", () => {
44272
44704
  const addr = server.address();
44273
44705
  if (addr && typeof addr === "object")
44274
- resolve33(addr.port);
44706
+ resolve34(addr.port);
44275
44707
  else
44276
44708
  reject(new Error("no port"));
44277
44709
  });
@@ -44279,9 +44711,9 @@ async function startRpcServer(options) {
44279
44711
  server.unref();
44280
44712
  if (options.sweepRoot) {
44281
44713
  try {
44282
- await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log18);
44714
+ await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log19);
44283
44715
  } catch (error) {
44284
- log18.warn("rpc state sweep failed", {
44716
+ log19.warn("rpc state sweep failed", {
44285
44717
  pid: process.pid,
44286
44718
  error: error instanceof Error ? error.message : String(error)
44287
44719
  });
@@ -44289,21 +44721,21 @@ async function startRpcServer(options) {
44289
44721
  }
44290
44722
  try {
44291
44723
  await writePortFile(options.dir, { port, token, pid: process.pid }, { secureDir: options.secureDir });
44292
- log18.debug("rpc server pid", {
44724
+ log19.debug("rpc server pid", {
44293
44725
  pid: process.pid,
44294
44726
  rpcPort: port
44295
44727
  });
44296
44728
  } catch (error) {
44297
- await new Promise((resolve33) => server.close(() => resolve33()));
44729
+ await new Promise((resolve34) => server.close(() => resolve34()));
44298
44730
  throw error;
44299
44731
  }
44300
44732
  return {
44301
44733
  port,
44302
44734
  token,
44303
44735
  async stop() {
44304
- await new Promise((resolve33) => {
44736
+ await new Promise((resolve34) => {
44305
44737
  server.closeAllConnections?.();
44306
- server.close(() => resolve33());
44738
+ server.close(() => resolve34());
44307
44739
  for (const socket of connections)
44308
44740
  socket.destroy();
44309
44741
  });
@@ -45228,7 +45660,7 @@ import { join as join33, resolve as resolve29 } from "node:path";
45228
45660
  // ../core/dist/common-auth-embedded/tui-prefs/watcher.js
45229
45661
  init_canonical_file_path();
45230
45662
  init_private_files();
45231
- import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync8, watch } from "node:fs";
45663
+ import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync9, watch } from "node:fs";
45232
45664
  import { readFile as readFile17, stat as stat18 } from "node:fs/promises";
45233
45665
  import { basename as basename11, dirname as dirname25, join as join32, resolve as resolve28 } from "node:path";
45234
45666
  import { clearTimeout as clearTimeout2, setTimeout as setTimeout2 } from "node:timers";
@@ -45272,7 +45704,7 @@ function watchFile(file, onChange, options, settings) {
45272
45704
  let lastSeen = null;
45273
45705
  if (settings || !windowsPrivateFiles)
45274
45706
  try {
45275
- const metadata = identity3((options.fs?.statSync ?? statSync8)(path5), settings);
45707
+ const metadata = identity3((options.fs?.statSync ?? statSync9)(path5), settings);
45276
45708
  lastSeen = (options.fs?.readFileSync ?? ((file2) => readFileSync8(file2, "utf8")))(path5);
45277
45709
  lastMetadata = metadata;
45278
45710
  } catch {
@@ -46158,7 +46590,7 @@ function openSettings(definition, options) {
46158
46590
  loaded = windowsSeen.get(path5) !== content;
46159
46591
  windowsSeen.set(path5, content);
46160
46592
  };
46161
- const readFile23 = async ([path5]) => {
46593
+ const readFile24 = async ([path5]) => {
46162
46594
  let text2;
46163
46595
  try {
46164
46596
  text2 = await SettingsFs.readFile(path5, "utf8");
@@ -46195,7 +46627,7 @@ function openSettings(definition, options) {
46195
46627
  snapshot: buildSettingsSnapshot(definition, file, parsed)
46196
46628
  } : { status: "unparseable" };
46197
46629
  };
46198
- const outcome = process.platform === "win32" ? await readFile23([file.path]) : await cache.read([file.path], readFile23);
46630
+ const outcome = process.platform === "win32" ? await readFile24([file.path]) : await cache.read([file.path], readFile24);
46199
46631
  const key2 = JSON.stringify([file.kind, file.path]);
46200
46632
  if (currentSequence <= (committedSequences.get(key2) ?? 0))
46201
46633
  return;
@@ -46334,7 +46766,7 @@ async function exists3(path5) {
46334
46766
  throw error;
46335
46767
  }
46336
46768
  }
46337
- function log9(options, level, message, data) {
46769
+ function log10(options, level, message, data) {
46338
46770
  try {
46339
46771
  options.log[level](message, data);
46340
46772
  } catch {
@@ -46405,7 +46837,7 @@ function merge(options, legacy, mapped, result) {
46405
46837
  }));
46406
46838
  if (values.some(({ host, value }) => !isDeepStrictEqual5(hosts.has(host) ? hosts.get(host) : primary.value, value))) {
46407
46839
  result.differing.push({ setting, values });
46408
- log9(options, "info", `Differing legacy settings: ${setting}`, { values });
46840
+ log10(options, "info", `Differing legacy settings: ${setting}`, { values });
46409
46841
  }
46410
46842
  }
46411
46843
  return document;
@@ -46442,7 +46874,7 @@ A rollback loses changes made after the move.
46442
46874
  }
46443
46875
  } catch (error) {
46444
46876
  result.noteFailures.push({ path: path5, error });
46445
- log9(options, "warn", "Could not write settings move note", {
46877
+ log10(options, "warn", "Could not write settings move note", {
46446
46878
  path: path5,
46447
46879
  error
46448
46880
  });
@@ -46486,7 +46918,7 @@ ${JSON.stringify(document, null, 2)}
46486
46918
  staged = false;
46487
46919
  } catch (error) {
46488
46920
  result.postPublishFailures.push({ step: "temp-unlink", error });
46489
- log9(options, "warn", "Settings move temp cleanup failed", { temp, error });
46921
+ log10(options, "warn", "Settings move temp cleanup failed", { temp, error });
46490
46922
  }
46491
46923
  if (process.platform !== "win32") {
46492
46924
  try {
@@ -46498,7 +46930,7 @@ ${JSON.stringify(document, null, 2)}
46498
46930
  }
46499
46931
  } catch (error) {
46500
46932
  result.postPublishFailures.push({ step: "directory-sync", error });
46501
- log9(options, "warn", "Settings move directory sync failed", {
46933
+ log10(options, "warn", "Settings move directory sync failed", {
46502
46934
  target,
46503
46935
  error
46504
46936
  });
@@ -46607,7 +47039,7 @@ async function moveSettingsOnce(options) {
46607
47039
  if (settled.outcome === "moved") {
46608
47040
  settled.postPublishFailures.push({ step: "lock-release", error });
46609
47041
  }
46610
- log9(options, "warn", "Settings move lock release failed", { error });
47042
+ log10(options, "warn", "Settings move lock release failed", { error });
46611
47043
  return settled;
46612
47044
  }
46613
47045
  } catch (cause) {
@@ -47044,7 +47476,7 @@ function getUserConfigPath() {
47044
47476
  function getProjectConfigPath(directory) {
47045
47477
  return join35(directory, ".opencode", "antigravity.json");
47046
47478
  }
47047
- function loadConfigFile(path5, log18) {
47479
+ function loadConfigFile(path5, log19) {
47048
47480
  try {
47049
47481
  if (!fs6.existsSync(path5)) {
47050
47482
  return null;
@@ -47053,7 +47485,7 @@ function loadConfigFile(path5, log18) {
47053
47485
  const rawConfig = JSON.parse(content);
47054
47486
  const result = AntigravityConfigSchema.partial().safeParse(rawConfig);
47055
47487
  if (!result.success) {
47056
- log18.warn("Config validation error", {
47488
+ log19.warn("Config validation error", {
47057
47489
  path: path5,
47058
47490
  issues: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ")
47059
47491
  });
@@ -47062,9 +47494,9 @@ function loadConfigFile(path5, log18) {
47062
47494
  return result.data;
47063
47495
  } catch (error) {
47064
47496
  if (error instanceof SyntaxError) {
47065
- log18.warn("Invalid JSON in config file", { path: path5, error: error.message });
47497
+ log19.warn("Invalid JSON in config file", { path: path5, error: error.message });
47066
47498
  } else {
47067
- log18.warn("Failed to load config file", { path: path5, error: String(error) });
47499
+ log19.warn("Failed to load config file", { path: path5, error: String(error) });
47068
47500
  }
47069
47501
  return null;
47070
47502
  }
@@ -47083,15 +47515,15 @@ function mergeConfigs(base, override) {
47083
47515
  function loadConfig(directory) {
47084
47516
  return loadConfigWithLogger(directory, legacyLog);
47085
47517
  }
47086
- function loadConfigWithLogger(directory, log18) {
47518
+ function loadConfigWithLogger(directory, log19) {
47087
47519
  let config = structuredClone(DEFAULT_CONFIG);
47088
47520
  const userConfigPath = getUserConfigPath();
47089
- const userConfig = loadConfigFile(userConfigPath, log18);
47521
+ const userConfig = loadConfigFile(userConfigPath, log19);
47090
47522
  if (userConfig) {
47091
47523
  config = mergeConfigs(config, userConfig);
47092
47524
  }
47093
47525
  const projectConfigPath = getProjectConfigPath(directory);
47094
- const projectConfig = loadConfigFile(projectConfigPath, log18);
47526
+ const projectConfig = loadConfigFile(projectConfigPath, log19);
47095
47527
  if (projectConfig) {
47096
47528
  config = mergeConfigs(config, projectConfig);
47097
47529
  }
@@ -47605,7 +48037,7 @@ async function defaultFence2() {
47605
48037
  return (await versionFenceOpen({ currentVersion })).open;
47606
48038
  }
47607
48039
  function createSettingsRuntime(options) {
47608
- const { file, legacyUserFile, log: log18 } = options;
48040
+ const { file, legacyUserFile, log: log19 } = options;
47609
48041
  const open14 = options.open ?? openSettings;
47610
48042
  const store = options.protection ?? createProtectionStore2();
47611
48043
  const reportPath = options.moveReportPath ?? defaultMoveReportPath();
@@ -47620,7 +48052,7 @@ function createSettingsRuntime(options) {
47620
48052
  const enqueue = (step) => {
47621
48053
  const run = queue2.then(step);
47622
48054
  queue2 = run.catch(
47623
- (error) => log18.warn("Settings refresh failed", {
48055
+ (error) => log19.warn("Settings refresh failed", {
47624
48056
  error: error instanceof Error ? error.name : "unknown"
47625
48057
  })
47626
48058
  );
@@ -47653,7 +48085,7 @@ function createSettingsRuntime(options) {
47653
48085
  await store.save(file, next);
47654
48086
  persisted = next;
47655
48087
  } catch (error) {
47656
- log18.warn("Could not save the last applied protection settings", {
48088
+ log19.warn("Could not save the last applied protection settings", {
47657
48089
  error: error instanceof Error ? error.name : "unknown"
47658
48090
  });
47659
48091
  }
@@ -47723,7 +48155,7 @@ function createSettingsRuntime(options) {
47723
48155
  if (mode === "shared" || disposed) return;
47724
48156
  handle = open14(ANTIGRAVITY_SETTINGS, {
47725
48157
  file,
47726
- log: log18,
48158
+ log: log19,
47727
48159
  separateInstall: false,
47728
48160
  createMissing: true,
47729
48161
  legacyProject: (project2) => ({
@@ -47761,7 +48193,7 @@ function createSettingsRuntime(options) {
47761
48193
  legacyUserFile,
47762
48194
  floorKeys: options.floorKeys ?? (async () => null),
47763
48195
  fence: options.fence ?? defaultFence2,
47764
- log: log18,
48196
+ log: log19,
47765
48197
  ...options.move ? { move: options.move } : {}
47766
48198
  });
47767
48199
  } catch (cause) {
@@ -47780,7 +48212,7 @@ function createSettingsRuntime(options) {
47780
48212
  unmapped: result.unmapped
47781
48213
  });
47782
48214
  } catch (error) {
47783
- log18.warn("Could not save the settings move report", {
48215
+ log19.warn("Could not save the settings move report", {
47784
48216
  error: error instanceof Error ? error.name : "unknown"
47785
48217
  });
47786
48218
  }
@@ -47793,14 +48225,14 @@ function createSettingsRuntime(options) {
47793
48225
  return;
47794
48226
  case "fence-closed":
47795
48227
  if (!reportedFence)
47796
- log18.info(
48228
+ log19.info(
47797
48229
  "Settings stay in antigravity.json while an older antigravity-auth runs"
47798
48230
  );
47799
48231
  reportedFence = true;
47800
48232
  break;
47801
48233
  case "failed":
47802
48234
  if (!reportedFailure)
47803
- log18.warn("The settings move failed; it is retried", {
48235
+ log19.warn("The settings move failed; it is retried", {
47804
48236
  error: result.cause instanceof Error ? result.cause.name : "unknown"
47805
48237
  });
47806
48238
  reportedFailure = true;
@@ -48292,6 +48724,25 @@ function selectBestVerificationUrl(urls) {
48292
48724
  unique.sort((a, b) => score(b) - score(a));
48293
48725
  return unique[0];
48294
48726
  }
48727
+ function structuredVerificationUrl(bodyText) {
48728
+ const urls = /* @__PURE__ */ new Set();
48729
+ const collect = (payload) => {
48730
+ try {
48731
+ JSON.parse(payload, (key2, value) => {
48732
+ if (typeof value === "string" && /^(?:validation_url|verify_url|verification_url|url)$/i.test(key2) && /^https:\/\//i.test(decodeEscapedText(value).trim()))
48733
+ urls.add(value);
48734
+ return value;
48735
+ });
48736
+ } catch {
48737
+ }
48738
+ };
48739
+ collect(bodyText);
48740
+ for (const rawLine of bodyText.split("\n")) {
48741
+ const line = rawLine.trim();
48742
+ if (line.startsWith("data:")) collect(line.slice(5));
48743
+ }
48744
+ return selectBestVerificationUrl([...urls]);
48745
+ }
48295
48746
  function extractAccountAccessErrorDetails(bodyText) {
48296
48747
  const decodedBody = decodeEscapedText(bodyText);
48297
48748
  const lowerBody = decodedBody.toLowerCase();
@@ -48369,11 +48820,13 @@ function extractAccountAccessErrorDetails(bodyText) {
48369
48820
  (line) => line && !line.startsWith("data:") && /(verify|validation|required|ineligible)/i.test(line)
48370
48821
  );
48371
48822
  }
48823
+ const structuredVerifyUrl = structuredVerificationUrl(bodyText);
48372
48824
  return {
48373
48825
  validationRequired,
48374
48826
  accountIneligible,
48375
48827
  message,
48376
- verifyUrl: selectBestVerificationUrl([...verificationUrls])
48828
+ verifyUrl: selectBestVerificationUrl([...verificationUrls]),
48829
+ ...structuredVerifyUrl && { structuredVerifyUrl }
48377
48830
  };
48378
48831
  }
48379
48832
  function buildAccountAccessProbeRequest(projectId) {
@@ -49117,11 +49570,15 @@ init_dist();
49117
49570
  // src/plugin/config/models.ts
49118
49571
  function getOpencode1ModelDefinitions() {
49119
49572
  const models = { ...OPENCODE_MODEL_DEFINITIONS };
49120
- const hydrogen = models["antigravity-gemini-4-hydrogen"];
49121
- if (hydrogen) {
49122
- const variants = { ...hydrogen.variants };
49573
+ for (const id of [
49574
+ "antigravity-gemini-4-hydrogen",
49575
+ "antigravity-gemini-4-neon"
49576
+ ]) {
49577
+ const model = models[id];
49578
+ if (!model) continue;
49579
+ const variants = { ...model.variants };
49123
49580
  delete variants.xhigh;
49124
- models[hydrogen.id] = { ...hydrogen, variants };
49581
+ models[id] = { ...model, variants };
49125
49582
  }
49126
49583
  return models;
49127
49584
  }
@@ -49403,7 +49860,7 @@ async function select3(items, options) {
49403
49860
  }
49404
49861
  renderedLines = linesWritten;
49405
49862
  };
49406
- return new Promise((resolve33) => {
49863
+ return new Promise((resolve34) => {
49407
49864
  const wasRaw = stdin.isRaw ?? false;
49408
49865
  const cleanup2 = () => {
49409
49866
  if (isCleanedUp) return;
@@ -49424,11 +49881,11 @@ async function select3(items, options) {
49424
49881
  };
49425
49882
  const onSignal = () => {
49426
49883
  cleanup2();
49427
- resolve33(null);
49884
+ resolve34(null);
49428
49885
  };
49429
49886
  const finishWithValue = (value) => {
49430
49887
  cleanup2();
49431
- resolve33(value);
49888
+ resolve34(value);
49432
49889
  };
49433
49890
  const findNextSelectable = (from, direction) => {
49434
49891
  if (items.length === 0) return from;
@@ -49474,7 +49931,7 @@ async function select3(items, options) {
49474
49931
  stdin.setRawMode(true);
49475
49932
  } catch {
49476
49933
  cleanup2();
49477
- resolve33(null);
49934
+ resolve34(null);
49478
49935
  return;
49479
49936
  }
49480
49937
  stdin.resume();
@@ -50164,10 +50621,10 @@ function toV1AuthCallbackResult(result) {
50164
50621
  };
50165
50622
  }
50166
50623
  var MAX_OAUTH_ACCOUNTS = 10;
50167
- var log10 = createLogger4("oauth-methods");
50168
- async function reportPersistenceFailure(error, client, log18) {
50624
+ var log11 = createLogger4("oauth-methods");
50625
+ async function reportPersistenceFailure(error, client, log19) {
50169
50626
  const message = error instanceof AccountStorageUnreadableError ? `Account storage at ${error.details.path} is unreadable (${error.details.reason}: ${error.details.detail}).${error.details.backupPath ? ` A backup was written to ${error.details.backupPath}. Repair or remove the existing file before retrying.` : " A backup could not be written; repair or remove the existing file before retrying."}` : error instanceof Error ? error.message : String(error);
50170
- log18.error("OAuth login persistence failed; aborting login", {
50627
+ log19.error("OAuth login persistence failed; aborting login", {
50171
50628
  error: message
50172
50629
  });
50173
50630
  try {
@@ -51004,7 +51461,7 @@ ${verifyUrl}
51004
51461
  }
51005
51462
  });
51006
51463
  } catch (storeError) {
51007
- log10.error(
51464
+ log11.error(
51008
51465
  "Failed to update stored Antigravity OAuth credentials",
51009
51466
  { error: String(storeError) }
51010
51467
  );
@@ -51029,7 +51486,7 @@ ${verifyUrl}
51029
51486
  }
51030
51487
  });
51031
51488
  } catch (storeError) {
51032
- log10.error(
51489
+ log11.error(
51033
51490
  "Failed to clear stored Antigravity OAuth credentials",
51034
51491
  { error: String(storeError) }
51035
51492
  );
@@ -51070,7 +51527,7 @@ Re-authenticating ${refreshEmail || "account"}...
51070
51527
  }
51071
51528
  });
51072
51529
  } catch (storeError) {
51073
- log10.error(
51530
+ log11.error(
51074
51531
  "Failed to clear stored Antigravity OAuth credentials",
51075
51532
  { error: String(storeError) }
51076
51533
  );
@@ -51409,7 +51866,7 @@ ${authorization2.url}
51409
51866
  return await reportPersistenceFailure(
51410
51867
  persistError,
51411
51868
  client,
51412
- log10
51869
+ log11
51413
51870
  );
51414
51871
  }
51415
51872
  const newTotal = existingCount + 1;
@@ -51453,7 +51910,7 @@ ${authorization2.url}
51453
51910
  try {
51454
51911
  await persistAccountPool2([result], false);
51455
51912
  } catch (persistError) {
51456
- return await reportPersistenceFailure(persistError, client, log10);
51913
+ return await reportPersistenceFailure(persistError, client, log11);
51457
51914
  }
51458
51915
  const newTotal = existingCount + 1;
51459
51916
  const toastMessage = existingCount > 0 ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total` : `Authenticated${result.email ? ` (${result.email})` : ""}`;
@@ -51617,7 +52074,7 @@ init_logger4();
51617
52074
 
51618
52075
  // src/plugin/refresh-queue.ts
51619
52076
  init_logger4();
51620
- var log11 = createLogger4("refresh-queue");
52077
+ var log12 = createLogger4("refresh-queue");
51621
52078
  var DEFAULT_PROACTIVE_REFRESH_CONFIG = {
51622
52079
  enabled: true,
51623
52080
  bufferSeconds: 1800,
@@ -51657,7 +52114,7 @@ var ProactiveRefreshQueue = class {
51657
52114
  "ProactiveRefreshQueue needs a host client or explicit dependencies"
51658
52115
  );
51659
52116
  }
51660
- this.log = log11;
52117
+ this.log = log12;
51661
52118
  this.refresh = (auth) => refreshAccessToken(auth, client, providerId);
51662
52119
  }
51663
52120
  this.config = {
@@ -51877,20 +52334,20 @@ import crypto2 from "node:crypto";
51877
52334
  import { createHash as createHash17 } from "node:crypto";
51878
52335
 
51879
52336
  // src/plugin/cache/signature-cache.ts
52337
+ init_atomic_write();
51880
52338
  init_runtime_paths();
51881
- import {
51882
- existsSync as existsSync13,
51883
- mkdirSync as mkdirSync5,
51884
- readFileSync as readFileSync14,
51885
- renameSync as renameSync4,
51886
- unlinkSync as unlinkSync3,
51887
- writeFileSync as writeFileSync5
51888
- } from "node:fs";
51889
- import { tmpdir as tmpdir5 } from "node:os";
51890
- import { dirname as dirname33, join as join40 } from "node:path";
52339
+ import { existsSync as existsSync13, readFileSync as readFileSync14 } from "node:fs";
52340
+ import { readFile as readFile23 } from "node:fs/promises";
52341
+ import { resolve as resolve32 } from "node:path";
51891
52342
  function getSignatureCacheFilePath() {
51892
52343
  return stateHomeSignatureCacheFile();
51893
52344
  }
52345
+ var MAX_ENTRIES = 4096;
52346
+ function newestEntries(entries) {
52347
+ if (entries.length <= MAX_ENTRIES) return entries;
52348
+ return entries.sort(([, a], [, b]) => a.timestamp - b.timestamp).slice(-MAX_ENTRIES);
52349
+ }
52350
+ var pendingWrites = /* @__PURE__ */ new Map();
51894
52351
  var SignatureCache = class {
51895
52352
  // In-memory cache: key -> entry with signature and optional thinking text
51896
52353
  cache = /* @__PURE__ */ new Map();
@@ -51905,6 +52362,8 @@ var SignatureCache = class {
51905
52362
  now;
51906
52363
  // State
51907
52364
  dirty = false;
52365
+ revision = 0;
52366
+ pendingWrite;
51908
52367
  writeTimer = null;
51909
52368
  cleanupTimer = null;
51910
52369
  // Statistics
@@ -51941,11 +52400,10 @@ var SignatureCache = class {
51941
52400
  */
51942
52401
  store(key2, signature) {
51943
52402
  if (!this.enabled) return;
51944
- this.cache.set(key2, {
52403
+ this.storeEntry(key2, {
51945
52404
  value: signature,
51946
52405
  timestamp: this.now()
51947
52406
  });
51948
- this.dirty = true;
51949
52407
  }
51950
52408
  /**
51951
52409
  * Retrieve a signature from the cache.
@@ -51996,13 +52454,29 @@ var SignatureCache = class {
51996
52454
  */
51997
52455
  storeThinking(key2, thinkingText, signature, toolIds) {
51998
52456
  if (!this.enabled || !thinkingText || !signature) return;
51999
- this.cache.set(key2, {
52457
+ this.storeEntry(key2, {
52000
52458
  value: signature,
52001
52459
  timestamp: this.now(),
52002
52460
  thinkingText,
52003
52461
  textPreview: thinkingText.slice(0, 100),
52004
52462
  toolIds
52005
52463
  });
52464
+ }
52465
+ storeEntry(key2, entry) {
52466
+ this.cache.delete(key2);
52467
+ this.cache.set(key2, entry);
52468
+ if (this.cache.size > MAX_ENTRIES) {
52469
+ let oldest;
52470
+ let oldestTimestamp = Number.POSITIVE_INFINITY;
52471
+ for (const [candidate, value] of this.cache) {
52472
+ if (oldest === void 0 || value.timestamp < oldestTimestamp) {
52473
+ oldest = candidate;
52474
+ oldestTimestamp = value.timestamp;
52475
+ }
52476
+ }
52477
+ if (oldest !== void 0) this.cache.delete(oldest);
52478
+ }
52479
+ this.revision++;
52006
52480
  this.dirty = true;
52007
52481
  }
52008
52482
  /**
@@ -52071,7 +52545,17 @@ var SignatureCache = class {
52071
52545
  */
52072
52546
  async flush() {
52073
52547
  if (!this.enabled) return true;
52074
- return this.saveToDisk();
52548
+ const path5 = resolve32(this.cacheFilePath);
52549
+ const previous = pendingWrites.get(path5) ?? Promise.resolve(true);
52550
+ const writing = previous.then(() => this.saveToDisk());
52551
+ this.pendingWrite = writing;
52552
+ pendingWrites.set(path5, writing);
52553
+ try {
52554
+ return await writing;
52555
+ } finally {
52556
+ if (this.pendingWrite === writing) this.pendingWrite = void 0;
52557
+ if (pendingWrites.get(path5) === writing) pendingWrites.delete(path5);
52558
+ }
52075
52559
  }
52076
52560
  /**
52077
52561
  * Graceful shutdown: stop timers and flush to disk.
@@ -52086,7 +52570,7 @@ var SignatureCache = class {
52086
52570
  this.cleanupTimer = null;
52087
52571
  }
52088
52572
  if (this.dirty && this.enabled) {
52089
- this.saveToDisk();
52573
+ void this.flush();
52090
52574
  }
52091
52575
  }
52092
52576
  // ===========================================================================
@@ -52121,6 +52605,9 @@ var SignatureCache = class {
52121
52605
  _expired++;
52122
52606
  }
52123
52607
  }
52608
+ if (this.cache.size > MAX_ENTRIES) {
52609
+ this.cache = new Map(newestEntries([...this.cache]));
52610
+ }
52124
52611
  } catch {
52125
52612
  }
52126
52613
  }
@@ -52128,22 +52615,17 @@ var SignatureCache = class {
52128
52615
  * Save cache to disk with atomic write pattern.
52129
52616
  * Merges with existing disk entries that haven't expired.
52130
52617
  */
52131
- saveToDisk() {
52618
+ async saveToDisk() {
52132
52619
  try {
52133
- const dir = dirname33(this.cacheFilePath);
52134
- if (!existsSync13(dir)) {
52135
- mkdirSync5(dir, { recursive: true });
52136
- }
52137
- const now2 = this.now();
52138
52620
  let existingEntries = {};
52139
- if (existsSync13(this.cacheFilePath)) {
52140
- try {
52141
- const content = readFileSync14(this.cacheFilePath, "utf-8");
52142
- const data = JSON.parse(content);
52143
- existingEntries = data.entries || {};
52144
- } catch {
52145
- }
52621
+ try {
52622
+ const content = await readFile23(this.cacheFilePath, "utf-8");
52623
+ const data = JSON.parse(content);
52624
+ existingEntries = data.entries || {};
52625
+ } catch {
52146
52626
  }
52627
+ const now2 = this.now();
52628
+ const revision = this.revision;
52147
52629
  const validDiskEntries = {};
52148
52630
  for (const [key2, entry] of Object.entries(existingEntries)) {
52149
52631
  const age = now2 - entry.timestamp;
@@ -52162,7 +52644,9 @@ var SignatureCache = class {
52162
52644
  version: "1.0",
52163
52645
  memory_ttl_seconds: this.retentionMemoryTtlMs / 1e3,
52164
52646
  disk_ttl_seconds: this.retentionDiskTtlMs / 1e3,
52165
- entries: mergedEntries,
52647
+ entries: Object.fromEntries(
52648
+ newestEntries(Object.entries(mergedEntries))
52649
+ ),
52166
52650
  statistics: {
52167
52651
  memory_hits: this.stats.memoryHits,
52168
52652
  disk_hits: this.stats.diskHits,
@@ -52171,22 +52655,9 @@ var SignatureCache = class {
52171
52655
  last_write: now2
52172
52656
  }
52173
52657
  };
52174
- const tmpPath = join40(
52175
- tmpdir5(),
52176
- `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
52177
- );
52178
- writeFileSync5(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
52179
- try {
52180
- renameSync4(tmpPath, this.cacheFilePath);
52181
- } catch {
52182
- writeFileSync5(this.cacheFilePath, readFileSync14(tmpPath));
52183
- try {
52184
- unlinkSync3(tmpPath);
52185
- } catch {
52186
- }
52187
- }
52658
+ await writeJsonAtomic(this.cacheFilePath, cacheData);
52188
52659
  this.stats.writes++;
52189
- this.dirty = false;
52660
+ if (revision === this.revision) this.dirty = false;
52190
52661
  return true;
52191
52662
  } catch {
52192
52663
  return false;
@@ -52209,8 +52680,8 @@ var SignatureCache = class {
52209
52680
  }
52210
52681
  startWriteTimer() {
52211
52682
  this.writeTimer = setInterval(() => {
52212
- if (this.dirty) {
52213
- this.saveToDisk();
52683
+ if (this.dirty && !this.pendingWrite) {
52684
+ void this.flush();
52214
52685
  }
52215
52686
  }, this.writeIntervalMs);
52216
52687
  }
@@ -52389,11 +52860,18 @@ function createSignatureProcessState(options = {}) {
52389
52860
  updateRetention(shared3.path);
52390
52861
  return;
52391
52862
  }
52392
- if (disks.get(shared3.path) === shared3) disks.delete(shared3.path);
52863
+ const finalWrite = shared3.cache.flush();
52864
+ shared3.finalWrite = finalWrite;
52393
52865
  try {
52394
- await shared3.cache.flush();
52866
+ await finalWrite;
52395
52867
  } finally {
52396
- shared3.cache.shutdown();
52868
+ if (shared3.finalWrite === finalWrite) {
52869
+ shared3.finalWrite = void 0;
52870
+ if (shared3.owners.size === 0) {
52871
+ disks.delete(shared3.path);
52872
+ shared3.cache.shutdown();
52873
+ }
52874
+ }
52397
52875
  }
52398
52876
  };
52399
52877
  return {
@@ -52418,7 +52896,10 @@ function createSignatureProcessState(options = {}) {
52418
52896
  pathReaders.add(consumer);
52419
52897
  updateRetention(path5);
52420
52898
  }
52421
- const readableCache = () => shared3?.cache ?? (path5 ? disks.get(path5)?.cache : void 0);
52899
+ const readableCache = () => {
52900
+ const current = shared3 ?? (path5 ? disks.get(path5) : void 0);
52901
+ if (current?.owners.size) return current.cache;
52902
+ };
52422
52903
  const signatureStore = createSignatureStore();
52423
52904
  let disposed = false;
52424
52905
  return {
@@ -52523,13 +53004,13 @@ function clearSignatureCache(sessionId) {
52523
53004
  }
52524
53005
 
52525
53006
  // src/plugin/image-saver.ts
52526
- import { chmodSync as chmodSync4, existsSync as existsSync14, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
53007
+ import { chmodSync as chmodSync4, existsSync as existsSync14, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
52527
53008
  import { homedir as homedir14 } from "node:os";
52528
- import { join as join41 } from "node:path";
53009
+ import { join as join40 } from "node:path";
52529
53010
  function getImageOutputDir(outputDir) {
52530
- const resolved = outputDir ?? join41(homedir14(), ".opencode", "generated-images");
53011
+ const resolved = outputDir ?? join40(homedir14(), ".opencode", "generated-images");
52531
53012
  if (!existsSync14(resolved)) {
52532
- mkdirSync6(resolved, { recursive: true, mode: 448 });
53013
+ mkdirSync5(resolved, { recursive: true, mode: 448 });
52533
53014
  }
52534
53015
  chmodSync4(resolved, 448);
52535
53016
  return resolved;
@@ -52550,8 +53031,8 @@ function generateImageFilename(mimeType) {
52550
53031
  function saveImageToDisk(base64Data, mimeType, outputDir) {
52551
53032
  try {
52552
53033
  const resolvedOutputDir = getImageOutputDir(outputDir);
52553
- const filePath = join41(resolvedOutputDir, generateImageFilename(mimeType));
52554
- writeFileSync6(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
53034
+ const filePath = join40(resolvedOutputDir, generateImageFilename(mimeType));
53035
+ writeFileSync5(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
52555
53036
  chmodSync4(filePath, 384);
52556
53037
  return filePath;
52557
53038
  } catch (error) {
@@ -52994,6 +53475,49 @@ data: ${JSON.stringify(syntheticUsage)}
52994
53475
  });
52995
53476
  }
52996
53477
 
53478
+ // src/plugin/core/streaming/displayed-thinking.ts
53479
+ var MAX_DISPLAYED_THINKING_SESSIONS = 256;
53480
+ var MAX_DISPLAYED_THINKING_PER_SESSION = 512;
53481
+ var BoundedHashSet = class extends Set {
53482
+ constructor(limit) {
53483
+ super();
53484
+ this.limit = limit;
53485
+ }
53486
+ limit;
53487
+ add(value) {
53488
+ if (!this.has(value) && this.size >= this.limit) {
53489
+ const oldest = this.values().next().value;
53490
+ if (oldest !== void 0) this.delete(oldest);
53491
+ }
53492
+ return super.add(value);
53493
+ }
53494
+ };
53495
+ function createDisplayedThinkingRegistry(limits = {}) {
53496
+ const maxSessions = limits.sessions ?? MAX_DISPLAYED_THINKING_SESSIONS;
53497
+ const perSession = limits.perSession ?? MAX_DISPLAYED_THINKING_PER_SESSION;
53498
+ const sessions = /* @__PURE__ */ new Map();
53499
+ return {
53500
+ forSession(sessionKey) {
53501
+ if (!sessionKey) return void 0;
53502
+ let hashes = sessions.get(sessionKey);
53503
+ if (hashes) {
53504
+ sessions.delete(sessionKey);
53505
+ } else {
53506
+ hashes = new BoundedHashSet(perSession);
53507
+ if (sessions.size >= maxSessions) {
53508
+ const oldest = sessions.keys().next().value;
53509
+ if (oldest !== void 0) sessions.delete(oldest);
53510
+ }
53511
+ }
53512
+ sessions.set(sessionKey, hashes);
53513
+ return hashes;
53514
+ },
53515
+ get sessionCount() {
53516
+ return sessions.size;
53517
+ }
53518
+ };
53519
+ }
53520
+
52997
53521
  // src/plugin/request.ts
52998
53522
  init_debug();
52999
53523
 
@@ -53001,12 +53525,12 @@ init_debug();
53001
53525
  init_dist();
53002
53526
  init_logging_utils();
53003
53527
  import { createHash as createHash18 } from "node:crypto";
53004
- import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "node:fs";
53005
- import { tmpdir as tmpdir6 } from "node:os";
53006
- import { join as join42 } from "node:path";
53528
+ import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
53529
+ import { tmpdir as tmpdir5 } from "node:os";
53530
+ import { join as join41 } from "node:path";
53007
53531
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
53008
53532
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
53009
- var DEFAULT_DUMP_DIR = join42(tmpdir6(), "opencode-antigravity-gemini-dumps");
53533
+ var DEFAULT_DUMP_DIR = join41(tmpdir5(), "opencode-antigravity-gemini-dumps");
53010
53534
  var DUMP_DIR_MODE = 448;
53011
53535
  var DUMP_FILE_MODE = 384;
53012
53536
  var nextDumpId = 0;
@@ -53138,7 +53662,7 @@ function bodyStructureSummary(bodyText) {
53138
53662
  };
53139
53663
  }
53140
53664
  function writeJson(path5, value) {
53141
- writeFileSync7(path5, `${JSON.stringify(value, null, 2)}
53665
+ writeFileSync6(path5, `${JSON.stringify(value, null, 2)}
53142
53666
  `, {
53143
53667
  encoding: "utf8",
53144
53668
  mode: DUMP_FILE_MODE
@@ -53160,8 +53684,8 @@ function writeGeminiDump(input2) {
53160
53684
  nextDumpId += 1;
53161
53685
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
53162
53686
  const dumpDir = getGeminiDumpDirectory();
53163
- const prefix = join42(dumpDir, id);
53164
- mkdirSync7(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
53687
+ const prefix = join41(dumpDir, id);
53688
+ mkdirSync6(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
53165
53689
  const context = {
53166
53690
  id,
53167
53691
  files: {
@@ -53189,11 +53713,11 @@ function writeGeminiDump(input2) {
53189
53713
  }
53190
53714
  }
53191
53715
  };
53192
- writeFileSync7(context.files.request, redactJsonBodyString(input2.body), {
53716
+ writeFileSync6(context.files.request, redactJsonBodyString(input2.body), {
53193
53717
  encoding: "utf8",
53194
53718
  mode: DUMP_FILE_MODE
53195
53719
  });
53196
- writeFileSync7(context.files.response, "", {
53720
+ writeFileSync6(context.files.response, "", {
53197
53721
  encoding: "utf8",
53198
53722
  mode: DUMP_FILE_MODE
53199
53723
  });
@@ -53245,27 +53769,27 @@ init_logger4();
53245
53769
  // src/plugin/recovery/storage.ts
53246
53770
  import {
53247
53771
  existsSync as existsSync15,
53248
- mkdirSync as mkdirSync8,
53772
+ mkdirSync as mkdirSync7,
53249
53773
  readdirSync as readdirSync2,
53250
53774
  readFileSync as readFileSync15,
53251
- unlinkSync as unlinkSync4,
53252
- writeFileSync as writeFileSync8
53775
+ unlinkSync as unlinkSync3,
53776
+ writeFileSync as writeFileSync7
53253
53777
  } from "node:fs";
53254
- import { join as join44 } from "node:path";
53778
+ import { join as join43 } from "node:path";
53255
53779
 
53256
53780
  // src/plugin/recovery/constants.ts
53257
53781
  import { homedir as homedir15 } from "node:os";
53258
- import { join as join43 } from "node:path";
53782
+ import { join as join42 } from "node:path";
53259
53783
  function getXdgData() {
53260
53784
  const platform = process.platform;
53261
53785
  if (platform === "win32") {
53262
- return process.env.APPDATA || join43(homedir15(), "AppData", "Roaming");
53786
+ return process.env.APPDATA || join42(homedir15(), "AppData", "Roaming");
53263
53787
  }
53264
- return process.env.XDG_DATA_HOME || join43(homedir15(), ".local", "share");
53788
+ return process.env.XDG_DATA_HOME || join42(homedir15(), ".local", "share");
53265
53789
  }
53266
- var OPENCODE_STORAGE = join43(getXdgData(), "opencode", "storage");
53267
- var MESSAGE_STORAGE = join43(OPENCODE_STORAGE, "message");
53268
- var PART_STORAGE = join43(OPENCODE_STORAGE, "part");
53790
+ var OPENCODE_STORAGE = join42(getXdgData(), "opencode", "storage");
53791
+ var MESSAGE_STORAGE = join42(OPENCODE_STORAGE, "message");
53792
+ var PART_STORAGE = join42(OPENCODE_STORAGE, "part");
53269
53793
  var THINKING_TYPES = /* @__PURE__ */ new Set([
53270
53794
  "thinking",
53271
53795
  "redacted_thinking",
@@ -53275,13 +53799,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
53275
53799
  // src/plugin/recovery/storage.ts
53276
53800
  function getMessageDir(sessionID) {
53277
53801
  if (!existsSync15(MESSAGE_STORAGE)) return "";
53278
- const directPath = join44(MESSAGE_STORAGE, sessionID);
53802
+ const directPath = join43(MESSAGE_STORAGE, sessionID);
53279
53803
  if (existsSync15(directPath)) {
53280
53804
  return directPath;
53281
53805
  }
53282
53806
  try {
53283
53807
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
53284
- const sessionPath = join44(MESSAGE_STORAGE, dir, sessionID);
53808
+ const sessionPath = join43(MESSAGE_STORAGE, dir, sessionID);
53285
53809
  if (existsSync15(sessionPath)) {
53286
53810
  return sessionPath;
53287
53811
  }
@@ -53298,7 +53822,7 @@ function readMessages(sessionID) {
53298
53822
  for (const file of readdirSync2(messageDir)) {
53299
53823
  if (!file.endsWith(".json")) continue;
53300
53824
  try {
53301
- const content = readFileSync15(join44(messageDir, file), "utf-8");
53825
+ const content = readFileSync15(join43(messageDir, file), "utf-8");
53302
53826
  messages.push(JSON.parse(content));
53303
53827
  } catch {
53304
53828
  }
@@ -53314,14 +53838,14 @@ function readMessages(sessionID) {
53314
53838
  });
53315
53839
  }
53316
53840
  function readParts(messageID) {
53317
- const partDir = join44(PART_STORAGE, messageID);
53841
+ const partDir = join43(PART_STORAGE, messageID);
53318
53842
  if (!existsSync15(partDir)) return [];
53319
53843
  const parts = [];
53320
53844
  try {
53321
53845
  for (const file of readdirSync2(partDir)) {
53322
53846
  if (!file.endsWith(".json")) continue;
53323
53847
  try {
53324
- const content = readFileSync15(join44(partDir, file), "utf-8");
53848
+ const content = readFileSync15(join43(partDir, file), "utf-8");
53325
53849
  parts.push(JSON.parse(content));
53326
53850
  } catch {
53327
53851
  }
@@ -53363,10 +53887,10 @@ function findMessagesWithOrphanThinking(sessionID) {
53363
53887
  return result;
53364
53888
  }
53365
53889
  function prependThinkingPart(sessionID, messageID) {
53366
- const partDir = join44(PART_STORAGE, messageID);
53890
+ const partDir = join43(PART_STORAGE, messageID);
53367
53891
  try {
53368
53892
  if (!existsSync15(partDir)) {
53369
- mkdirSync8(partDir, { recursive: true });
53893
+ mkdirSync7(partDir, { recursive: true });
53370
53894
  }
53371
53895
  const partId = "prt_0000000000_thinking";
53372
53896
  const part = {
@@ -53377,8 +53901,8 @@ function prependThinkingPart(sessionID, messageID) {
53377
53901
  thinking: "",
53378
53902
  synthetic: true
53379
53903
  };
53380
- writeFileSync8(
53381
- join44(partDir, `${partId}.json`),
53904
+ writeFileSync7(
53905
+ join43(partDir, `${partId}.json`),
53382
53906
  JSON.stringify(part, null, 2)
53383
53907
  );
53384
53908
  return true;
@@ -53387,18 +53911,18 @@ function prependThinkingPart(sessionID, messageID) {
53387
53911
  }
53388
53912
  }
53389
53913
  function stripThinkingParts(messageID) {
53390
- const partDir = join44(PART_STORAGE, messageID);
53914
+ const partDir = join43(PART_STORAGE, messageID);
53391
53915
  if (!existsSync15(partDir)) return false;
53392
53916
  let anyRemoved = false;
53393
53917
  try {
53394
53918
  for (const file of readdirSync2(partDir)) {
53395
53919
  if (!file.endsWith(".json")) continue;
53396
53920
  try {
53397
- const filePath = join44(partDir, file);
53921
+ const filePath = join43(partDir, file);
53398
53922
  const content = readFileSync15(filePath, "utf-8");
53399
53923
  const part = JSON.parse(content);
53400
53924
  if (THINKING_TYPES.has(part.type)) {
53401
- unlinkSync4(filePath);
53925
+ unlinkSync3(filePath);
53402
53926
  anyRemoved = true;
53403
53927
  }
53404
53928
  } catch {
@@ -53628,8 +54152,8 @@ function createSessionRecoveryHook(ctx, config) {
53628
54152
  if (!sessionID) return false;
53629
54153
  let assistantMsgID = info.id;
53630
54154
  let msgs;
53631
- const log18 = createLogger4("session-recovery");
53632
- log18.debug("Recovery attempt started", {
54155
+ const log19 = createLogger4("session-recovery");
54156
+ log19.debug("Recovery attempt started", {
53633
54157
  errorType,
53634
54158
  sessionID,
53635
54159
  providedMsgID: assistantMsgID ?? "none"
@@ -53649,7 +54173,7 @@ function createSessionRecoveryHook(ctx, config) {
53649
54173
  const m = msgs[i];
53650
54174
  if (m && m.info?.role === "assistant" && m.info?.id) {
53651
54175
  assistantMsgID = m.info.id;
53652
- log18.debug("Found assistant message ID from session messages", {
54176
+ log19.debug("Found assistant message ID from session messages", {
53653
54177
  msgID: assistantMsgID,
53654
54178
  msgIndex: i
53655
54179
  });
@@ -53658,7 +54182,7 @@ function createSessionRecoveryHook(ctx, config) {
53658
54182
  }
53659
54183
  }
53660
54184
  if (!assistantMsgID) {
53661
- log18.debug("No assistant message ID found, cannot recover");
54185
+ log19.debug("No assistant message ID found, cannot recover");
53662
54186
  return false;
53663
54187
  }
53664
54188
  if (processingErrors.has(assistantMsgID)) return false;
@@ -53702,7 +54226,7 @@ function createSessionRecoveryHook(ctx, config) {
53702
54226
  }
53703
54227
  return success;
53704
54228
  } catch (err) {
53705
- log18.error("Recovery failed", { error: String(err) });
54229
+ log19.error("Recovery failed", { error: String(err) });
53706
54230
  return false;
53707
54231
  } finally {
53708
54232
  processingErrors.delete(assistantMsgID);
@@ -53722,7 +54246,7 @@ function createSessionRecoveryHook(ctx, config) {
53722
54246
  // src/plugin/request-helpers.ts
53723
54247
  init_dist();
53724
54248
  init_logger4();
53725
- var log12 = createLogger4("request-helpers");
54249
+ var log13 = createLogger4("request-helpers");
53726
54250
  var ANTIGRAVITY_PREVIEW_LINK = "https://goo.gle/enable-preview-features";
53727
54251
  function appendDescriptionHint(schema, hint) {
53728
54252
  if (!schema || typeof schema !== "object") {
@@ -54147,7 +54671,7 @@ function filterContentArray(contentArray, sessionId, getCachedSignatureFn, isCla
54147
54671
  }
54148
54672
  const existingSignature = item.signature || item.thoughtSignature;
54149
54673
  const signatureInfo = existingSignature ? `foreign signature (${String(existingSignature).length} chars)` : "no signature";
54150
- log12.debug(
54674
+ log13.debug(
54151
54675
  `Injecting plain text sentinel for last-message thinking block with ${signatureInfo}`
54152
54676
  );
54153
54677
  const sentinel2 = { text: "." };
@@ -54659,7 +55183,7 @@ function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, curre
54659
55183
  if (lastBracket > 0) {
54660
55184
  const cleaned = stripped.slice(0, lastBracket + 1);
54661
55185
  const parsed = JSON.parse(cleaned);
54662
- log12.debug("Auto-corrected malformed JSON array", {
55186
+ log13.debug("Auto-corrected malformed JSON array", {
54663
55187
  truncatedChars: stripped.length - cleaned.length
54664
55188
  });
54665
55189
  return recursivelyParseJsonStrings(parsed);
@@ -54673,7 +55197,7 @@ function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, curre
54673
55197
  if (lastBrace > 0) {
54674
55198
  const cleaned = stripped.slice(0, lastBrace + 1);
54675
55199
  const parsed = JSON.parse(cleaned);
54676
- log12.debug("Auto-corrected malformed JSON object", {
55200
+ log13.debug("Auto-corrected malformed JSON object", {
54677
55201
  truncatedChars: stripped.length - cleaned.length
54678
55202
  });
54679
55203
  return recursivelyParseJsonStrings(parsed);
@@ -54691,6 +55215,9 @@ function fixToolResponseGrouping(contents) {
54691
55215
  const newContents = [];
54692
55216
  const pendingGroups = [];
54693
55217
  const collectedResponses = /* @__PURE__ */ new Map();
55218
+ const arrivalById = /* @__PURE__ */ new Map();
55219
+ let arrivals = 0;
55220
+ const idsByName = /* @__PURE__ */ new Map();
54694
55221
  for (const content of contents) {
54695
55222
  const role = content.role;
54696
55223
  const parts = content.parts || [];
@@ -54700,6 +55227,15 @@ function fixToolResponseGrouping(contents) {
54700
55227
  const respId = resp.functionResponse?.id || "";
54701
55228
  if (respId && !collectedResponses.has(respId)) {
54702
55229
  collectedResponses.set(respId, resp);
55230
+ const arrival = arrivals++;
55231
+ arrivalById.set(respId, arrival);
55232
+ const name = resp.functionResponse?.name || "";
55233
+ let queue2 = idsByName.get(name);
55234
+ if (!queue2) {
55235
+ queue2 = { entries: [], head: 0 };
55236
+ idsByName.set(name, queue2);
55237
+ }
55238
+ queue2.entries.push({ id: respId, arrival });
54703
55239
  }
54704
55240
  }
54705
55241
  for (let i = pendingGroups.length - 1; i >= 0; i--) {
@@ -54737,7 +55273,20 @@ function fixToolResponseGrouping(contents) {
54737
55273
  newContents.push(content);
54738
55274
  }
54739
55275
  }
55276
+ const firstCollectedNamed = (name) => {
55277
+ const queue2 = idsByName.get(name);
55278
+ if (!queue2) return null;
55279
+ while (queue2.head < queue2.entries.length) {
55280
+ const entry = queue2.entries[queue2.head];
55281
+ if (collectedResponses.has(entry.id) && arrivalById.get(entry.id) === entry.arrival) {
55282
+ return entry.id;
55283
+ }
55284
+ queue2.head++;
55285
+ }
55286
+ return null;
55287
+ };
54740
55288
  pendingGroups.sort((a, b) => b.insertAfterIdx - a.insertAfterIdx);
55289
+ const insertedAfter = /* @__PURE__ */ new Map();
54741
55290
  for (const group of pendingGroups) {
54742
55291
  const groupResponses = [];
54743
55292
  for (let i = 0; i < group.ids.length; i++) {
@@ -54748,20 +55297,9 @@ function fixToolResponseGrouping(contents) {
54748
55297
  collectedResponses.delete(expectedId);
54749
55298
  } else if (collectedResponses.size > 0) {
54750
55299
  let matchedId = null;
54751
- for (const [orphanId, orphanResp] of collectedResponses) {
54752
- const orphanName = orphanResp.functionResponse?.name || "";
54753
- if (orphanName === expectedName) {
54754
- matchedId = orphanId;
54755
- break;
54756
- }
54757
- }
55300
+ matchedId = firstCollectedNamed(expectedName);
54758
55301
  if (!matchedId) {
54759
- for (const [orphanId, orphanResp] of collectedResponses) {
54760
- if (orphanResp.functionResponse?.name === "unknown_function") {
54761
- matchedId = orphanId;
54762
- break;
54763
- }
54764
- }
55302
+ matchedId = firstCollectedNamed("unknown_function");
54765
55303
  }
54766
55304
  if (!matchedId) {
54767
55305
  matchedId = collectedResponses.keys().next().value ?? null;
@@ -54773,7 +55311,7 @@ function fixToolResponseGrouping(contents) {
54773
55311
  if (orphanResp.functionResponse.name === "unknown_function" && expectedName) {
54774
55312
  orphanResp.functionResponse.name = expectedName;
54775
55313
  }
54776
- log12.debug("Auto-repaired tool ID mismatch", {
55314
+ log13.debug("Auto-repaired tool ID mismatch", {
54777
55315
  mappedFrom: matchedId,
54778
55316
  mappedTo: expectedId,
54779
55317
  functionName: expectedName
@@ -54793,7 +55331,7 @@ function fixToolResponseGrouping(contents) {
54793
55331
  id: expectedId
54794
55332
  }
54795
55333
  };
54796
- log12.debug("Created placeholder response for missing tool", {
55334
+ log13.debug("Created placeholder response for missing tool", {
54797
55335
  id: expectedId,
54798
55336
  name: expectedName
54799
55337
  });
@@ -54801,13 +55339,20 @@ function fixToolResponseGrouping(contents) {
54801
55339
  }
54802
55340
  }
54803
55341
  if (groupResponses.length > 0) {
54804
- newContents.splice(group.insertAfterIdx + 1, 0, {
55342
+ insertedAfter.set(group.insertAfterIdx, {
54805
55343
  parts: groupResponses,
54806
55344
  role: "user"
54807
55345
  });
54808
55346
  }
54809
55347
  }
54810
- return newContents;
55348
+ if (insertedAfter.size === 0) return newContents;
55349
+ const withRecovered = [];
55350
+ for (let i = 0; i < newContents.length; i++) {
55351
+ withRecovered.push(newContents[i]);
55352
+ const recovered = insertedAfter.get(i);
55353
+ if (recovered) withRecovered.push(recovered);
55354
+ }
55355
+ return withRecovered;
54811
55356
  }
54812
55357
  function findOrphanedToolUseIds(messages) {
54813
55358
  const toolUseIds = /* @__PURE__ */ new Set();
@@ -55111,7 +55656,7 @@ function applyToolPairingFixes(payload, isClaude) {
55111
55656
  );
55112
55657
  payload.contents = fixToolResponseGrouping(contentsWithMatchedIds);
55113
55658
  contentsFixed = true;
55114
- log12.debug("Applied tool pairing fixes to contents[]", {
55659
+ log13.debug("Applied tool pairing fixes to contents[]", {
55115
55660
  originalLength: payload.contents.length
55116
55661
  });
55117
55662
  }
@@ -55120,7 +55665,7 @@ function applyToolPairingFixes(payload, isClaude) {
55120
55665
  payload.messages
55121
55666
  );
55122
55667
  messagesFixed = true;
55123
- log12.debug("Applied tool pairing fixes to messages[]", {
55668
+ log13.debug("Applied tool pairing fixes to messages[]", {
55124
55669
  originalLength: payload.messages.length
55125
55670
  });
55126
55671
  }
@@ -55719,10 +56264,10 @@ init_dist();
55719
56264
  init_dist();
55720
56265
 
55721
56266
  // src/plugin/request.ts
55722
- var log13 = createLogger4("request");
56267
+ var log14 = createLogger4("request");
55723
56268
  var PLUGIN_SESSION_ID = `-${crypto2.randomUUID()}`;
55724
56269
  var DEFAULT_AGY_REQUEST_SESSION = createAgyRequestSessionContext();
55725
- var sessionDisplayedThinkingHashes = /* @__PURE__ */ new Set();
56270
+ var openCode1DisplayedThinking = createDisplayedThinkingRegistry();
55726
56271
  var MIN_SIGNATURE_LENGTH = 50;
55727
56272
  var AGY_CLAUDE_THINKING_BUDGET = 1024;
55728
56273
  var ANTIGRAVITY_ENVELOPE_FIELD_ORDER = [
@@ -55868,6 +56413,9 @@ function ensureThinkingFields(obj) {
55868
56413
  ensureThinkingFields(val);
55869
56414
  }
55870
56415
  }
56416
+ function systemInstructionOf(request2) {
56417
+ return request2 && typeof request2 === "object" ? request2.systemInstruction : void 0;
56418
+ }
55871
56419
  function safeStringify(obj) {
55872
56420
  ensureThinkingFields(obj);
55873
56421
  return JSON.stringify(obj, thinkingSafeReplacer);
@@ -56120,9 +56668,6 @@ function stripUnsupportedAntigravityFields(payload) {
56120
56668
  }
56121
56669
  }
56122
56670
  }
56123
- function isGeminiFunctionResponseTurn(content, wireModel) {
56124
- return wireModel.startsWith("gemini-") && content?.role === "model" && Array.isArray(content.parts) && content.parts.length > 0 && content.parts.every((part) => part?.functionResponse);
56125
- }
56126
56671
  function configureAntigravityToolCalling(payload) {
56127
56672
  delete payload.toolConfig;
56128
56673
  if (Array.isArray(payload.tools)) {
@@ -56542,9 +57087,9 @@ var openCode1WireLocation = {
56542
57087
  logAntigravityDebugResponse: (context, response, meta) => logAntigravityDebugResponse(context, response, meta),
56543
57088
  logCacheStats: (model, cacheRead, cacheWrite, totalInput) => logCacheStats(model, cacheRead, cacheWrite, totalInput)
56544
57089
  },
56545
- logger: log13,
57090
+ logger: log14,
56546
57091
  sessionFingerprint: () => getSessionFingerprint(),
56547
- displayedThinkingHashes: sessionDisplayedThinkingHashes,
57092
+ displayedThinking: openCode1DisplayedThinking,
56548
57093
  cacheStats: { last: null }
56549
57094
  };
56550
57095
  function getLastCacheStats() {
@@ -56569,6 +57114,7 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56569
57114
  let sessionId;
56570
57115
  let needsSignedThinkingWarmup = false;
56571
57116
  let thinkingRecoveryMessage;
57117
+ let wireSystemInstruction;
56572
57118
  if (!isGenerativeLanguageRequest(input2)) {
56573
57119
  return {
56574
57120
  request: input2,
@@ -56601,9 +57147,9 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56601
57147
  }
56602
57148
  const [, rawModel = "", rawAction = ""] = match;
56603
57149
  const requestedModel = rawModel;
56604
- const hydrogenTier = isGeminiHydrogenModel(rawModel) ? options?.variant?.thinkingLevel : void 0;
57150
+ const geminiTier = supportsGeminiXHigh(rawModel) ? options?.variant?.thinkingLevel : void 0;
56605
57151
  const resolved = resolveAntigravityModel(
56606
- hydrogenTier ? `${rawModel.replace(/-(low|medium|high|xhigh)$/i, "")}-${hydrogenTier}` : rawModel
57152
+ geminiTier ? `${rawModel.replace(/-(low|medium|high|xhigh)$/i, "")}-${geminiTier}` : rawModel
56607
57153
  );
56608
57154
  let effectiveModel = resolved.actualModel;
56609
57155
  const streaming = rawAction === STREAM_ACTION;
@@ -56697,13 +57243,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56697
57243
  normalizeNativeFunctionResponseRoles(req, effectiveModel);
56698
57244
  }
56699
57245
  for (const req of requestObjects) {
56700
- if (Array.isArray(req.contents)) {
56701
- const contents = req.contents;
56702
- const lastContent = contents[contents.length - 1];
56703
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
56704
- contents.push({ role: "user", parts: [{ text: "[Continue]" }] });
56705
- }
56706
- }
57246
+ if (Array.isArray(req.contents))
57247
+ appendAgyContinuation(req.contents, effectiveModel);
56707
57248
  if (Array.isArray(req.messages)) {
56708
57249
  const messages = req.messages;
56709
57250
  const lastMessage = messages[messages.length - 1];
@@ -56753,6 +57294,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56753
57294
  }
56754
57295
  }
56755
57296
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
57297
+ wireSystemInstruction = {
57298
+ body,
57299
+ instruction: systemInstructionOf(wrappedBody.request)
57300
+ };
56756
57301
  } else {
56757
57302
  const requestPayload = { ...parsedBody };
56758
57303
  if (isImageGenerationModel(effectiveModel) && isOpenCodeTitleGenerationRequest(requestPayload)) {
@@ -56774,9 +57319,9 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56774
57319
  `[ThinkingResolution] rawModel=${rawModel} resolvedModel=${effectiveModel} resolvedTier=${tierThinkingLevel ?? "none"} variantLevel=${variantConfig?.thinkingLevel ?? "none"} variantBudget=${variantConfig?.thinkingBudget ?? "none"} providerOptions.google=${JSON.stringify(requestPayload.providerOptions?.google ?? null)} generationConfig.thinkingConfig=${JSON.stringify(rawGenerationConfig?.thinkingConfig ?? null)}`
56775
57320
  );
56776
57321
  delete requestPayload.providerOptions;
56777
- if (variantConfig?.thinkingLevel && (isGemini3 || isGeminiArgonModel(effectiveModel) || isGeminiCarbonModel(effectiveModel) || isGeminiHydrogenModel(effectiveModel) || getAgyNativeModel(effectiveModel)?.supportsAdaptiveThinking)) {
57322
+ if (variantConfig?.thinkingLevel && (isGemini3 || isGeminiArgonModel(effectiveModel) || isGeminiCarbonModel(effectiveModel) || supportsGeminiXHigh(effectiveModel) || getAgyNativeModel(effectiveModel)?.supportsAdaptiveThinking)) {
56778
57323
  const variantModelBase = rawModel.replace(/-preview-customtools$/i, "").replace(/-preview$/i, "").replace(
56779
- isGeminiHydrogenModel(effectiveModel) ? /-(low|medium|high|xhigh)$/i : /-(minimal|low|medium|high)$/i,
57324
+ supportsGeminiXHigh(effectiveModel) ? /-(low|medium|high|xhigh)$/i : /-(minimal|low|medium|high)$/i,
56780
57325
  ""
56781
57326
  );
56782
57327
  const variantResolved = resolveAntigravityModel(
@@ -57139,15 +57684,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57139
57684
  wire.signatures.signatureStore.delete(signatureSessionKey);
57140
57685
  }
57141
57686
  }
57142
- if (Array.isArray(requestPayload.contents)) {
57143
- const lastContent = requestPayload.contents[requestPayload.contents.length - 1];
57144
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
57145
- requestPayload.contents.push({
57146
- role: "user",
57147
- parts: [{ text: "[Continue]" }]
57148
- });
57149
- }
57150
- }
57687
+ if (Array.isArray(requestPayload.contents))
57688
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
57151
57689
  if (Array.isArray(requestPayload.messages)) {
57152
57690
  const lastMessage = requestPayload.messages[requestPayload.messages.length - 1];
57153
57691
  if (lastMessage?.role === "model" || lastMessage?.role === "assistant") {
@@ -57175,15 +57713,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57175
57713
  stripUnsupportedAntigravityFields(requestPayload);
57176
57714
  configureAntigravityToolCalling(requestPayload);
57177
57715
  normalizeNativeFunctionResponseRoles(requestPayload, effectiveModel);
57178
- if (Array.isArray(requestPayload.contents)) {
57179
- const lastContent = requestPayload.contents.at(-1);
57180
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel)) {
57181
- requestPayload.contents.push({
57182
- role: "user",
57183
- parts: [{ text: "[Continue]" }]
57184
- });
57185
- }
57186
- }
57716
+ if (Array.isArray(requestPayload.contents))
57717
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
57187
57718
  }
57188
57719
  const effectiveProjectId = projectId?.trim() || ANTIGRAVITY_DEFAULT_PROJECT_ID;
57189
57720
  resolvedProjectId = effectiveProjectId;
@@ -57208,6 +57739,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57208
57739
  requestType: "agent"
57209
57740
  };
57210
57741
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
57742
+ wireSystemInstruction = {
57743
+ body,
57744
+ instruction: requestPayload.systemInstruction
57745
+ };
57211
57746
  }
57212
57747
  } catch {
57213
57748
  throw new Error("Failed to build Antigravity request body");
@@ -57251,7 +57786,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57251
57786
  toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
57252
57787
  needsSignedThinkingWarmup,
57253
57788
  headerStyle: "antigravity",
57254
- thinkingRecoveryMessage
57789
+ thinkingRecoveryMessage,
57790
+ ...wireSystemInstruction ? { wireSystemInstruction } : {}
57255
57791
  };
57256
57792
  }
57257
57793
  function prepareAntigravityRequest(...args) {
@@ -57369,7 +57905,7 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
57369
57905
  signatureSessionKey: sessionId,
57370
57906
  debugText,
57371
57907
  cacheSignatures,
57372
- displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinkingHashes : void 0
57908
+ displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinking.forSession(sessionId) : void 0
57373
57909
  // injectSyntheticThinking removed - keep_thinking now unified with debug via debugText
57374
57910
  }
57375
57911
  );
@@ -57730,10 +58266,10 @@ async function retainResponseLifetime(response, cancellation) {
57730
58266
  cancellation.release();
57731
58267
  throw error;
57732
58268
  }
57733
- let resolve33 = () => {
58269
+ let resolve34 = () => {
57734
58270
  };
57735
58271
  const settled = new Promise((done) => {
57736
- resolve33 = done;
58272
+ resolve34 = done;
57737
58273
  });
57738
58274
  let stopping = false;
57739
58275
  let finished = false;
@@ -57743,7 +58279,7 @@ async function retainResponseLifetime(response, cancellation) {
57743
58279
  finished = true;
57744
58280
  cancellation.signal.removeEventListener("abort", abort);
57745
58281
  cancellation.release();
57746
- resolve33();
58282
+ resolve34();
57747
58283
  };
57748
58284
  const abort = () => {
57749
58285
  if (finished || stopping) return;
@@ -57812,8 +58348,8 @@ function createAfterHandoff(work, signals, onFailure) {
57812
58348
  let running = false;
57813
58349
  let resolveCompletion = () => {
57814
58350
  };
57815
- const completion = new Promise((resolve33) => {
57816
- resolveCompletion = resolve33;
58351
+ const completion = new Promise((resolve34) => {
58352
+ resolveCompletion = resolve34;
57817
58353
  });
57818
58354
  const finish = () => {
57819
58355
  if (finished) return;
@@ -57860,14 +58396,14 @@ function createAfterHandoff(work, signals, onFailure) {
57860
58396
  };
57861
58397
  }
57862
58398
  function publishResponse(dispatch) {
57863
- return new Promise((resolve33, reject) => {
58399
+ return new Promise((resolve34, reject) => {
57864
58400
  let acknowledge;
57865
58401
  void Promise.resolve().then(
57866
58402
  () => dispatch((callback) => {
57867
58403
  acknowledge = callback;
57868
58404
  })
57869
58405
  ).then((response) => {
57870
- resolve33(response);
58406
+ resolve34(response);
57871
58407
  acknowledge?.();
57872
58408
  }, reject);
57873
58409
  });
@@ -57875,7 +58411,7 @@ function publishResponse(dispatch) {
57875
58411
 
57876
58412
  // src/plugin/auth-loader.ts
57877
58413
  init_storage();
57878
- var log14 = createLogger4("auth-loader");
58414
+ var log15 = createLogger4("auth-loader");
57879
58415
  var failureLog = createLogger("auth-loader");
57880
58416
  function loaderFailure(error) {
57881
58417
  if (error instanceof RuntimeLayoutRefusal) return error;
@@ -57958,16 +58494,21 @@ function createAuthLoader({
57958
58494
  };
57959
58495
  let storeOpening = null;
57960
58496
  const openStore = () => {
57961
- storeOpening ??= deps.openAccountStore().then((opening) => {
57962
- if (opening.status === "ready") {
57963
- lifecycle.register({
57964
- async dispose() {
57965
- await opening.repository.dispose();
57966
- }
57967
- });
57968
- }
57969
- return opening;
57970
- });
58497
+ if (!storeOpening) {
58498
+ const attempt = deps.openAccountStore().then((opening) => {
58499
+ if (opening.status === "ready") {
58500
+ lifecycle.register({
58501
+ async dispose() {
58502
+ await opening.repository.dispose();
58503
+ }
58504
+ });
58505
+ } else if (opening.status === "refused" && opening.admission.status === "busy" && opening.admission.retryable && storeOpening === attempt) {
58506
+ storeOpening = null;
58507
+ }
58508
+ return opening;
58509
+ });
58510
+ storeOpening = attempt;
58511
+ }
57971
58512
  return storeOpening;
57972
58513
  };
57973
58514
  const initializeFreshStore = async () => {
@@ -58047,7 +58588,7 @@ function createAuthLoader({
58047
58588
  });
58048
58589
  refreshQueue = deps.createStoreRefreshQueue(
58049
58590
  {
58050
- logger: log14,
58591
+ logger: log15,
58051
58592
  refreshToken: (_auth, account) => credentials.refresh(account)
58052
58593
  },
58053
58594
  queueConfig
@@ -58155,7 +58696,7 @@ function createAuthLoader({
58155
58696
  }
58156
58697
  if (opening.status === "ready") {
58157
58698
  if (!isOAuthAuth(auth) && !readAuthority) {
58158
- log14.warn(
58699
+ log15.warn(
58159
58700
  "The host holds no Antigravity sign-in; the account store is left untouched"
58160
58701
  );
58161
58702
  return {};
@@ -58214,12 +58755,12 @@ function createAuthLoader({
58214
58755
  expires: auth.expires ?? 0
58215
58756
  }
58216
58757
  });
58217
- log14.info("Restored Antigravity OAuth auth from account storage", {
58758
+ log15.info("Restored Antigravity OAuth auth from account storage", {
58218
58759
  reason: drift.reason,
58219
58760
  email: drift.account.email
58220
58761
  });
58221
58762
  } catch (error) {
58222
- log14.warn(
58763
+ log15.warn(
58223
58764
  "Failed to restore Antigravity OAuth auth from account storage",
58224
58765
  { error: String(error) }
58225
58766
  );
@@ -58465,16 +59006,10 @@ var BackgroundQuotaRefresh = class {
58465
59006
  if (this.timer.unref) this.timer.unref();
58466
59007
  }
58467
59008
  async runTick() {
58468
- if (this.mayRun && !await this.mayRun()) {
59009
+ if (!await this.canRun()) {
58469
59010
  if (!this.disposed) this.scheduleNext(this.jitteredInterval());
58470
59011
  return;
58471
59012
  }
58472
- if (this.disposed) return;
58473
- const freshnessThresholdMs = Math.max(
58474
- this.intervalMs - MIN_INTERVAL_MS,
58475
- Math.floor(this.intervalMs / 2)
58476
- );
58477
- const ageMs = this.now() - this.snapshots.lastCheckedAt();
58478
59013
  const lockPath = this.snapshots.pollLockPath;
58479
59014
  let lock = null;
58480
59015
  try {
@@ -58492,9 +59027,7 @@ var BackgroundQuotaRefresh = class {
58492
59027
  return;
58493
59028
  }
58494
59029
  try {
58495
- if (this.disposed || this.mayRun && !await this.mayRun()) return;
58496
- if (ageMs >= freshnessThresholdMs) await this.refresh();
58497
- else await this.refreshTierSlot();
59030
+ if (await this.canRun()) await this.refresh();
58498
59031
  } finally {
58499
59032
  await lock.release().catch(() => {
58500
59033
  });
@@ -58503,22 +59036,36 @@ var BackgroundQuotaRefresh = class {
58503
59036
  this.scheduleNext(this.jitteredInterval());
58504
59037
  }
58505
59038
  }
59039
+ async canRun() {
59040
+ return !this.disposed && (!this.mayRun || await this.mayRun()) && !this.disposed;
59041
+ }
58506
59042
  async refresh() {
58507
59043
  const refreshedQuota = await this.refreshQuota();
58508
- if (!this.disposed && (!this.mayRun || await this.mayRun()))
58509
- await this.refreshTierSlot();
58510
- if (refreshedQuota) await this.pushSnapshot();
59044
+ if (await this.canRun()) await this.refreshTierSlot();
59045
+ if (refreshedQuota && await this.canRun()) await this.pushSnapshot();
58511
59046
  }
58512
59047
  async refreshQuota() {
58513
- if (this.disposed || this.mayRun && !await this.mayRun()) return false;
58514
59048
  const manager = this.getAccountManager();
58515
59049
  if (!manager) return false;
58516
- const accounts = manager.getAccountsForQuotaCheck();
59050
+ const observed = await (manager.readAccountsForQuotaPoll?.() ?? this.localObservations(manager));
59051
+ if (!await this.canRun()) return false;
59052
+ const now2 = this.now();
59053
+ const freshnessThresholdMs = Math.max(
59054
+ this.intervalMs - MIN_INTERVAL_MS,
59055
+ Math.floor(this.intervalMs / 2)
59056
+ );
59057
+ const accounts = observed.filter(
59058
+ ({ enabled, cachedQuotaUpdatedAt: at }) => enabled !== false && (at === void 0 || !Number.isFinite(at) || at <= 0 || at > now2 || now2 - at >= freshnessThresholdMs)
59059
+ );
58517
59060
  if (accounts.length === 0) return false;
58518
59061
  let results;
58519
59062
  try {
59063
+ const indexes = new Map(
59064
+ accounts.map((account, index) => [account, index])
59065
+ );
58520
59066
  results = await this.quotaManager.refreshAccounts(accounts, {
58521
- indexFor: (account) => accounts.indexOf(account),
59067
+ indexFor: (account) => indexes.get(account),
59068
+ publishSidebar: false,
58522
59069
  // Do not force: the quota manager's per-account dedup and backoff
58523
59070
  // apply — an account that already refreshed recently is skipped.
58524
59071
  force: false
@@ -58526,7 +59073,7 @@ var BackgroundQuotaRefresh = class {
58526
59073
  } catch {
58527
59074
  return false;
58528
59075
  }
58529
- if (this.disposed) return false;
59076
+ if (!await this.canRun()) return false;
58530
59077
  const liveAccounts = manager.getAccounts();
58531
59078
  const liveIndexByToken = /* @__PURE__ */ new Map();
58532
59079
  for (const entry of liveAccounts) {
@@ -58535,7 +59082,8 @@ var BackgroundQuotaRefresh = class {
58535
59082
  let anyUpdated = false;
58536
59083
  for (let i = 0; i < results.length; i++) {
58537
59084
  const result = results[i];
58538
- if (result?.status !== "ok" || !result.quota?.groups) continue;
59085
+ if (result?.status !== "ok" || !result.quota?.groups || result.checkedAt === void 0)
59086
+ continue;
58539
59087
  const candidateTokens = [
58540
59088
  result.updatedAccount?.refreshToken,
58541
59089
  accounts[i]?.refreshToken
@@ -58544,7 +59092,13 @@ var BackgroundQuotaRefresh = class {
58544
59092
  if (liveIndex === void 0) continue;
58545
59093
  const liveToken = liveAccounts[liveIndex]?.parts.refreshToken;
58546
59094
  if (!liveToken) continue;
58547
- manager.updateQuotaCache(liveIndex, result.quota.groups, liveToken);
59095
+ if (manager.updateQuotaCache(
59096
+ liveIndex,
59097
+ result.quota.groups,
59098
+ liveToken,
59099
+ result.checkedAt
59100
+ ) === false)
59101
+ continue;
58548
59102
  const uaTier = toCapturedTier(result.updatedAccount ?? {});
58549
59103
  if (uaTier !== void 0) {
58550
59104
  manager.applyUpdatedAccount(
@@ -58560,9 +59114,24 @@ var BackgroundQuotaRefresh = class {
58560
59114
  }
58561
59115
  anyUpdated = true;
58562
59116
  }
58563
- if (anyUpdated) manager.requestSaveToDisk();
59117
+ if (anyUpdated && await this.canRun()) {
59118
+ if (manager.saveToDisk) await manager.saveToDisk();
59119
+ else manager.requestSaveToDisk();
59120
+ }
58564
59121
  return true;
58565
59122
  }
59123
+ localObservations(manager) {
59124
+ const accounts = new Map(
59125
+ manager.getAccounts().map((row) => [row.parts.refreshToken, row])
59126
+ );
59127
+ return manager.getAccountsForQuotaCheck().map((target) => {
59128
+ const row = accounts.get(target.refreshToken);
59129
+ return {
59130
+ ...target,
59131
+ cachedQuotaUpdatedAt: row?.cachedQuota && row.cachedQuotaUpdatedAt
59132
+ };
59133
+ });
59134
+ }
58566
59135
  async refreshTierSlot() {
58567
59136
  if (this.disposed || !this.loadAccountTier) return;
58568
59137
  const manager = this.getAccountManager();
@@ -58587,7 +59156,7 @@ var BackgroundQuotaRefresh = class {
58587
59156
  if (!accountForTier) return;
58588
59157
  try {
58589
59158
  const tier = await this.loadAccountTier(accountForTier);
58590
- if (tier === null || this.disposed) return;
59159
+ if (tier === null || !await this.canRun()) return;
58591
59160
  const liveEntry = manager.getAccounts().find((entry) => entry.parts.refreshToken === refreshToken);
58592
59161
  if (!liveEntry) return;
58593
59162
  manager.applyUpdatedAccount(
@@ -58623,6 +59192,7 @@ var BackgroundQuotaRefresh = class {
58623
59192
  enabled: entry.enabled,
58624
59193
  coolingDownUntil: entry.coolingDownUntil,
58625
59194
  cachedQuota: entry.cachedQuota,
59195
+ cachedQuotaUpdatedAt: entry.cachedQuotaUpdatedAt,
58626
59196
  cachedQuotaAccountId: entry.cachedQuotaAccountId,
58627
59197
  // An account reorder changes which cached reading occupies an index.
58628
59198
  // Use a refresh-token-derived account ID to detect that mismatch
@@ -58886,12 +59456,12 @@ var BackgroundVaultQuotaRefresh = class {
58886
59456
  outcome.reason = "no-rows";
58887
59457
  return;
58888
59458
  }
58889
- const due = pool.selector.rows.some((row) => {
59459
+ const dueRoutes = pool.selector.rows.filter((row) => {
58890
59460
  const quota = quotaReadingForVaultRoute(row.route, state2);
58891
59461
  const at = quota?.cachedQuotaUpdatedAt;
58892
59462
  return quota?.cachedQuota == null || typeof at !== "number" || !Number.isFinite(at) || at < 0 || now2 - at >= threshold;
58893
- });
58894
- if (!due) {
59463
+ }).map((row) => row.route);
59464
+ if (dueRoutes.length === 0) {
58895
59465
  outcome.reason = "fresh";
58896
59466
  return;
58897
59467
  }
@@ -58900,6 +59470,7 @@ var BackgroundVaultQuotaRefresh = class {
58900
59470
  const report = await checkAndPublishVaultQuota(
58901
59471
  {
58902
59472
  pool,
59473
+ routes: dueRoutes,
58903
59474
  signal: controller.signal,
58904
59475
  now: this.now,
58905
59476
  onStage: (stage) => {
@@ -59545,15 +60116,15 @@ init_debug();
59545
60116
  // src/plugin/dependencies.ts
59546
60117
  init_dist();
59547
60118
  import { homedir as homedir16 } from "node:os";
59548
- import { join as join45 } from "node:path";
60119
+ import { join as join44 } from "node:path";
59549
60120
  function defaultFilesystemRoots() {
59550
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join45(homedir16(), ".config");
59551
- const xdgState2 = process.env.XDG_STATE_HOME ?? join45(homedir16(), ".local", "state");
60121
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join44(homedir16(), ".config");
60122
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join44(homedir16(), ".local", "state");
59552
60123
  return {
59553
60124
  projectRoot: process.cwd(),
59554
- userConfigRoot: join45(xdgConfig2, "opencode"),
59555
- sidebarStateRoot: join45(xdgState2, "cortexkit", "antigravity-auth"),
59556
- rpcRoot: join45(xdgState2, "cortexkit", "antigravity-auth", "rpc")
60125
+ userConfigRoot: join44(xdgConfig2, "opencode"),
60126
+ sidebarStateRoot: join44(xdgState2, "cortexkit", "antigravity-auth"),
60127
+ rpcRoot: join44(xdgState2, "cortexkit", "antigravity-auth", "rpc")
59557
60128
  };
59558
60129
  }
59559
60130
  function resolvePluginDependencies(overrides = {}) {
@@ -59582,10 +60153,10 @@ function resolvePluginDependencies(overrides = {}) {
59582
60153
  }
59583
60154
  async function defaultSleep(ms, signal) {
59584
60155
  if (ms <= 0) return;
59585
- await new Promise((resolve33, reject) => {
60156
+ await new Promise((resolve34, reject) => {
59586
60157
  const timer = setTimeout(() => {
59587
60158
  signal?.removeEventListener("abort", onAbort);
59588
- resolve33();
60159
+ resolve34();
59589
60160
  }, ms);
59590
60161
  timer.unref?.();
59591
60162
  const onAbort = () => {
@@ -59834,8 +60405,6 @@ function candidateView(candidates) {
59834
60405
  accounts.push({ account_id: accountId, credential_id: credentialId });
59835
60406
  }
59836
60407
  }
59837
- if (accounts.length === 0)
59838
- return void 0;
59839
60408
  const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
59840
60409
  `, "utf8")).sort(Buffer.compare);
59841
60410
  const hash2 = createHash22("sha256");
@@ -59912,8 +60481,8 @@ async function askRouting(input2) {
59912
60481
  return void 0;
59913
60482
  const requested = input2.deadlineMs ?? 1500;
59914
60483
  const deadlineMs = Number.isNaN(requested) ? 1500 : Math.min(2e3, Math.max(1, requested));
59915
- const expired = new Promise((resolve33) => {
59916
- timer = setTimeout(() => resolve33(void 0), deadlineMs);
60484
+ const expired = new Promise((resolve34) => {
60485
+ timer = setTimeout(() => resolve34(void 0), deadlineMs);
59917
60486
  timer.unref();
59918
60487
  });
59919
60488
  const cap = input2.holdWaitMaxS;
@@ -59927,7 +60496,7 @@ async function askRouting(input2) {
59927
60496
  request2.warm_credential = warmCredentialId;
59928
60497
  }
59929
60498
  const candidates = candidateView(input2.candidates);
59930
- if (candidates)
60499
+ if (candidates.accounts.length > 0 || request2.mode === "continue")
59931
60500
  request2.candidates = candidates;
59932
60501
  const pending = accountFor.call(handle, request2, { deadlineMs });
59933
60502
  if (!isObject2(pending) || typeof pending.then !== "function")
@@ -60303,7 +60872,7 @@ function createRetryState() {
60303
60872
  var MAX_WARMUP_SESSIONS = 1e3;
60304
60873
  var MAX_WARMUP_RETRIES = 2;
60305
60874
  function createWarmupState() {
60306
- const warmupAttemptedSessionIds = /* @__PURE__ */ new Set();
60875
+ const warmupAttemptCounts = /* @__PURE__ */ new Map();
60307
60876
  const warmupSucceededSessionIds = /* @__PURE__ */ new Set();
60308
60877
  let disposed = false;
60309
60878
  function trackAttempt(sessionId) {
@@ -60311,22 +60880,22 @@ function createWarmupState() {
60311
60880
  if (warmupSucceededSessionIds.has(sessionId)) {
60312
60881
  return false;
60313
60882
  }
60314
- if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
60315
- const first = warmupAttemptedSessionIds.values().next().value;
60316
- if (first) {
60317
- warmupAttemptedSessionIds.delete(first);
60318
- warmupSucceededSessionIds.delete(first);
60319
- }
60320
- }
60321
60883
  const attempts2 = getAttemptCount(sessionId);
60322
60884
  if (attempts2 >= MAX_WARMUP_RETRIES) {
60323
60885
  return false;
60324
60886
  }
60325
- warmupAttemptedSessionIds.add(sessionId);
60887
+ if (attempts2 === 0 && warmupAttemptCounts.size >= MAX_WARMUP_SESSIONS) {
60888
+ const first = warmupAttemptCounts.keys().next().value;
60889
+ if (first !== void 0) {
60890
+ warmupAttemptCounts.delete(first);
60891
+ warmupSucceededSessionIds.delete(first);
60892
+ }
60893
+ }
60894
+ warmupAttemptCounts.set(sessionId, attempts2 + 1);
60326
60895
  return true;
60327
60896
  }
60328
60897
  function getAttemptCount(sessionId) {
60329
- return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
60898
+ return warmupAttemptCounts.get(sessionId) ?? 0;
60330
60899
  }
60331
60900
  function markSuccess(sessionId) {
60332
60901
  if (disposed) return;
@@ -60336,12 +60905,14 @@ function createWarmupState() {
60336
60905
  if (first) warmupSucceededSessionIds.delete(first);
60337
60906
  }
60338
60907
  }
60339
- function clearWarmupAttempt(sessionId) {
60908
+ function refundAttempt(sessionId) {
60340
60909
  if (disposed) return;
60341
- warmupAttemptedSessionIds.delete(sessionId);
60910
+ const attempts2 = getAttemptCount(sessionId);
60911
+ if (attempts2 <= 1) warmupAttemptCounts.delete(sessionId);
60912
+ else warmupAttemptCounts.set(sessionId, attempts2 - 1);
60342
60913
  }
60343
60914
  function clear() {
60344
- warmupAttemptedSessionIds.clear();
60915
+ warmupAttemptCounts.clear();
60345
60916
  warmupSucceededSessionIds.clear();
60346
60917
  }
60347
60918
  function dispose() {
@@ -60356,7 +60927,7 @@ function createWarmupState() {
60356
60927
  trackAttempt,
60357
60928
  getAttemptCount,
60358
60929
  markSuccess,
60359
- clearWarmupAttempt,
60930
+ refundAttempt,
60360
60931
  clear,
60361
60932
  dispose
60362
60933
  };
@@ -60847,6 +61418,7 @@ function isTitleVaultRequest(kind, headers) {
60847
61418
  var FIRST_RETRY_DELAY_MS = 1e3;
60848
61419
  var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
60849
61420
  var ROUTING_ASK_DEADLINE_MS = 2e3;
61421
+ var FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS = 5;
60850
61422
  var REFUSAL_BODY_TIMEOUT_MS = 2e3;
60851
61423
  var REFUSAL_BODY_MAX_BYTES = 64 * 1024;
60852
61424
  async function readRefusalBody(response, deadline) {
@@ -60875,8 +61447,8 @@ async function readRefusalBody(response, deadline) {
60875
61447
  return false;
60876
61448
  }
60877
61449
  })(),
60878
- new Promise((resolve33) => {
60879
- timer = setTimeout(() => resolve33(false), REFUSAL_BODY_TIMEOUT_MS);
61450
+ new Promise((resolve34) => {
61451
+ timer = setTimeout(() => resolve34(false), REFUSAL_BODY_TIMEOUT_MS);
60880
61452
  })
60881
61453
  ])
60882
61454
  );
@@ -60992,7 +61564,7 @@ function formatWaitTime(ms) {
60992
61564
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
60993
61565
  }
60994
61566
  function sleep4(ms, signal) {
60995
- return new Promise((resolve33, reject) => {
61567
+ return new Promise((resolve34, reject) => {
60996
61568
  if (signal?.aborted) {
60997
61569
  reject(
60998
61570
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -61002,7 +61574,7 @@ function sleep4(ms, signal) {
61002
61574
  const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
61003
61575
  const timeout = setTimeout(() => {
61004
61576
  cleanup2();
61005
- resolve33();
61577
+ resolve34();
61006
61578
  }, timerMs);
61007
61579
  const onAbort = () => {
61008
61580
  cleanup2();
@@ -61055,7 +61627,7 @@ async function withRoutingWaitReports(cancellation, run) {
61055
61627
  finish(cancellation.aborted ? "cancelled" : "abandoned");
61056
61628
  }
61057
61629
  }
61058
- function createLocalQuotaRefresh(accountManager, quotaManager, log18) {
61630
+ function createLocalQuotaRefresh(accountManager, quotaManager, log19) {
61059
61631
  return async function refreshQuotaAfterSuccess(account, intervalMinutes, signal) {
61060
61632
  if (intervalMinutes <= 0) return;
61061
61633
  const accountIndex = accountManager.getAccounts().indexOf(account);
@@ -61075,18 +61647,19 @@ function createLocalQuotaRefresh(accountManager, quotaManager, log18) {
61075
61647
  ...signal ? { signal } : {}
61076
61648
  });
61077
61649
  if (signal?.aborted) return;
61078
- if (result.status === "ok" && result.quota?.groups) {
61650
+ if (result.status === "ok" && result.quota?.groups && result.checkedAt !== void 0) {
61079
61651
  const currentIndex = accountManager.getAccounts().indexOf(account);
61080
61652
  if (currentIndex === -1) return;
61081
- accountManager.updateQuotaCache(
61653
+ if (accountManager.updateQuotaCache(
61082
61654
  currentIndex,
61083
61655
  result.quota.groups,
61084
- expectedRefreshToken
61085
- );
61086
- accountManager.requestSaveToDisk();
61656
+ expectedRefreshToken,
61657
+ result.checkedAt
61658
+ ))
61659
+ accountManager.requestSaveToDisk();
61087
61660
  }
61088
61661
  } catch (err) {
61089
- log18.debug(
61662
+ log19.debug(
61090
61663
  `quota-refresh-failed ${singleAccount ? quotaManager.hashedLogLabel("account", singleAccount) : `idx-${accountIndex}`}`,
61091
61664
  { error: String(err) }
61092
61665
  );
@@ -61105,7 +61678,7 @@ function createRequestExecutor(deps) {
61105
61678
  wire,
61106
61679
  debug,
61107
61680
  dump,
61108
- logger: log18,
61681
+ logger: log19,
61109
61682
  trackers,
61110
61683
  classifyAccessError,
61111
61684
  notify,
@@ -61156,7 +61729,7 @@ function createRequestExecutor(deps) {
61156
61729
  const entries = unavailableModels.get(key2);
61157
61730
  const entry = entries?.get(model);
61158
61731
  if (!entries || !entry) return;
61159
- log18.debug("model-unavailable-memory-drop", {
61732
+ log19.debug("model-unavailable-memory-drop", {
61160
61733
  account: entry.label,
61161
61734
  model,
61162
61735
  cause
@@ -61196,7 +61769,7 @@ function createRequestExecutor(deps) {
61196
61769
  ...entry,
61197
61770
  recordedAt: modelAvailabilityNow()
61198
61771
  });
61199
- log18.debug("model-unavailable-memory-record", {
61772
+ log19.debug("model-unavailable-memory-record", {
61200
61773
  account: entry.label,
61201
61774
  model
61202
61775
  });
@@ -61209,10 +61782,22 @@ function createRequestExecutor(deps) {
61209
61782
  let retired = false;
61210
61783
  let drainPromise;
61211
61784
  let disposePromise;
61785
+ let warnedConditionReceipt = false;
61786
+ const runVaultCondition = (operation) => {
61787
+ void Promise.resolve().then(operation).catch((error) => {
61788
+ if (warnedConditionReceipt || !(error instanceof Error) || !("kind" in error) || error.kind !== "no-receipt")
61789
+ return;
61790
+ warnedConditionReceipt = true;
61791
+ try {
61792
+ log19.warn("vault-condition-no-receipt");
61793
+ } catch {
61794
+ }
61795
+ });
61796
+ };
61212
61797
  const reportVault401 = (admission, status) => {
61213
61798
  if (!admission || status !== 401) return;
61214
61799
  void Promise.resolve().then(() => admission.report401(status)).catch((error) => {
61215
- log18.debug("send-admission-401-report-failed", { error: String(error) });
61800
+ log19.debug("send-admission-401-report-failed", { error: String(error) });
61216
61801
  });
61217
61802
  };
61218
61803
  const reportRouting2 = (sessionId, entry) => {
@@ -61220,7 +61805,7 @@ function createRequestExecutor(deps) {
61220
61805
  try {
61221
61806
  onRouting(sessionId, entry);
61222
61807
  } catch (error) {
61223
- log18.debug("routing-report-failed", { sessionId, error: String(error) });
61808
+ log19.debug("routing-report-failed", { sessionId, error: String(error) });
61224
61809
  }
61225
61810
  };
61226
61811
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy, waits) {
@@ -61320,6 +61905,7 @@ function createRequestExecutor(deps) {
61320
61905
  } : void 0;
61321
61906
  const isChildRequest = requestSessionIdentity.parentSessionId !== null;
61322
61907
  let physicalSendCount = 0;
61908
+ let emptyResponseAttempts = 0;
61323
61909
  if (accountManager.getAccountCount() === 0) {
61324
61910
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
61325
61911
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
@@ -61404,7 +61990,7 @@ function createRequestExecutor(deps) {
61404
61990
  const quietMode = config.quiet_mode;
61405
61991
  const toastScope = config.toast_scope;
61406
61992
  const showToast = async (message, variant2) => {
61407
- log18.debug("toast", {
61993
+ log19.debug("toast", {
61408
61994
  message,
61409
61995
  variant: variant2,
61410
61996
  isChildSession: isChildRequest,
@@ -61413,7 +61999,7 @@ function createRequestExecutor(deps) {
61413
61999
  if (quietMode) return;
61414
62000
  if (abortSignal?.aborted) return;
61415
62001
  if (toastScope === "root_only" && isChildRequest) {
61416
- log18.debug("toast-suppressed-child-session", {
62002
+ log19.debug("toast-suppressed-child-session", {
61417
62003
  message,
61418
62004
  variant: variant2,
61419
62005
  parentID: requestSessionIdentity.parentSessionId
@@ -61432,6 +62018,7 @@ function createRequestExecutor(deps) {
61432
62018
  }
61433
62019
  };
61434
62020
  let accountSwitchCount = 0;
62021
+ let capacityExhaustedSelections = 0;
61435
62022
  let unconfirmedRetries = 0;
61436
62023
  const maxAccountSwitches = config.max_account_switches ?? 2;
61437
62024
  let previousAccountIndex = -1;
@@ -61443,6 +62030,7 @@ function createRequestExecutor(deps) {
61443
62030
  let routingPlacementConsidered = false;
61444
62031
  let routedCandidate;
61445
62032
  let continueRouting;
62033
+ let continueOnlyLogin = false;
61446
62034
  const refusedRoutes = /* @__PURE__ */ new Map();
61447
62035
  let routingTitle = false;
61448
62036
  let routingWaitMs = 0;
@@ -61456,7 +62044,7 @@ function createRequestExecutor(deps) {
61456
62044
  );
61457
62045
  const routingRefusalResponse = (refused2) => {
61458
62046
  const { code: code2, routingCode, reason } = refused2;
61459
- log18.warn("routing-refused", {
62047
+ log19.warn("routing-refused", {
61460
62048
  code: code2,
61461
62049
  ...routingCode === void 0 ? {} : { routingCode },
61462
62050
  ...reason === void 0 ? {} : { reason }
@@ -61510,10 +62098,12 @@ function createRequestExecutor(deps) {
61510
62098
  const choice = routedCandidate;
61511
62099
  routedCandidate = void 0;
61512
62100
  const exhausted = continueRouting;
62101
+ const onlyLoginContinuation = continueOnlyLogin;
61513
62102
  continueRouting = void 0;
62103
+ continueOnlyLogin = false;
61514
62104
  if (exhausted) refusedRoutes.set(routingIdentityKey(exhausted), exhausted);
61515
62105
  const accountCount = accountManager.getAccountCount();
61516
- if (accountCount === 0) {
62106
+ if (accountCount === 0 && !onlyLoginContinuation) {
61517
62107
  if (choice) return failedRoutedPick();
61518
62108
  return createNoAccountResponse(
61519
62109
  "No Antigravity accounts available. Run `opencode auth login`.",
@@ -61533,7 +62123,7 @@ function createRequestExecutor(deps) {
61533
62123
  pushDebug(
61534
62124
  `model-access: all ${serviceable.length} serviceable account(s) excluded`
61535
62125
  );
61536
- log18.warn("model-access-all-excluded", {
62126
+ log19.warn("model-access-all-excluded", {
61537
62127
  family,
61538
62128
  model,
61539
62129
  accounts: serviceable.length
@@ -61613,7 +62203,7 @@ function createRequestExecutor(deps) {
61613
62203
  });
61614
62204
  } catch (error) {
61615
62205
  if (error instanceof AntigravityKillswitchError) {
61616
- log18.warn("killswitch-all-excluded", {
62206
+ log19.warn("killswitch-all-excluded", {
61617
62207
  family,
61618
62208
  model,
61619
62209
  threshold: error.thresholdPercent,
@@ -61639,7 +62229,7 @@ function createRequestExecutor(deps) {
61639
62229
  pushDebug(
61640
62230
  `model-unavailable: all ${candidates.length} eligible account(s) skipped`
61641
62231
  );
61642
- log18.warn("model-unavailable-all-accounts", {
62232
+ log19.warn("model-unavailable-all-accounts", {
61643
62233
  family,
61644
62234
  model,
61645
62235
  accounts: candidates.length
@@ -61701,7 +62291,7 @@ function createRequestExecutor(deps) {
61701
62291
  const canHold = !!holdCandidate && candidates.some(
61702
62292
  (candidate) => routingIdentityKey(candidate) === holdCandidate
61703
62293
  );
61704
- const answer = await deadline.wait(() => {
62294
+ const ask = () => deadline.wait(() => {
61705
62295
  const input3 = {
61706
62296
  sessionId: accountSessionIdentity.id,
61707
62297
  provider: "antigravity",
@@ -61723,9 +62313,21 @@ function createRequestExecutor(deps) {
61723
62313
  } : input3
61724
62314
  );
61725
62315
  });
62316
+ let answer = await ask();
62317
+ const firstRefusal = !exhausted && answer && "refused" in answer ? answer.refused : void 0;
62318
+ if (firstRefusal?.code === "account_selection_refused" && firstRefusal.retryAfterSecs !== void 0 && firstRefusal.retryAfterSecs <= FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS) {
62319
+ await routingSleep(
62320
+ firstRefusal.retryAfterSecs * 1e3,
62321
+ "account_free"
62322
+ );
62323
+ checkAborted();
62324
+ answer = await ask();
62325
+ }
61726
62326
  checkAborted();
61727
62327
  if (answer && "refused" in answer)
61728
62328
  return routingRefusalResponse(answer.refused);
62329
+ if (!answer && onlyLoginContinuation && candidates.length === 0)
62330
+ return failedRoutedPick();
61729
62331
  if (exhausted && answer?.hold) {
61730
62332
  if (!canHold || routingIdentityKey(answer.candidate) !== holdCandidate)
61731
62333
  return failedRoutedPick();
@@ -61962,7 +62564,7 @@ function createRequestExecutor(deps) {
61962
62564
  await deadline.wait(() => credentials.saveToDisk());
61963
62565
  } catch (error) {
61964
62566
  checkAborted();
61965
- log18.error("Failed to persist project context", {
62567
+ log19.error("Failed to persist project context", {
61966
62568
  error: String(error)
61967
62569
  });
61968
62570
  }
@@ -62019,7 +62621,7 @@ function createRequestExecutor(deps) {
62019
62621
  await deadline.wait(() => credentials.saveToDisk());
62020
62622
  } catch (error) {
62021
62623
  checkAborted();
62022
- log18.error("Failed to persist refreshed auth", {
62624
+ log19.error("Failed to persist refreshed auth", {
62023
62625
  error: String(error)
62024
62626
  });
62025
62627
  }
@@ -62028,14 +62630,14 @@ function createRequestExecutor(deps) {
62028
62630
  if (credentials.isInvalidGrant(error)) {
62029
62631
  const removed = credentials.removeAccount(account);
62030
62632
  if (removed) {
62031
- log18.warn(
62633
+ log19.warn(
62032
62634
  "Removed revoked account from pool - reauthenticate via `opencode auth login`"
62033
62635
  );
62034
62636
  try {
62035
62637
  await deadline.wait(() => credentials.saveToDiskReplace());
62036
62638
  } catch (persistError) {
62037
62639
  checkAborted();
62038
- log18.error("Failed to persist revoked account removal", {
62640
+ log19.error("Failed to persist revoked account removal", {
62039
62641
  error: String(persistError)
62040
62642
  });
62041
62643
  }
@@ -62045,7 +62647,7 @@ function createRequestExecutor(deps) {
62045
62647
  await deadline.wait(() => credentials.clearStoredAuth());
62046
62648
  } catch (storeError) {
62047
62649
  checkAborted();
62048
- log18.error(
62650
+ log19.error(
62049
62651
  "Failed to clear stored Antigravity OAuth credentials",
62050
62652
  {
62051
62653
  error: String(storeError)
@@ -62115,8 +62717,8 @@ function createRequestExecutor(deps) {
62115
62717
  const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
62116
62718
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
62117
62719
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
62118
- if (source === "local") log18.info(message);
62119
- else (log18.hostInfo ?? log18.info)(message);
62720
+ if (source === "local") log19.info(message);
62721
+ else (log19.hostInfo ?? log19.info)(message);
62120
62722
  const attempt = ++physicalSendCount;
62121
62723
  const sessionId = requestSessionIdentity.sessionId;
62122
62724
  const billing = admission && sessionId && hasVaultRoutingAccessor() ? new VaultBillingAttempt(
@@ -62198,12 +62800,14 @@ function createRequestExecutor(deps) {
62198
62800
  streaming: true,
62199
62801
  projectId
62200
62802
  });
62803
+ let warmupDispatched = false;
62201
62804
  try {
62202
62805
  pushDebug("thinking-warmup: start");
62203
62806
  const warmupSend = await credentialForAuxiliarySend(
62204
62807
  warmupInit,
62205
62808
  projectId
62206
62809
  );
62810
+ warmupDispatched = true;
62207
62811
  const warmupResponse = await sendPhysical(
62208
62812
  warmupUrl,
62209
62813
  warmupSend.init,
@@ -62228,7 +62832,7 @@ function createRequestExecutor(deps) {
62228
62832
  warmupState.markSuccess(prepared.sessionId);
62229
62833
  pushDebug("thinking-warmup: done");
62230
62834
  } catch (error) {
62231
- warmupState.clearWarmupAttempt(prepared.sessionId);
62835
+ if (!warmupDispatched) warmupState.refundAttempt(prepared.sessionId);
62232
62836
  if (error instanceof PreResponseTimeoutError) throw error;
62233
62837
  checkAborted();
62234
62838
  if (isLocalGrantError(error)) throw error;
@@ -62495,7 +63099,7 @@ function createRequestExecutor(deps) {
62495
63099
  );
62496
63100
  } catch (error) {
62497
63101
  checkAborted();
62498
- log18.debug("send-admission-401-report-failed", {
63102
+ log19.debug("send-admission-401-report-failed", {
62499
63103
  error: String(error)
62500
63104
  });
62501
63105
  }
@@ -62561,9 +63165,9 @@ function createRequestExecutor(deps) {
62561
63165
  const routed429 = response.status === 429 ? routedIdentity : void 0;
62562
63166
  if (response.status === 429 && rateLimitReason === "UNKNOWN") {
62563
63167
  await logResponseBody2(debugContext, response, 429);
62564
- const outgoing = JSON.parse(String(prepared.init.body));
63168
+ const carried = prepared.wireSystemInstruction;
62565
63169
  const recognised = systemInstructionHasHarnessIdentity(
62566
- outgoing.request?.systemInstruction
63170
+ carried && carried.body === prepared.init.body ? carried.instruction : JSON.parse(String(prepared.init.body)).request?.systemInstruction
62567
63171
  );
62568
63172
  if (recognised) {
62569
63173
  void response.body?.cancel().catch(() => {
@@ -62687,10 +63291,19 @@ function createRequestExecutor(deps) {
62687
63291
  i -= 1;
62688
63292
  continue;
62689
63293
  }
63294
+ retainHttpFailure(response);
63295
+ capacityExhaustedSelections++;
63296
+ if (capacityExhaustedSelections > 1) {
63297
+ pushDebug(
63298
+ `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted again after one account switch, giving up`
63299
+ );
63300
+ return terminalMainAttemptFailure(
63301
+ "Antigravity has no capacity for this model right now"
63302
+ );
63303
+ }
62690
63304
  pushDebug(
62691
63305
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
62692
63306
  );
62693
- retainHttpFailure(response);
62694
63307
  shouldSwitchAccount = true;
62695
63308
  break;
62696
63309
  }
@@ -62836,6 +63449,10 @@ function createRequestExecutor(deps) {
62836
63449
  i -= 1;
62837
63450
  continue;
62838
63451
  }
63452
+ if (routed429 && exhaustion) {
63453
+ const { accountId, credentialId } = routed429;
63454
+ continueRouting = { accountId, credentialId, ...exhaustion };
63455
+ }
62839
63456
  const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
62840
63457
  if (accountCount > 1) {
62841
63458
  const quotaMsg = reasonInfo.quotaResetTime ? ` (quota resets ${reasonInfo.quotaResetTime})` : ``;
@@ -62844,7 +63461,7 @@ function createRequestExecutor(deps) {
62844
63461
  "warning"
62845
63462
  );
62846
63463
  await sleep4(switchAccountDelayMs, abortSignal);
62847
- } else {
63464
+ } else if (!continueRouting || isHardEligible(account)) {
62848
63465
  const expBackoffMs = Math.min(
62849
63466
  FIRST_RETRY_DELAY_MS * 2 ** (backoff.attempt - 1),
62850
63467
  6e4
@@ -62861,10 +63478,6 @@ function createRequestExecutor(deps) {
62861
63478
  );
62862
63479
  }
62863
63480
  retainHttpFailure(response);
62864
- if (routed429 && exhaustion) {
62865
- const { accountId, credentialId } = routed429;
62866
- continueRouting = { accountId, credentialId, ...exhaustion };
62867
- }
62868
63481
  shouldSwitchAccount = true;
62869
63482
  break;
62870
63483
  }
@@ -62884,7 +63497,7 @@ function createRequestExecutor(deps) {
62884
63497
  debug.logAntigravityDebugResponse(debugContext, response, {
62885
63498
  note
62886
63499
  });
62887
- log18.info("model-unavailable", {
63500
+ log19.info("model-unavailable", {
62888
63501
  accountIndex: account.index,
62889
63502
  family,
62890
63503
  model,
@@ -62908,6 +63521,19 @@ function createRequestExecutor(deps) {
62908
63521
  () => response.clone().text().catch(() => "")
62909
63522
  );
62910
63523
  const extracted = errorBodyText === void 0 ? void 0 : classifyAccessError(errorBodyText);
63524
+ const served2 = sendAdmission;
63525
+ const reportCondition = (reason) => {
63526
+ if (credentials.domain !== "vault" || !served2?.reportCondition)
63527
+ return;
63528
+ const actionUrl = extracted?.structuredVerifyUrl;
63529
+ waitPolicy.vaultConditions.push(
63530
+ () => served2.reportCondition?.({
63531
+ reason,
63532
+ providerStatus: 403,
63533
+ ...actionUrl && { actionUrl }
63534
+ })
63535
+ );
63536
+ };
62911
63537
  if (routedIdentity && (extracted?.accountIneligible || extracted?.validationRequired)) {
62912
63538
  const { accountId, credentialId } = routedIdentity;
62913
63539
  continueRouting = {
@@ -62937,6 +63563,7 @@ function createRequestExecutor(deps) {
62937
63563
  trackers.health.recordFailure(account.index);
62938
63564
  retainHttpFailure(response);
62939
63565
  shouldSwitchAccount = true;
63566
+ reportCondition("provider_ineligible");
62940
63567
  break;
62941
63568
  }
62942
63569
  if (extracted?.validationRequired) {
@@ -62972,6 +63599,7 @@ function createRequestExecutor(deps) {
62972
63599
  trackers.health.recordFailure(account.index);
62973
63600
  retainHttpFailure(response);
62974
63601
  shouldSwitchAccount = true;
63602
+ reportCondition("provider_verification_required");
62975
63603
  break;
62976
63604
  }
62977
63605
  }
@@ -63051,8 +63679,7 @@ function createRequestExecutor(deps) {
63051
63679
  })
63052
63680
  );
63053
63681
  if (isEmptyResponseBody(bodyText)) {
63054
- const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
63055
- const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
63682
+ const currentAttempts = ++emptyResponseAttempts;
63056
63683
  pushDebug(
63057
63684
  `empty-response: attempt ${currentAttempts}/${maxAttempts}`
63058
63685
  );
@@ -63065,14 +63692,11 @@ function createRequestExecutor(deps) {
63065
63692
  await sleep4(retryDelayMs, abortSignal);
63066
63693
  continue;
63067
63694
  }
63068
- retryState.clearEmptyResponseAttempts();
63069
63695
  return createNativeGoogleErrorResponse({
63070
63696
  status: 502,
63071
63697
  reason: "empty_response"
63072
63698
  });
63073
63699
  }
63074
- const _emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
63075
- retryState.clearEmptyResponseAttempts();
63076
63700
  }
63077
63701
  const routingObservation = credentials.domain === "vault" && sendAdmission && sessionKey && response.ok && hasVaultRoutingAccessor() ? observeVaultUpstream(response, abortSignal) : void 0;
63078
63702
  const transformedResponse = await deadline.wait(
@@ -63109,7 +63733,7 @@ function createRequestExecutor(deps) {
63109
63733
  }
63110
63734
  if (apiRequestCount > 1) {
63111
63735
  pushDebug(
63112
- `[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`
63736
+ `[Quota] Main-request responses on this account selection: ${apiRequestCount}`
63113
63737
  );
63114
63738
  }
63115
63739
  const dailyCounts = accountManager.getDailyRequestCounts(
@@ -63149,6 +63773,9 @@ function createRequestExecutor(deps) {
63149
63773
  const refresh = credentials.refreshQuotaAfterSuccess;
63150
63774
  waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
63151
63775
  }
63776
+ const served = sendAdmission;
63777
+ if (credentials.domain === "vault" && response.ok && transformedResponse.ok && served?.clearCondition)
63778
+ waitPolicy.vaultConditions.push(() => served.clearCondition?.());
63152
63779
  return routingObservation && credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor() && response.ok ? observeVaultServed(
63153
63780
  {
63154
63781
  sessionId: sessionKey,
@@ -63166,6 +63793,7 @@ function createRequestExecutor(deps) {
63166
63793
  trackers.token.refund(account.index);
63167
63794
  tokenConsumed = false;
63168
63795
  }
63796
+ deadline.resume();
63169
63797
  if (credentials.domain === "local" && localGrant?.captured.source === "store" && isLocalGrantError(error)) {
63170
63798
  if (error instanceof LocalGrantSupersededError && !localRecaptureUsed) {
63171
63799
  localRecaptureUsed = true;
@@ -63208,7 +63836,7 @@ function createRequestExecutor(deps) {
63208
63836
  const originalError = recoveryError.originalError || {
63209
63837
  error: { message: "Thinking recovery triggered" }
63210
63838
  };
63211
- log18.debug("thinking-recovery-failed", { error: originalError });
63839
+ log19.debug("thinking-recovery-failed", { error: originalError });
63212
63840
  const recoveryMessage = "Antigravity could not repair the conversation's thinking blocks. Start a new session.";
63213
63841
  return new Response(
63214
63842
  JSON.stringify({
@@ -63251,6 +63879,10 @@ function createRequestExecutor(deps) {
63251
63879
  }
63252
63880
  if (shouldSwitchAccount) {
63253
63881
  if (switchedForUnconfirmed) continue;
63882
+ if (accountCount === 1 && continueRouting && (continueRouting.limitWindow === "signed_out" || !isHardEligible(account))) {
63883
+ continueOnlyLogin = true;
63884
+ continue;
63885
+ }
63254
63886
  accountSwitchCount++;
63255
63887
  if (accountSwitchCount > maxAccountSwitches) {
63256
63888
  pushDebug(
@@ -63313,13 +63945,17 @@ function createRequestExecutor(deps) {
63313
63945
  cancellation.signal,
63314
63946
  deps.preResponseClock
63315
63947
  );
63316
- log18.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
63948
+ log19.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
63317
63949
  const handoff = createAfterHandoff(
63318
63950
  advisoryWork,
63319
63951
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
63320
- () => log18.debug("post-response-advisory-work-failed")
63952
+ () => log19.debug("post-response-advisory-work-failed")
63321
63953
  );
63322
- const waitPolicy = {};
63954
+ const waitPolicy = { vaultConditions: [] };
63955
+ const publishVaultConditions = () => {
63956
+ for (const operation of waitPolicy.vaultConditions.splice(0))
63957
+ runVaultCondition(operation);
63958
+ };
63323
63959
  const selectedCredentials = /* @__PURE__ */ new Set();
63324
63960
  const selectedProjectIds = /* @__PURE__ */ new Set();
63325
63961
  const redactFailure = (error) => {
@@ -63347,7 +63983,7 @@ function createRequestExecutor(deps) {
63347
63983
  ).catch((error) => {
63348
63984
  cancellation.signal.throwIfAborted();
63349
63985
  if (error instanceof PreResponseTimeoutError) {
63350
- log18.debug("pre-response-timeout", { reason: error.reason });
63986
+ log19.debug("pre-response-timeout", { reason: error.reason });
63351
63987
  return waitPolicy.refusal?.() ?? preResponseTimeoutResponse();
63352
63988
  }
63353
63989
  throw error;
@@ -63392,7 +64028,21 @@ function createRequestExecutor(deps) {
63392
64028
  cancellation.release();
63393
64029
  throw redactFailure(error);
63394
64030
  }
63395
- ).catch((error) => {
64031
+ ).then((response) => {
64032
+ if (waitPolicy.vaultConditions.length > 0) {
64033
+ if (requestOptions?.onResponseHandoff) {
64034
+ try {
64035
+ requestOptions.onResponseHandoff(publishVaultConditions);
64036
+ return response;
64037
+ } catch {
64038
+ }
64039
+ }
64040
+ setImmediate(publishVaultConditions);
64041
+ }
64042
+ return response;
64043
+ }).catch((error) => {
64044
+ if (waitPolicy.vaultConditions.length > 0)
64045
+ setImmediate(publishVaultConditions);
63396
64046
  handoff.cancel();
63397
64047
  deadline.dispose();
63398
64048
  cancellation.release();
@@ -63479,7 +64129,7 @@ function extractRateLimitBodyInfo(body, status, headers) {
63479
64129
 
63480
64130
  // src/plugin/fetch-interceptor.ts
63481
64131
  init_vault_request_credentials();
63482
- var log15 = createLogger4("fetch-interceptor");
64132
+ var log16 = createLogger4("fetch-interceptor");
63483
64133
  var failureLog2 = createLogger("fetch-interceptor");
63484
64134
  function fetchFailure(error, input2, init) {
63485
64135
  const signal = init?.signal ?? (input2 instanceof Request ? input2.signal : void 0);
@@ -63539,14 +64189,14 @@ function openCode1EngineCollaborators(common) {
63539
64189
  // the engine calls.
63540
64190
  debug: debug_exports,
63541
64191
  dump: { dumpRequest: dumpGeminiRequest },
63542
- logger: log15,
64192
+ logger: log16,
63543
64193
  classifyAccessError: extractAccountAccessErrorDetails,
63544
64194
  notify: (message, variant) => client.tui.showToast({ body: { message, variant } }),
63545
64195
  onRouting: common.onRouting ?? ((sessionId, entry) => {
63546
64196
  void upsertSidebarActiveRouting(sessionId, entry, {
63547
64197
  authoritative: true
63548
64198
  }).catch((error) => {
63549
- log15.debug("sidebar-routing-upsert-failed", {
64199
+ log16.debug("sidebar-routing-upsert-failed", {
63550
64200
  sessionId,
63551
64201
  error: String(error)
63552
64202
  });
@@ -63572,7 +64222,7 @@ function createFetchInterceptor(context) {
63572
64222
  const refreshQuotaAfterSuccess = createLocalQuotaRefresh(
63573
64223
  accountManager,
63574
64224
  quotaManager,
63575
- log15
64225
+ log16
63576
64226
  );
63577
64227
  const executor = createRequestExecutor({
63578
64228
  assertAdmission: context.assertAdmission,
@@ -63727,7 +64377,7 @@ init_logger4();
63727
64377
 
63728
64378
  // src/plugin/search.ts
63729
64379
  init_logger4();
63730
- var log16 = createLogger4("search");
64380
+ var log17 = createLogger4("search");
63731
64381
  function formatSearchResult(result) {
63732
64382
  const lines = [];
63733
64383
  lines.push("## Search Results\n");
@@ -63855,7 +64505,7 @@ ${urlList}`;
63855
64505
  requestType: "agent"
63856
64506
  };
63857
64507
  const url = `${ANTIGRAVITY_ENDPOINT}/v1internal:generateContent`;
63858
- log16.debug("Executing search", {
64508
+ log17.debug("Executing search", {
63859
64509
  query,
63860
64510
  urlCount: urls?.length ?? 0,
63861
64511
  thinking
@@ -63878,7 +64528,7 @@ ${urlList}`;
63878
64528
  );
63879
64529
  if (!response.ok) {
63880
64530
  const errorText3 = await response.text();
63881
- log16.debug("Search API error", {
64531
+ log17.debug("Search API error", {
63882
64532
  status: response.status,
63883
64533
  error: errorText3
63884
64534
  });
@@ -63891,14 +64541,14 @@ ${errorText3}
63891
64541
  Please try again with a different query.`;
63892
64542
  }
63893
64543
  const data = await response.json();
63894
- log16.debug("Search response received", { hasResponse: !!data.response });
64544
+ log17.debug("Search response received", { hasResponse: !!data.response });
63895
64545
  const result = parseSearchResponse(data);
63896
64546
  const formatted = formatSearchResult(result);
63897
- log16.debug("Search response formatted", { resultLength: formatted.length });
64547
+ log17.debug("Search response formatted", { resultLength: formatted.length });
63898
64548
  return formatted;
63899
64549
  } catch (error) {
63900
64550
  const message = error instanceof Error ? error.message : String(error);
63901
- log16.debug("Search execution error", { error: message });
64551
+ log17.debug("Search execution error", { error: message });
63902
64552
  return `## Search Error
63903
64553
 
63904
64554
  Failed to execute search: ${message}. Please try again with a different query.`;
@@ -63906,7 +64556,7 @@ Failed to execute search: ${message}. Please try again with a different query.`;
63906
64556
  }
63907
64557
 
63908
64558
  // src/plugin/google-search-tool.ts
63909
- var log17 = createLogger4("plugin");
64559
+ var log18 = createLogger4("plugin");
63910
64560
  function createGoogleSearchTool({
63911
64561
  getAuth,
63912
64562
  client,
@@ -63928,7 +64578,7 @@ function createGoogleSearchTool({
63928
64578
  if (mayStartLocalWork && !await mayStartLocalWork()) {
63929
64579
  return "Google Search is not available through local credentials while vault custody is active or unreadable.";
63930
64580
  }
63931
- log17.debug("Google Search tool called", {
64581
+ log18.debug("Google Search tool called", {
63932
64582
  query: args.query,
63933
64583
  urlCount: args.urls?.length ?? 0
63934
64584
  });
@@ -64093,8 +64743,8 @@ function createPluginLifecycle(options) {
64093
64743
  };
64094
64744
  let failDisposal = () => {
64095
64745
  };
64096
- disposal = new Promise((resolve33, reject) => {
64097
- finishDisposal = resolve33;
64746
+ disposal = new Promise((resolve34, reject) => {
64747
+ finishDisposal = resolve34;
64098
64748
  failDisposal = reject;
64099
64749
  });
64100
64750
  void (async () => {
@@ -64282,7 +64932,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
64282
64932
  // Diagnostics. Before the move they load from and write to the
64283
64933
  // project or user antigravity.json through the operator writer.
64284
64934
  operator: () => createOperatorSettingsController({
64285
- projectConfigPath: join46(directory, ".opencode", "antigravity.json"),
64935
+ projectConfigPath: join45(directory, ".opencode", "antigravity.json"),
64286
64936
  // getUserConfigPath() already returns the full file path including
64287
64937
  // 'antigravity.json' — do NOT join again or the path double-nests
64288
64938
  // into <dir>/antigravity.json/antigravity.json.
@@ -64344,7 +64994,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
64344
64994
  await drainSidebarWrites();
64345
64995
  }
64346
64996
  });
64347
- const accountFile = resolve32(accountFileForVault());
64997
+ const accountFile = resolve33(accountFileForVault());
64348
64998
  const vaultFolder = await prepareVaultFolder({ accountFile });
64349
64999
  const unavailableMessage = vaultFolder.refusal?.message ?? VAULT_ACCOUNT_REMEDY;
64350
65000
  let vaultQuotaPoller;