@cortexkit/opencode-antigravity-auth 3.1.10 → 3.1.12

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 (172) hide show
  1. package/dist/cli.js +357 -58
  2. package/dist/cli.js.map +3 -3
  3. package/dist/cli.meta.json +42 -32
  4. package/dist/index.js +1115 -493
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +98 -65
  7. package/dist/server.js +1266 -616
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/cli.d.ts +3 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +19 -6
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  15. package/dist/src/common-auth-embedded/claustrum/consumer.js +32 -0
  16. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +39 -1
  17. package/dist/src/common-auth-embedded/claustrum/custody.js +145 -8
  18. package/dist/src/common-auth-embedded/claustrum/host.js +8 -0
  19. package/dist/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  20. package/dist/src/common-auth-embedded/claustrum/hub.js +10 -0
  21. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  22. package/dist/src/common-auth-embedded/routing-accessor/index.js +5 -3
  23. package/dist/src/common-auth-embedded/source-output.json +35 -35
  24. package/dist/src/ga/rpc/protocol.d.ts +11 -5
  25. package/dist/src/ga/rpc/protocol.d.ts.map +1 -1
  26. package/dist/src/ga/rpc/protocol.js +11 -3
  27. package/dist/src/ga/rpc/protocol.js.map +1 -1
  28. package/dist/src/ga/server/index.d.ts.map +1 -1
  29. package/dist/src/ga/server/index.js +30 -14
  30. package/dist/src/ga/server/index.js.map +1 -1
  31. package/dist/src/ga/tui/host-ga.d.ts +2 -1
  32. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  33. package/dist/src/ga/tui/host-ga.js +9 -4
  34. package/dist/src/ga/tui/host-ga.js.map +1 -1
  35. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  36. package/dist/src/plugin/account-access.d.ts +1 -0
  37. package/dist/src/plugin/account-access.d.ts.map +1 -1
  38. package/dist/src/plugin/account-access.js +28 -0
  39. package/dist/src/plugin/account-access.js.map +1 -1
  40. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  41. package/dist/src/plugin/auth-loader.js +21 -12
  42. package/dist/src/plugin/auth-loader.js.map +1 -1
  43. package/dist/src/plugin/background-quota-refresh.d.ts +11 -24
  44. package/dist/src/plugin/background-quota-refresh.d.ts.map +1 -1
  45. package/dist/src/plugin/background-quota-refresh.js +54 -60
  46. package/dist/src/plugin/background-quota-refresh.js.map +1 -1
  47. package/dist/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  48. package/dist/src/plugin/background-vault-quota-refresh.js +6 -3
  49. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  50. package/dist/src/plugin/cache/signature-cache.d.ts +3 -0
  51. package/dist/src/plugin/cache/signature-cache.d.ts.map +1 -1
  52. package/dist/src/plugin/cache/signature-cache.js +73 -46
  53. package/dist/src/plugin/cache/signature-cache.js.map +1 -1
  54. package/dist/src/plugin/cache.d.ts.map +1 -1
  55. package/dist/src/plugin/cache.js +17 -7
  56. package/dist/src/plugin/cache.js.map +1 -1
  57. package/dist/src/plugin/core/streaming/displayed-thinking.d.ts +23 -0
  58. package/dist/src/plugin/core/streaming/displayed-thinking.d.ts.map +1 -0
  59. package/dist/src/plugin/core/streaming/displayed-thinking.js +58 -0
  60. package/dist/src/plugin/core/streaming/displayed-thinking.js.map +1 -0
  61. package/dist/src/plugin/fetch/warmup.d.ts +9 -2
  62. package/dist/src/plugin/fetch/warmup.d.ts.map +1 -1
  63. package/dist/src/plugin/fetch/warmup.js +22 -14
  64. package/dist/src/plugin/fetch/warmup.js.map +1 -1
  65. package/dist/src/plugin/ga-location-services.d.ts +1 -0
  66. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  67. package/dist/src/plugin/ga-location-services.js +2 -0
  68. package/dist/src/plugin/ga-location-services.js.map +1 -1
  69. package/dist/src/plugin/ga-shared-vault-custody.d.ts.map +1 -1
  70. package/dist/src/plugin/ga-shared-vault-custody.js +7 -1
  71. package/dist/src/plugin/ga-shared-vault-custody.js.map +1 -1
  72. package/dist/src/plugin/index.d.ts.map +1 -1
  73. package/dist/src/plugin/index.js +6 -1
  74. package/dist/src/plugin/index.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 +27 -42
  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 +25 -15
  95. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  96. package/dist/src/plugin/shared/vault-request-credentials.js +141 -68
  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 +39 -1
  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/ga/rpc/protocol.d.ts +11 -5
  119. package/dist/types/src/ga/rpc/protocol.d.ts.map +1 -1
  120. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  121. package/dist/types/src/plugin/account-access.d.ts +1 -0
  122. package/dist/types/src/plugin/account-access.d.ts.map +1 -1
  123. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  124. package/dist/types/src/plugin/background-quota-refresh.d.ts +11 -24
  125. package/dist/types/src/plugin/background-quota-refresh.d.ts.map +1 -1
  126. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  127. package/dist/types/src/plugin/cache/signature-cache.d.ts +3 -0
  128. package/dist/types/src/plugin/cache/signature-cache.d.ts.map +1 -1
  129. package/dist/types/src/plugin/cache.d.ts.map +1 -1
  130. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts +23 -0
  131. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts.map +1 -0
  132. package/dist/types/src/plugin/fetch/warmup.d.ts +9 -2
  133. package/dist/types/src/plugin/fetch/warmup.d.ts.map +1 -1
  134. package/dist/types/src/plugin/ga-location-services.d.ts +1 -0
  135. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  136. package/dist/types/src/plugin/ga-shared-vault-custody.d.ts.map +1 -1
  137. package/dist/types/src/plugin/index.d.ts.map +1 -1
  138. package/dist/types/src/plugin/quota.d.ts +10 -2
  139. package/dist/types/src/plugin/quota.d.ts.map +1 -1
  140. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  141. package/dist/types/src/plugin/request.d.ts +12 -1
  142. package/dist/types/src/plugin/request.d.ts.map +1 -1
  143. package/dist/types/src/plugin/shared/request-services.d.ts +4 -1
  144. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  145. package/dist/types/src/plugin/shared/runtime.d.ts +3 -4
  146. package/dist/types/src/plugin/shared/runtime.d.ts.map +1 -1
  147. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +25 -15
  148. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  149. package/dist/types/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  150. package/dist/types/src/setup.d.ts +3 -0
  151. package/dist/types/src/setup.d.ts.map +1 -1
  152. package/dist/types/src/sidebar-state.d.ts +20 -7
  153. package/dist/types/src/sidebar-state.d.ts.map +1 -1
  154. package/package.json +3 -3
  155. package/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  156. package/src/common-auth-embedded/claustrum/consumer.js +32 -0
  157. package/src/common-auth-embedded/claustrum/custody.d.ts +39 -1
  158. package/src/common-auth-embedded/claustrum/custody.js +145 -8
  159. package/src/common-auth-embedded/claustrum/host.js +8 -0
  160. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  161. package/src/common-auth-embedded/claustrum/hub.js +10 -0
  162. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  163. package/src/common-auth-embedded/routing-accessor/index.js +5 -3
  164. package/src/common-auth-embedded/source-output.json +35 -35
  165. package/src/sidebar-state.ts +77 -8
  166. package/src/tui-compiled/sidebar-state.js +40 -1
  167. package/src/tui-compiled/tui.js +49 -24
  168. package/src/tui-ga-compiled/host-ga.js +11 -5
  169. package/src/tui-ga-raw/host-ga.tsx +17 -6
  170. package/src/tui-raw/sidebar-state.js +40 -1
  171. package/src/tui-raw/tui.tsx +40 -24
  172. package/src/tui.tsx +40 -24
package/dist/server.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
@@ -1642,10 +1652,10 @@ async function privateDirectory(path5) {
1642
1652
  if (errno(error) !== "EEXIST")
1643
1653
  throw error;
1644
1654
  }
1645
- const stat21 = await lstat2(path5);
1646
- if (!stat21.isDirectory() || stat21.isSymbolicLink())
1655
+ const stat22 = await lstat2(path5);
1656
+ if (!stat22.isDirectory() || stat22.isSymbolicLink())
1647
1657
  throw new AccountMigrationError("successor directory is not a regular directory");
1648
- privateMode(stat21.mode, 448);
1658
+ privateMode(stat22.mode, 448);
1649
1659
  if (windowsPrivateFiles)
1650
1660
  await verifySafeDirectory(path5);
1651
1661
  if (!sameFilesystemPath(await realpath(path5), path5))
@@ -5058,9 +5068,7 @@ function reconcileRateLimitsFromReading(account, reading, now2) {
5058
5068
  function quotaRetryAfter(account, family, model, reason, retryAfterMs, now2) {
5059
5069
  if (reason !== "QUOTA_EXHAUSTED" || !(retryAfterMs && retryAfterMs > MAX_QUOTA_EXHAUSTED_BACKOFF_MS))
5060
5070
  return retryAfterMs;
5061
- const at = account.cachedQuotaUpdatedAt;
5062
- const group = resolveQuotaGroup(family, model, account.cachedQuota);
5063
- 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;
5064
5072
  }
5065
5073
  function quotaExhaustedUntil(account, family, model, now2) {
5066
5074
  const at = account.cachedQuotaUpdatedAt;
@@ -7685,11 +7693,21 @@ var init_account_repository = __esm({
7685
7693
  rowId: ref.id
7686
7694
  });
7687
7695
  }
7688
- await this.store.recordQuota(ref.id, credentialFenceOf(ref), encoded);
7689
- await this.updateMetadata(ref, (metadata) => metadata ? {
7690
- kind: "set",
7691
- metadata: applyRateLimitReadingUpdate(metadata, rateLimitReadingUpdateOf(observation), this.now())
7692
- } : { 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
+ });
7693
7711
  });
7694
7712
  }
7695
7713
  // ---- selection and roster ---------------------------------------------
@@ -8304,7 +8322,7 @@ async function rmEvictingDir(evictingPath) {
8304
8322
  });
8305
8323
  }
8306
8324
  async function sleep(ms) {
8307
- await new Promise((resolve34) => setTimeout(resolve34, ms));
8325
+ await new Promise((resolve35) => setTimeout(resolve35, ms));
8308
8326
  }
8309
8327
  async function acquireFencedFileLock(options) {
8310
8328
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -8420,8 +8438,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now2) {
8420
8438
  let released = false;
8421
8439
  let lost = false;
8422
8440
  let lostResolve = null;
8423
- let lostPromise = new Promise((resolve34) => {
8424
- lostResolve = resolve34;
8441
+ let lostPromise = new Promise((resolve35) => {
8442
+ lostResolve = resolve35;
8425
8443
  });
8426
8444
  const markLost = () => {
8427
8445
  if (lost)
@@ -8431,9 +8449,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now2) {
8431
8449
  clearInterval(renewTimer);
8432
8450
  renewTimer = null;
8433
8451
  }
8434
- const resolve34 = lostResolve;
8452
+ const resolve35 = lostResolve;
8435
8453
  lostResolve = null;
8436
- resolve34?.();
8454
+ resolve35?.();
8437
8455
  };
8438
8456
  const setupRenew = () => {
8439
8457
  if (options.renew === false)
@@ -9056,7 +9074,7 @@ async function saveAccountStorageReplace(path5, incoming) {
9056
9074
  return mutateAccountStorage(path5, () => incoming);
9057
9075
  }
9058
9076
  async function clearAccountStorage(path5) {
9059
- const sleep5 = (ms) => new Promise((resolve34) => setTimeout(resolve34, ms));
9077
+ const sleep5 = (ms) => new Promise((resolve35) => setTimeout(resolve35, ms));
9060
9078
  const lock = await acquireWithRetry(path5, sleep5);
9061
9079
  try {
9062
9080
  await assertLegacyAccountStorageWritable(path5);
@@ -9104,7 +9122,7 @@ var init_account_storage = __esm({
9104
9122
  }
9105
9123
  };
9106
9124
  RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
9107
- DEFAULT_SLEEP = (ms) => new Promise((resolve34) => setTimeout(resolve34, ms));
9125
+ DEFAULT_SLEEP = (ms) => new Promise((resolve35) => setTimeout(resolve35, ms));
9108
9126
  DEFAULT_BUILD_BACKUP_PATH = (path5, now2) => `${path5}.corrupt-${now2.toISOString().replace(/[:.]/g, "-")}`;
9109
9127
  }
9110
9128
  });
@@ -9202,7 +9220,7 @@ function isStorageLockContention(error) {
9202
9220
  function quotaAccountIdentity(refreshToken) {
9203
9221
  return createHash3("sha256").update(refreshToken).digest("hex").slice(0, 16);
9204
9222
  }
9205
- function applyPendingRowWrite(metadata, pending, now2) {
9223
+ function applyPendingRowWrite(metadata, pending, now2, storedReadingAt) {
9206
9224
  let next = metadata;
9207
9225
  const resets = {};
9208
9226
  const cleared = [];
@@ -9224,7 +9242,7 @@ function applyPendingRowWrite(metadata, pending, now2) {
9224
9242
  delete written[key2];
9225
9243
  next = { ...next, rateLimitResetTimes: rates, rateLimitWrittenAt: written };
9226
9244
  }
9227
- if (pending.readingUpdate)
9245
+ if (storedReadingAt != null && pending.readingUpdate?.checkedAt === storedReadingAt)
9228
9246
  next = applyRateLimitReadingUpdate(next, pending.readingUpdate, now2);
9229
9247
  if (pending.cooldown !== void 0) {
9230
9248
  next = applyCooldownObservation(next, pending.cooldown.value);
@@ -9979,7 +9997,7 @@ var init_account_manager = __esm({
9979
9997
  for (const pending of rows) {
9980
9998
  repository.updateMetadata(pending.ref, (current, row) => ({
9981
9999
  kind: "set",
9982
- 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)
9983
10001
  })).catch((error) => {
9984
10002
  if (error instanceof AccountRepositoryError && error.failure.kind === "lock-contention" && !error.failure.ambiguous) {
9985
10003
  this.requeueRowWrite(pending);
@@ -10358,8 +10376,8 @@ var init_account_manager = __esm({
10358
10376
  await this.saveInFlight;
10359
10377
  return;
10360
10378
  }
10361
- return new Promise((resolve34, reject) => {
10362
- this.savePromiseResolvers.push({ resolve: resolve34, reject });
10379
+ return new Promise((resolve35, reject) => {
10380
+ this.savePromiseResolvers.push({ resolve: resolve35, reject });
10363
10381
  });
10364
10382
  }
10365
10383
  async dispose() {
@@ -10402,8 +10420,8 @@ var init_account_manager = __esm({
10402
10420
  reject(error);
10403
10421
  throw error;
10404
10422
  }
10405
- for (const { resolve: resolve34 } of resolvers)
10406
- resolve34();
10423
+ for (const { resolve: resolve35 } of resolvers)
10424
+ resolve35();
10407
10425
  }
10408
10426
  async executeSave() {
10409
10427
  this.savePending = false;
@@ -10417,16 +10435,16 @@ var init_account_manager = __esm({
10417
10435
  }
10418
10436
  try {
10419
10437
  await this.saveToDisk();
10420
- for (const { resolve: resolve34 } of resolvers) {
10421
- resolve34();
10438
+ for (const { resolve: resolve35 } of resolvers) {
10439
+ resolve35();
10422
10440
  }
10423
10441
  } catch (error) {
10424
10442
  if (isStorageLockContention(error)) {
10425
10443
  this.onDiagnostic?.("Skipped account-state persist due to storage lock contention", {
10426
10444
  error: String(error)
10427
10445
  });
10428
- for (const { resolve: resolve34 } of resolvers) {
10429
- resolve34();
10446
+ for (const { resolve: resolve35 } of resolvers) {
10447
+ resolve35();
10430
10448
  }
10431
10449
  return;
10432
10450
  }
@@ -10464,13 +10482,13 @@ var init_account_manager = __esm({
10464
10482
  getAccountFingerprintHistory(accountIndex) {
10465
10483
  return this.selection.getAccountFingerprintHistory(accountIndex);
10466
10484
  }
10467
- updateQuotaCache(accountIndex, quotaGroups, expectedRefreshToken) {
10485
+ updateQuotaCache(accountIndex, quotaGroups, expectedRefreshToken, checkedAt = this.now()) {
10468
10486
  const account = this.accounts[accountIndex];
10469
- if (!account || account.parts.refreshToken !== expectedRefreshToken && expectedRefreshToken !== void 0)
10470
- return;
10487
+ if (!account || account.parts.refreshToken !== expectedRefreshToken && expectedRefreshToken !== void 0 || !Number.isFinite(checkedAt) || account.cachedQuotaUpdatedAt !== void 0 && checkedAt < account.cachedQuotaUpdatedAt)
10488
+ return false;
10471
10489
  account.cachedQuota = quotaGroups;
10472
10490
  account.cachedQuotaAccountId = quotaAccountIdentity(account.parts.refreshToken);
10473
- account.cachedQuotaUpdatedAt = this.now();
10491
+ account.cachedQuotaUpdatedAt = checkedAt;
10474
10492
  this.selection.reconcileQuotaReading(account, this.repository === void 0);
10475
10493
  const pending = account.ref ? this.pendingRowWrites.get(rowRefKey(account.ref)) : void 0;
10476
10494
  if (pending)
@@ -10486,6 +10504,7 @@ var init_account_manager = __esm({
10486
10504
  cachedQuotaUpdatedAt: account.cachedQuotaUpdatedAt
10487
10505
  };
10488
10506
  this.dispatch(account, "quota reading", (repository, ref) => repository.recordQuota(ref, reading));
10507
+ return true;
10489
10508
  }
10490
10509
  /**
10491
10510
  * Apply a subset of fields from a quota-fetch `updatedAccount` result onto
@@ -10610,6 +10629,35 @@ var init_account_manager = __esm({
10610
10629
  }
10611
10630
  return targets;
10612
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
+ }
10613
10661
  getOldestQuotaCacheAge() {
10614
10662
  return this.selection.getOldestQuotaCacheAge();
10615
10663
  }
@@ -10688,6 +10736,14 @@ function orderAgyRequestPayloadInPlace(payload) {
10688
10736
  function countAgyRequestSteps(payload) {
10689
10737
  return Array.isArray(payload.contents) ? payload.contents.length : 0;
10690
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
+ }
10691
10747
  function hasSecondUserTurn(payload) {
10692
10748
  if (!Array.isArray(payload.contents))
10693
10749
  return false;
@@ -10933,7 +10989,7 @@ function getHttpsProxy(url) {
10933
10989
  }
10934
10990
  }
10935
10991
  function waitForHead(socket, timeoutMs, onTimeout) {
10936
- return new Promise((resolve34, reject) => {
10992
+ return new Promise((resolve35, reject) => {
10937
10993
  let buffer = Buffer3.alloc(0);
10938
10994
  const timeout = setTimeout(() => {
10939
10995
  onTimeout();
@@ -10956,7 +11012,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
10956
11012
  return;
10957
11013
  const head = buffer.subarray(0, marker).toString("latin1");
10958
11014
  const leftover = buffer.subarray(marker + 4);
10959
- cleanup2(() => resolve34({ head, leftover }));
11015
+ cleanup2(() => resolve35({ head, leftover }));
10960
11016
  };
10961
11017
  socket.on("data", onData);
10962
11018
  socket.once("error", onError);
@@ -10970,7 +11026,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
10970
11026
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
10971
11027
  signal: signal ?? void 0
10972
11028
  });
10973
- await new Promise((resolve34, reject) => {
11029
+ await new Promise((resolve35, reject) => {
10974
11030
  const timeout = setTimeout(() => {
10975
11031
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
10976
11032
  proxySocket.destroy();
@@ -10979,7 +11035,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
10979
11035
  const cleanup2 = () => clearTimeout(timeout);
10980
11036
  proxySocket.once("connect", () => {
10981
11037
  cleanup2();
10982
- resolve34();
11038
+ resolve35();
10983
11039
  });
10984
11040
  proxySocket.once("error", (error) => {
10985
11041
  cleanup2();
@@ -11004,7 +11060,7 @@ Host: ${targetHost}:${targetPort}\r
11004
11060
  if (leftover.length > 0) {
11005
11061
  proxySocket.unshift(leftover);
11006
11062
  }
11007
- return await new Promise((resolve34, reject) => {
11063
+ return await new Promise((resolve35, reject) => {
11008
11064
  const tlsOptions = {
11009
11065
  socket: proxySocket,
11010
11066
  servername: targetHost,
@@ -11020,7 +11076,7 @@ Host: ${targetHost}:${targetPort}\r
11020
11076
  const cleanup2 = () => clearTimeout(timeout);
11021
11077
  tlsSocket.once("secureConnect", () => {
11022
11078
  cleanup2();
11023
- resolve34(tlsSocket);
11079
+ resolve35(tlsSocket);
11024
11080
  });
11025
11081
  tlsSocket.once("error", (error) => {
11026
11082
  cleanup2();
@@ -11029,7 +11085,7 @@ Host: ${targetHost}:${targetPort}\r
11029
11085
  });
11030
11086
  }
11031
11087
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
11032
- return await new Promise((resolve34, reject) => {
11088
+ return await new Promise((resolve35, reject) => {
11033
11089
  const tlsOptions = {
11034
11090
  host: targetUrl.hostname,
11035
11091
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -11046,7 +11102,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
11046
11102
  const cleanup2 = () => clearTimeout(timeout);
11047
11103
  socket.once("secureConnect", () => {
11048
11104
  cleanup2();
11049
- resolve34(socket);
11105
+ resolve35(socket);
11050
11106
  });
11051
11107
  socket.once("error", (error) => {
11052
11108
  cleanup2();
@@ -11132,15 +11188,24 @@ function buildResponseStream(socket, leftover, head, signal, idleTimeoutMs, onDe
11132
11188
  source.write(leftover);
11133
11189
  }
11134
11190
  socket.pipe(source);
11191
+ const stages = [source];
11192
+ let framing;
11135
11193
  let responseBody = source;
11136
11194
  if (head.chunked) {
11137
- responseBody = responseBody.pipe(new ChunkedDecodeStream());
11195
+ framing = new ChunkedDecodeStream();
11138
11196
  } else if (typeof head.contentLength === "number") {
11139
- 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);
11140
11202
  }
11141
11203
  if (head.gzip) {
11142
11204
  responseBody = responseBody.pipe(createGunzip());
11205
+ stages.push(responseBody);
11143
11206
  }
11207
+ let settled = false;
11208
+ let socketEnded = false;
11144
11209
  let idleTimer;
11145
11210
  const clearIdle = () => {
11146
11211
  if (idleTimer) {
@@ -11154,31 +11219,55 @@ function buildResponseStream(socket, leftover, head, signal, idleTimeoutMs, onDe
11154
11219
  clearIdle();
11155
11220
  idleTimer = setTimeout(() => {
11156
11221
  onDebug?.(`agy transport idle timeout after ${idleTimeoutMs}ms with no body data`);
11157
- 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"));
11158
11223
  }, idleTimeoutMs);
11159
11224
  };
11160
- socket.on("data", armIdle);
11161
- armIdle();
11162
- const abort = () => socket.destroy(new DOMException("The operation was aborted", "AbortError"));
11163
- 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;
11164
11239
  clearIdle();
11165
11240
  socket.off("data", armIdle);
11241
+ socket.off("end", onSocketEnd);
11242
+ socket.off("close", onSocketClose);
11166
11243
  signal?.removeEventListener("abort", abort);
11167
- };
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();
11168
11266
  if (signal?.aborted) {
11169
11267
  abort();
11170
11268
  } else {
11171
11269
  signal?.addEventListener("abort", abort, { once: true });
11172
11270
  }
11173
- responseBody.once("end", () => {
11174
- cleanup2();
11175
- socket.destroy();
11176
- });
11177
- responseBody.once("error", () => {
11178
- cleanup2();
11179
- socket.destroy();
11180
- });
11181
- responseBody.once("close", cleanup2);
11182
11271
  return Readable.toWeb(responseBody);
11183
11272
  }
11184
11273
  async function fetchWithAgyCliTransport(url, init = {}, options = {}) {
@@ -11236,6 +11325,11 @@ var init_agy_transport = __esm({
11236
11325
  constructor(contentLength) {
11237
11326
  super();
11238
11327
  this.remaining = contentLength;
11328
+ if (this.remaining <= 0)
11329
+ this.push(null);
11330
+ }
11331
+ get complete() {
11332
+ return this.remaining <= 0;
11239
11333
  }
11240
11334
  _transform(chunk, _encoding, callback) {
11241
11335
  if (this.remaining <= 0) {
@@ -11254,10 +11348,21 @@ var init_agy_transport = __esm({
11254
11348
  }
11255
11349
  callback();
11256
11350
  }
11351
+ _flush(callback) {
11352
+ callback(this.remaining > 0 ? new Error("Antigravity response ended before its declared length") : null);
11353
+ }
11257
11354
  };
11258
11355
  ChunkedDecodeStream = class extends Transform {
11259
11356
  buffer = Buffer3.alloc(0);
11357
+ finished = false;
11358
+ get complete() {
11359
+ return this.finished;
11360
+ }
11260
11361
  _transform(chunk, _encoding, callback) {
11362
+ if (this.finished) {
11363
+ callback();
11364
+ return;
11365
+ }
11261
11366
  this.buffer = Buffer3.concat([this.buffer, chunk]);
11262
11367
  try {
11263
11368
  this.flushAvailableChunks();
@@ -11268,8 +11373,9 @@ var init_agy_transport = __esm({
11268
11373
  }
11269
11374
  _flush(callback) {
11270
11375
  try {
11271
- this.flushAvailableChunks();
11272
- callback();
11376
+ if (!this.finished)
11377
+ this.flushAvailableChunks();
11378
+ callback(this.finished ? null : new Error("Antigravity response ended before its final chunk"));
11273
11379
  } catch (error) {
11274
11380
  callback(error instanceof Error ? error : new Error(String(error)));
11275
11381
  }
@@ -11285,16 +11391,19 @@ var init_agy_transport = __esm({
11285
11391
  if (!Number.isFinite(size)) {
11286
11392
  throw new Error(`Invalid chunk size: ${sizeLine}`);
11287
11393
  }
11288
- const chunkStart = lineEnd + 2;
11289
- const chunkEnd = chunkStart + size;
11290
- const nextOffset = chunkEnd + 2;
11291
- if (this.buffer.length < nextOffset)
11292
- return;
11293
11394
  if (size === 0) {
11395
+ if (this.buffer.indexOf("\r\n\r\n", lineEnd) === -1)
11396
+ return;
11397
+ this.finished = true;
11294
11398
  this.buffer = Buffer3.alloc(0);
11295
11399
  this.push(null);
11296
11400
  return;
11297
11401
  }
11402
+ const chunkStart = lineEnd + 2;
11403
+ const chunkEnd = chunkStart + size;
11404
+ const nextOffset = chunkEnd + 2;
11405
+ if (this.buffer.length < nextOffset)
11406
+ return;
11298
11407
  this.push(this.buffer.subarray(chunkStart, chunkEnd));
11299
11408
  this.buffer = this.buffer.subarray(nextOffset);
11300
11409
  }
@@ -13855,8 +13964,8 @@ async function acquireRefreshFileLockWithClock(options) {
13855
13964
  let releaseConfirmed = false;
13856
13965
  let loss;
13857
13966
  let resolveLoss;
13858
- const lostPromise = new Promise((resolve34) => {
13859
- resolveLoss = resolve34;
13967
+ const lostPromise = new Promise((resolve35) => {
13968
+ resolveLoss = resolve35;
13860
13969
  });
13861
13970
  function notifyTimerStep(event) {
13862
13971
  try {
@@ -14020,7 +14129,7 @@ async function acquireRefreshFileLockWithClock(options) {
14020
14129
  }
14021
14130
  }
14022
14131
  async function backoff() {
14023
- await new Promise((resolve34) => setTimeout(resolve34, Math.floor(Math.random() * 4)));
14132
+ await new Promise((resolve35) => setTimeout(resolve35, Math.floor(Math.random() * 4)));
14024
14133
  }
14025
14134
  async function readLockState(notifyReady = true) {
14026
14135
  if (notifyReady && options.onStep)
@@ -14113,7 +14222,7 @@ async function acquireRefreshFileLockWithClock(options) {
14113
14222
  const remainingMs = deadline - performance.now();
14114
14223
  if (remainingMs <= 0)
14115
14224
  throw original;
14116
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
14225
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(delayMs, remainingMs)));
14117
14226
  if (performance.now() >= deadline)
14118
14227
  throw original;
14119
14228
  delayMs = Math.min(delayMs * 2, 50);
@@ -14616,7 +14725,7 @@ async function acquireRefreshFileLockWithClock(options) {
14616
14725
  const remainingMs = deadline - performance.now();
14617
14726
  if (remainingMs <= 0)
14618
14727
  break;
14619
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
14728
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(delayMs, remainingMs)));
14620
14729
  if (windowsPrivateFiles && performance.now() >= deadline)
14621
14730
  break;
14622
14731
  delayMs = Math.min(delayMs * 2, 50);
@@ -14701,7 +14810,7 @@ async function withLock(target, options, fn) {
14701
14810
  timeoutMs: options.timeoutMs
14702
14811
  });
14703
14812
  }
14704
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(25, Math.ceil(remaining))));
14813
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(25, Math.ceil(remaining))));
14705
14814
  }
14706
14815
  }
14707
14816
  var LockContentionError, LockOwnershipError;
@@ -14791,7 +14900,7 @@ async function acquirePoolLock(spec, defaults2, env3) {
14791
14900
  });
14792
14901
  }
14793
14902
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
14794
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(options.retryMs + jitter, remaining)));
14903
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(options.retryMs + jitter, remaining)));
14795
14904
  }
14796
14905
  }
14797
14906
  function definedOnly(spec) {
@@ -17704,11 +17813,11 @@ var init_quota_writer = __esm({
17704
17813
  const left = deadline - performance.now();
17705
17814
  if (left <= 0)
17706
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);
17707
- await new Promise((resolve34) => {
17816
+ await new Promise((resolve35) => {
17708
17817
  const done = () => {
17709
17818
  clearTimeout(timer);
17710
17819
  this.wake.delete(done);
17711
- resolve34();
17820
+ resolve35();
17712
17821
  };
17713
17822
  const timer = setTimeout(done, left);
17714
17823
  this.wake.add(done);
@@ -20440,6 +20549,8 @@ async function request(operation) {
20440
20549
  function wrapHostClient(client) {
20441
20550
  const watchScoped = client.watchScoped?.bind(client);
20442
20551
  const reportUsageScoped = client.reportUsageScoped?.bind(client);
20552
+ const reportCondition = client.reportCondition?.bind(client);
20553
+ const clearCondition = client.clearCondition?.bind(client);
20443
20554
  return {
20444
20555
  listScoped: (...args) => request(() => client.listScoped(...args)),
20445
20556
  getScoped: (...args) => request(() => client.getScoped(...args)),
@@ -20460,6 +20571,12 @@ function wrapHostClient(client) {
20460
20571
  ...reportUsageScoped && {
20461
20572
  reportUsageScoped: (...args) => request(() => reportUsageScoped(...args))
20462
20573
  },
20574
+ ...reportCondition && {
20575
+ reportCondition: (...args) => request(() => reportCondition(...args))
20576
+ },
20577
+ ...clearCondition && {
20578
+ clearCondition: (...args) => request(() => clearCondition(...args))
20579
+ },
20463
20580
  ...client.insula && {
20464
20581
  insula: wrapInsula(client.insula)
20465
20582
  }
@@ -20831,7 +20948,7 @@ async function select(terminal, items, options) {
20831
20948
  writeLine("");
20832
20949
  renderedLines = lines;
20833
20950
  };
20834
- return new Promise((resolve34) => {
20951
+ return new Promise((resolve35) => {
20835
20952
  const wasRaw = stdin.isRaw ?? false;
20836
20953
  const cleanup2 = () => {
20837
20954
  if (cleaned)
@@ -20851,7 +20968,7 @@ async function select(terminal, items, options) {
20851
20968
  };
20852
20969
  const finish = (value) => {
20853
20970
  cleanup2();
20854
- resolve34(value);
20971
+ resolve35(value);
20855
20972
  };
20856
20973
  const onSignal = () => finish(null);
20857
20974
  const onKey = (data) => {
@@ -20891,7 +21008,7 @@ async function select(terminal, items, options) {
20891
21008
  stdin.setRawMode(true);
20892
21009
  } catch {
20893
21010
  cleanup2();
20894
- resolve34(null);
21011
+ resolve35(null);
20895
21012
  return;
20896
21013
  }
20897
21014
  stdin.resume();
@@ -22917,10 +23034,10 @@ async function drainShutdown(pending, onTimeout) {
22917
23034
  try {
22918
23035
  await Promise.race([
22919
23036
  drained,
22920
- new Promise((resolve34) => {
23037
+ new Promise((resolve35) => {
22921
23038
  timer = setTimeout(() => {
22922
23039
  expired = true;
22923
- resolve34();
23040
+ resolve35();
22924
23041
  }, 2e3);
22925
23042
  })
22926
23043
  ]);
@@ -23197,6 +23314,28 @@ function rowFactsOf(row, { includeProviderIds = true } = {}) {
23197
23314
  authMethod: metadata.authMethod
23198
23315
  };
23199
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;
23338
+ }
23200
23339
  function grantReachOf(listed) {
23201
23340
  const { grants, grantTuples } = listed;
23202
23341
  if (grants === void 0 || grantTuples === void 0)
@@ -23235,6 +23374,10 @@ var init_custody = __esm({
23235
23374
  #logger;
23236
23375
  #provenance = /* @__PURE__ */ new WeakMap();
23237
23376
  #reports = /* @__PURE__ */ new WeakMap();
23377
+ #conditionReports = /* @__PURE__ */ new Map();
23378
+ #conditionClears = /* @__PURE__ */ new Map();
23379
+ #conditionsUnsupported = false;
23380
+ #pendingConditionCalls = 0;
23238
23381
  #kept = /* @__PURE__ */ new Map();
23239
23382
  #keptAttempts = /* @__PURE__ */ new WeakMap();
23240
23383
  #usage;
@@ -23253,8 +23396,9 @@ var init_custody = __esm({
23253
23396
  #closed = false;
23254
23397
  /** The view of the last successful `discover()`, for `watchRoster`. */
23255
23398
  #discoveredView;
23399
+ #discoveredConditions = /* @__PURE__ */ new Map();
23256
23400
  #watches = /* @__PURE__ */ new Set();
23257
- #tokenReads = /* @__PURE__ */ new Set();
23401
+ #shutdownWork = /* @__PURE__ */ new Set();
23258
23402
  #warnShutdown;
23259
23403
  #onDrainTimeout;
23260
23404
  #disposing;
@@ -23313,6 +23457,7 @@ var init_custody = __esm({
23313
23457
  if (hasVaultHost() && !isVaultHostClient(next))
23314
23458
  throw new ClaustrumUnreachableError();
23315
23459
  this.#client = next;
23460
+ this.#conditionsUnsupported = false;
23316
23461
  for (const watch2 of this.#watches)
23317
23462
  watch2.restart();
23318
23463
  }
@@ -23381,12 +23526,12 @@ var init_custody = __esm({
23381
23526
  phase: "token read begin"
23382
23527
  });
23383
23528
  const pending = this.#readToken();
23384
- this.#tokenReads.add(pending);
23529
+ this.#shutdownWork.add(pending);
23385
23530
  let value;
23386
23531
  try {
23387
23532
  value = await pending;
23388
23533
  } finally {
23389
- this.#tokenReads.delete(pending);
23534
+ this.#shutdownWork.delete(pending);
23390
23535
  if (phaseDiagnostics.hasSubscribers)
23391
23536
  phaseDiagnostics.publish({
23392
23537
  logger: this.#logger,
@@ -23439,6 +23584,11 @@ var init_custody = __esm({
23439
23584
  async discover(signal) {
23440
23585
  const inventory = await this.#list(signal);
23441
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
+ }
23442
23592
  return inventory;
23443
23593
  }
23444
23594
  async #list(signal) {
@@ -23512,6 +23662,7 @@ var init_custody = __esm({
23512
23662
  });
23513
23663
  continue;
23514
23664
  }
23665
+ const condition = vaultConditionOf(row);
23515
23666
  credentials.push(Object.freeze({
23516
23667
  credentialId: row.id,
23517
23668
  credentialType: type,
@@ -23521,7 +23672,8 @@ var init_custody = __esm({
23521
23672
  },
23522
23673
  state: row.state,
23523
23674
  ...row.email !== void 0 && { email: row.email },
23524
- ...row.orgName !== void 0 && { orgName: row.orgName }
23675
+ ...row.orgName !== void 0 && { orgName: row.orgName },
23676
+ ...condition && { condition }
23525
23677
  }));
23526
23678
  }
23527
23679
  for (const record5 of skipped)
@@ -23729,7 +23881,7 @@ var init_custody = __esm({
23729
23881
  }
23730
23882
  #receiptBackoff(delay5, signal) {
23731
23883
  this.#check(signal);
23732
- return new Promise((resolve34, reject) => {
23884
+ return new Promise((resolve35, reject) => {
23733
23885
  const abort = () => {
23734
23886
  this.#clearTimeout(timer);
23735
23887
  signal.removeEventListener("abort", abort);
@@ -23737,7 +23889,7 @@ var init_custody = __esm({
23737
23889
  };
23738
23890
  const timer = this.#setTimeout(() => {
23739
23891
  signal.removeEventListener("abort", abort);
23740
- resolve34();
23892
+ resolve35();
23741
23893
  }, delay5);
23742
23894
  timer.unref?.();
23743
23895
  signal.addEventListener("abort", abort, { once: true });
@@ -23866,6 +24018,90 @@ var init_custody = __esm({
23866
24018
  throw error;
23867
24019
  }
23868
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
+ }
23869
24105
  /**
23870
24106
  * Watch this consumer's visible vault accounts instead of listing them on a
23871
24107
  * short timer. Opens one `watchScoped` on this custody's client and calls
@@ -23981,15 +24217,17 @@ var init_custody = __esm({
23981
24217
  this.#watches.clear();
23982
24218
  this.#kept.clear();
23983
24219
  const usage = this.#usage.close();
24220
+ const keepClientOpen = usage !== void 0 || this.#pendingConditionCalls > 0;
23984
24221
  if (usage) {
23985
- this.#tokenReads.add(usage);
23986
- void usage.then(() => this.#tokenReads.delete(usage));
23987
- } else
24222
+ this.#shutdownWork.add(usage);
24223
+ void usage.then(() => this.#shutdownWork.delete(usage));
24224
+ }
24225
+ if (!keepClientOpen)
23988
24226
  this.#client.close();
23989
- 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(() => {
23990
24228
  this.#usage.drop();
23991
24229
  this.#usageServed.clear();
23992
- if (usage)
24230
+ if (keepClientOpen)
23993
24231
  this.#client.close();
23994
24232
  });
23995
24233
  }
@@ -24973,7 +25211,7 @@ var init_consumer = __esm({
24973
25211
  this.#shutdown.signal,
24974
25212
  ...signal ? [signal] : []
24975
25213
  ]);
24976
- return new Promise((resolve34, reject) => {
25214
+ return new Promise((resolve35, reject) => {
24977
25215
  const cleanup2 = () => {
24978
25216
  combined.signal.removeEventListener("abort", abort);
24979
25217
  combined.dispose();
@@ -24988,7 +25226,7 @@ var init_consumer = __esm({
24988
25226
  if (combined.signal.aborted)
24989
25227
  reject(combined.signal.reason);
24990
25228
  else
24991
- resolve34(value);
25229
+ resolve35(value);
24992
25230
  }, (error) => {
24993
25231
  cleanup2();
24994
25232
  reject(error);
@@ -25584,6 +25822,36 @@ var init_consumer = __esm({
25584
25822
  throw new ClaustrumConsumerError("no-receipt", "Claustrum dispatch receipt has no active owner");
25585
25823
  await this.#custody.reportFailure(attempt, status, source);
25586
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
+ }
25587
25855
  /**
25588
25856
  * Send on a vault route. `dispatch` builds and sends the request with the
25589
25857
  * receipt's token and may be called twice, so it must be able to rebuild
@@ -25794,12 +26062,12 @@ function unreachableConnect2() {
25794
26062
  return new ClaustrumUnreachableError();
25795
26063
  }
25796
26064
  function untilAborted(pending, signal) {
25797
- return new Promise((resolve34, reject) => {
26065
+ return new Promise((resolve35, reject) => {
25798
26066
  const abort = () => reject(signal.reason);
25799
26067
  signal.addEventListener("abort", abort, { once: true });
25800
26068
  pending.then((value) => {
25801
26069
  signal.removeEventListener("abort", abort);
25802
- resolve34(value);
26070
+ resolve35(value);
25803
26071
  }, (error) => {
25804
26072
  signal.removeEventListener("abort", abort);
25805
26073
  reject(error);
@@ -26190,6 +26458,16 @@ var init_hub = __esm({
26190
26458
  check();
26191
26459
  return custody.reportFailure(attempt, status, source);
26192
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
+ },
26193
26471
  reportUsage: (input2) => {
26194
26472
  if (!state2.released && !generation.ended)
26195
26473
  custody.reportUsage(input2);
@@ -27174,13 +27452,13 @@ async function safeRead(path5, afterReadCheck) {
27174
27452
  let file;
27175
27453
  try {
27176
27454
  file = await open7(path5, constants2.O_RDONLY | constants2.O_NOFOLLOW);
27177
- const stat21 = await file.stat();
27178
- if (!stat21.isFile()) {
27455
+ const stat22 = await file.stat();
27456
+ if (!stat22.isFile()) {
27179
27457
  throw new PiSlotError("unsafe-path");
27180
27458
  }
27181
27459
  await afterReadCheck?.(path5);
27182
27460
  const current = await lstat5(path5);
27183
- if (!current.isFile() || current.dev !== stat21.dev || current.ino !== stat21.ino) {
27461
+ if (!current.isFile() || current.dev !== stat22.dev || current.ino !== stat22.ino) {
27184
27462
  throw new PiSlotError("unsafe-path");
27185
27463
  }
27186
27464
  const bytes = await file.readFile();
@@ -27864,9 +28142,11 @@ var init_pre_response_deadline = __esm({
27864
28142
  this.cancelTimer = void 0;
27865
28143
  }
27866
28144
  resume() {
28145
+ const paused = !this.active;
27867
28146
  this.active = true;
27868
28147
  this.check();
27869
- this.arm();
28148
+ if (paused)
28149
+ this.arm();
27870
28150
  }
27871
28151
  /** Cancel a response that arrives after its sender lost the abort race. */
27872
28152
  open(work) {
@@ -28079,8 +28359,8 @@ function getDefaultTierId(allowedTiers) {
28079
28359
  return allowedTiers[0]?.id;
28080
28360
  }
28081
28361
  function wait(ms) {
28082
- return new Promise((resolve34) => {
28083
- setTimeout(resolve34, ms);
28362
+ return new Promise((resolve35) => {
28363
+ setTimeout(resolve35, ms);
28084
28364
  });
28085
28365
  }
28086
28366
  function extractManagedProjectId(payload) {
@@ -28121,7 +28401,7 @@ function invalidateProjectContextCache(refresh) {
28121
28401
  function clearProvisionFailedKeys() {
28122
28402
  provisionFailedKeys.clear();
28123
28403
  }
28124
- async function loadManagedProject(accessToken, _projectId) {
28404
+ async function loadManagedProject(accessToken, _projectId, admit2) {
28125
28405
  const requestBody = buildBootstrapRequestBody();
28126
28406
  const loadHeaders = buildAntigravityHarnessBootstrapHeaders(accessToken);
28127
28407
  const loadEndpoints = Array.from(/* @__PURE__ */ new Set([
@@ -28129,6 +28409,8 @@ async function loadManagedProject(accessToken, _projectId) {
28129
28409
  ...ANTIGRAVITY_ENDPOINT_FALLBACKS
28130
28410
  ]));
28131
28411
  for (const baseEndpoint of loadEndpoints) {
28412
+ if (admit2)
28413
+ await admit2();
28132
28414
  try {
28133
28415
  const response = await fetchWithAgyCliTransport(`${baseEndpoint}/v1internal:loadCodeAssist`, {
28134
28416
  method: "POST",
@@ -28148,7 +28430,7 @@ async function loadManagedProject(accessToken, _projectId) {
28148
28430
  }
28149
28431
  return null;
28150
28432
  }
28151
- async function onboardManagedProject(accessToken, tierId, projectId, attempts2 = 10, delayMs = 5e3) {
28433
+ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 = 10, delayMs = 5e3, admit2) {
28152
28434
  const requestBody = { tierId };
28153
28435
  const onboardEndpoints = Array.from(/* @__PURE__ */ new Set([
28154
28436
  ANTIGRAVITY_ENDPOINT_PROD,
@@ -28157,6 +28439,8 @@ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 =
28157
28439
  ]));
28158
28440
  for (const baseEndpoint of onboardEndpoints) {
28159
28441
  for (let attempt = 0; attempt < attempts2; attempt += 1) {
28442
+ if (admit2)
28443
+ await admit2();
28160
28444
  try {
28161
28445
  const response = await fetchWithAgyCliTransport(`${baseEndpoint}/v1internal:onboardUser`, {
28162
28446
  method: "POST",
@@ -28191,7 +28475,7 @@ async function onboardManagedProject(accessToken, tierId, projectId, attempts2 =
28191
28475
  }
28192
28476
  return void 0;
28193
28477
  }
28194
- async function ensureProjectContext(auth) {
28478
+ async function ensureProjectContext(auth, admit2) {
28195
28479
  const accessToken = auth.access;
28196
28480
  if (!accessToken) {
28197
28481
  return { auth, effectiveProjectId: "" };
@@ -28235,7 +28519,7 @@ async function ensureProjectContext(auth) {
28235
28519
  capturedTier
28236
28520
  };
28237
28521
  };
28238
- const loadPayload = await loadManagedProject(accessToken, parts.projectId ?? fallbackProjectId);
28522
+ const loadPayload = await loadManagedProject(accessToken, parts.projectId ?? fallbackProjectId, admit2);
28239
28523
  const capturedTierId = loadPayload?.currentTier?.id;
28240
28524
  const paidTierId = typeof loadPayload?.paidTier === "string" ? loadPayload.paidTier : loadPayload?.paidTier?.id;
28241
28525
  const tierFromPayload = capturedTierId ? {
@@ -28252,7 +28536,7 @@ async function ensureProjectContext(auth) {
28252
28536
  tierId,
28253
28537
  projectId: parts.projectId
28254
28538
  });
28255
- const provisionedProjectId = await onboardManagedProject(accessToken, tierId, parts.projectId);
28539
+ const provisionedProjectId = await onboardManagedProject(accessToken, tierId, parts.projectId, void 0, void 0, admit2);
28256
28540
  if (provisionedProjectId) {
28257
28541
  log3.debug("Successfully provisioned managed project", {
28258
28542
  provisionedProjectId
@@ -30492,12 +30776,12 @@ var init_vault_provider_state = __esm({
30492
30776
  function untilAborted2(pending, signal) {
30493
30777
  if (!signal)
30494
30778
  return pending;
30495
- return new Promise((resolve34, reject) => {
30779
+ return new Promise((resolve35, reject) => {
30496
30780
  const abort = () => reject(signal.reason);
30497
30781
  signal.addEventListener("abort", abort, { once: true });
30498
30782
  if (signal.aborted)
30499
30783
  abort();
30500
- pending.then(resolve34, reject).finally(() => signal.removeEventListener("abort", abort));
30784
+ pending.then(resolve35, reject).finally(() => signal.removeEventListener("abort", abort));
30501
30785
  });
30502
30786
  }
30503
30787
  async function resolveClaustrumConnectionPath(explicit) {
@@ -30679,6 +30963,8 @@ function createAntigravityVaultAccountSource(options) {
30679
30963
  return response;
30680
30964
  },
30681
30965
  reportServedStatus,
30966
+ reportCondition: async (admission, input2) => consumer.reportCondition(issuedEntry(admission).receipt, input2),
30967
+ clearCondition: async (admission) => consumer.clearCondition(issuedEntry(admission).receipt),
30682
30968
  attribution: (admission) => {
30683
30969
  issuedEntry(admission);
30684
30970
  return Object.freeze({
@@ -31634,6 +31920,7 @@ var init_provider_key_policy = __esm({
31634
31920
  });
31635
31921
 
31636
31922
  // src/plugin/shared/vault-request-credentials.ts
31923
+ import { stat as stat11 } from "node:fs/promises";
31637
31924
  function vaultAccountRows(routes) {
31638
31925
  return routes.map((route, index) => ({
31639
31926
  index,
@@ -31681,10 +31968,7 @@ function createVaultRequestCredentials(source, onAdmitted) {
31681
31968
  const admission = await source.admit(account.route, signal);
31682
31969
  if (onAdmitted)
31683
31970
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
31684
- const grant = new VaultSendGrant(
31685
- admission,
31686
- (status) => source.reportServedStatus(admission, status)
31687
- );
31971
+ const grant = new VaultSendGrant(admission, source);
31688
31972
  issued.set(grant, admission);
31689
31973
  return grant;
31690
31974
  }
@@ -31739,14 +32023,6 @@ function durableSelectionOf(row) {
31739
32023
  ...row.cooldownReason !== void 0 ? { cooldownReason: row.cooldownReason } : {},
31740
32024
  ...row.fingerprint !== void 0 ? { fingerprint: structuredClone(row.fingerprint) } : {},
31741
32025
  ...row.fingerprintHistory !== void 0 ? { fingerprintHistory: structuredClone(row.fingerprintHistory) } : {},
31742
- ...row.verificationRequired !== void 0 ? { verificationRequired: row.verificationRequired } : {},
31743
- ...row.verificationRequiredAt !== void 0 ? { verificationRequiredAt: row.verificationRequiredAt } : {},
31744
- ...row.verificationRequiredReason !== void 0 ? { verificationRequiredReason: row.verificationRequiredReason } : {},
31745
- ...row.verificationUrl !== void 0 ? { verificationUrl: row.verificationUrl } : {},
31746
- ...row.accountIneligible !== void 0 ? { accountIneligible: row.accountIneligible } : {},
31747
- ...row.accountIneligibleAt !== void 0 ? { accountIneligibleAt: row.accountIneligibleAt } : {},
31748
- ...row.accountIneligibleReason !== void 0 ? { accountIneligibleReason: row.accountIneligibleReason } : {},
31749
- ...row.eligibilityStateUpdatedAt !== void 0 ? { eligibilityStateUpdatedAt: row.eligibilityStateUpdatedAt } : {},
31750
32026
  ...row.dailyRequestCounts !== void 0 ? { dailyRequestCounts: { ...row.dailyRequestCounts } } : {}
31751
32027
  };
31752
32028
  }
@@ -31833,6 +32109,7 @@ function createVaultSelectionState(options) {
31833
32109
  const attributions = /* @__PURE__ */ new WeakMap();
31834
32110
  const changed = /* @__PURE__ */ new Set();
31835
32111
  const clears = /* @__PURE__ */ new WeakMap();
32112
+ const accessVerdicts = /* @__PURE__ */ new WeakMap();
31836
32113
  const legacyLoads = /* @__PURE__ */ new Map();
31837
32114
  let writing = Promise.resolve();
31838
32115
  const mark = (row) => {
@@ -31848,9 +32125,11 @@ function createVaultSelectionState(options) {
31848
32125
  const attribution = attributions.get(row);
31849
32126
  if (attribution === void 0) return;
31850
32127
  changed.delete(row);
31851
- const selection = durableSelectionOf(row);
32128
+ const { coolingDownUntil, cooldownReason, ...selection } = durableSelectionOf(row);
31852
32129
  const cleared = clears.get(row);
31853
32130
  clears.delete(row);
32131
+ const verdicts = accessVerdicts.get(row);
32132
+ accessVerdicts.delete(row);
31854
32133
  try {
31855
32134
  await options.source.commitState(attribution, (current) => {
31856
32135
  let metadata = applyRateLimitObservation(
@@ -31872,6 +32151,20 @@ function createVaultSelectionState(options) {
31872
32151
  selection.rateLimitResetTimes ?? {},
31873
32152
  selection.rateLimitWrittenAt ?? {}
31874
32153
  );
32154
+ if (coolingDownUntil != null && cooldownReason != null && (metadata.coolingDownUntil == null || coolingDownUntil > metadata.coolingDownUntil)) {
32155
+ metadata = applyCooldownObservation(metadata, {
32156
+ until: coolingDownUntil,
32157
+ reason: cooldownReason
32158
+ });
32159
+ }
32160
+ for (const verdict of verdicts ?? []) {
32161
+ const applied = applyAccessVerdict(metadata, verdict);
32162
+ if (applied) {
32163
+ metadata = applied.metadata;
32164
+ if (verdict.kind === "cleared")
32165
+ metadata.eligibilityStateUpdatedAt = verdict.observedAt;
32166
+ }
32167
+ }
31875
32168
  if (cleared) {
31876
32169
  const resets = { ...metadata.rateLimitResetTimes };
31877
32170
  const written = { ...metadata.rateLimitWrittenAt };
@@ -31924,7 +32217,12 @@ function createVaultSelectionState(options) {
31924
32217
  switched: mark,
31925
32218
  lastUsed: mark,
31926
32219
  usage: mark,
31927
- accessVerdict: mark,
32220
+ accessVerdict(row, verdict) {
32221
+ const pending = accessVerdicts.get(row);
32222
+ if (pending) pending.push(verdict);
32223
+ else accessVerdicts.set(row, [verdict]);
32224
+ mark(row);
32225
+ },
31928
32226
  fingerprint: mark,
31929
32227
  requestSave: () => {
31930
32228
  void flush2();
@@ -31933,16 +32231,20 @@ function createVaultSelectionState(options) {
31933
32231
  admitted(row, attribution) {
31934
32232
  attributions.set(row, attribution);
31935
32233
  },
31936
- async hydrate(rows) {
32234
+ async hydrate(rows, keptKeys) {
31937
32235
  const file = await options.readState();
31938
32236
  for (const row of rows) {
31939
32237
  const identity4 = row.route.accountIdentity;
31940
32238
  if (!Object.hasOwn(file.accounts, identity4)) continue;
31941
32239
  const state2 = file.accounts[identity4];
31942
32240
  if (state2 === void 0 || !stateBelongsTo(state2, row)) continue;
31943
- if (state2.metadata !== void 0)
31944
- applyDurableSelection(row, state2.metadata);
31945
- const stamped = stampRateLimitWrites(row, now2());
32241
+ const kept = keptKeys?.has(vaultAccountRowKey(row));
32242
+ if (state2.metadata !== void 0) {
32243
+ if (kept)
32244
+ row.rateLimitClearedAt = state2.metadata.rateLimitClearedAt ?? void 0;
32245
+ else applyDurableSelection(row, state2.metadata);
32246
+ }
32247
+ const stamped = kept ? [] : stampRateLimitWrites(row, now2());
31946
32248
  if (stamped.length) {
31947
32249
  const legacyKey = legacyLimitKey({
31948
32250
  ...state2.observed,
@@ -32020,6 +32322,17 @@ function createVaultSelectionState(options) {
32020
32322
  }
32021
32323
  };
32022
32324
  }
32325
+ async function providerStateSignature(path5) {
32326
+ if (path5 === void 0) return null;
32327
+ try {
32328
+ const info = await stat11(path5, { bigint: true });
32329
+ return info.isFile() ? `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` : null;
32330
+ } catch (error) {
32331
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
32332
+ return "missing";
32333
+ return null;
32334
+ }
32335
+ }
32023
32336
  function createVaultAccountPool(options) {
32024
32337
  const { source, durable } = options;
32025
32338
  const state2 = durable ? createVaultSelectionState({
@@ -32042,23 +32355,54 @@ function createVaultAccountPool(options) {
32042
32355
  const refusal3 = options.emptyRosterRefusal;
32043
32356
  if (refusal3)
32044
32357
  credentials.emptyRosterRefusal = () => refusal3(source.emptyRosterCause?.() ?? "unknown");
32358
+ const clock2 = options.now ?? Date.now;
32359
+ const refreshKeptRow = (prior, fresh) => {
32360
+ refreshVaultAccountRow(prior, fresh);
32361
+ const clearedAt = fresh.rateLimitClearedAt;
32362
+ if (clearedAt !== void 0 && clearedAt > (prior.rateLimitClearedAt ?? 0)) {
32363
+ prior.rateLimitClearedAt = clearedAt;
32364
+ reconcileManualLimitClear(prior);
32365
+ }
32366
+ const checkedAt = fresh.cachedQuotaUpdatedAt;
32367
+ if (fresh.cachedQuota !== void 0 && checkedAt !== void 0 && checkedAt > (prior.cachedQuotaUpdatedAt ?? 0) && checkedAt <= clock2()) {
32368
+ prior.cachedQuota = fresh.cachedQuota;
32369
+ prior.cachedQuotaUpdatedAt = checkedAt;
32370
+ selector.reconcileQuotaReading(prior, false);
32371
+ }
32372
+ };
32373
+ let hydratedSignature = null;
32045
32374
  const rowsFromSource = async () => {
32046
32375
  const rows = vaultAccountRows(source.routes());
32047
- if (state2) {
32048
- const kept = new Set(selector.rows.map(vaultAccountRowKey));
32049
- const added = rows.filter((row) => !kept.has(vaultAccountRowKey(row)));
32050
- if (added.length > 0) await state2.hydrate(added);
32376
+ if (!state2 || !durable || rows.length === 0) return { rows };
32377
+ const signature = await providerStateSignature(durable.stateFile);
32378
+ const kept = new Set(selector.rows.map(vaultAccountRowKey));
32379
+ const added = rows.some((row) => !kept.has(vaultAccountRowKey(row)));
32380
+ if (!added && signature !== null && signature === hydratedSignature)
32381
+ return { rows };
32382
+ try {
32383
+ await state2.hydrate(rows, kept);
32384
+ } catch (error) {
32385
+ if (added) throw error;
32386
+ try {
32387
+ durable.onReadFailure?.();
32388
+ } catch {
32389
+ }
32390
+ return { rows, signature: null };
32051
32391
  }
32052
- return rows;
32392
+ return { rows, signature };
32053
32393
  };
32054
- const replace = async () => {
32055
- selector.replaceAccounts(await rowsFromSource(), {
32394
+ const install = ({
32395
+ rows,
32396
+ signature
32397
+ }) => {
32398
+ selector.replaceAccounts(rows, {
32056
32399
  keyOf: vaultAccountRowKey,
32057
- refresh: refreshVaultAccountRow
32400
+ refresh: refreshKeptRow
32058
32401
  });
32402
+ if (signature !== void 0) hydratedSignature = signature;
32059
32403
  };
32404
+ const replace = async () => install(await rowsFromSource());
32060
32405
  let firstRead = null;
32061
- const clock2 = options.now ?? Date.now;
32062
32406
  const schedule2 = options.schedule ?? ((callback, delayMs) => {
32063
32407
  const timer = setTimeout(callback, delayMs);
32064
32408
  timer.unref?.();
@@ -32077,12 +32421,8 @@ function createVaultAccountPool(options) {
32077
32421
  firstReadStartedAt = clock2();
32078
32422
  firstRead = (async () => {
32079
32423
  await source.refresh();
32080
- const rows = await rowsFromSource();
32081
- if (current())
32082
- selector.replaceAccounts(rows, {
32083
- keyOf: vaultAccountRowKey,
32084
- refresh: refreshVaultAccountRow
32085
- });
32424
+ const loaded = await rowsFromSource();
32425
+ if (current()) install(loaded);
32086
32426
  })().then(
32087
32427
  () => {
32088
32428
  if (current()) firstReadStartedAt = null;
@@ -32103,12 +32443,12 @@ function createVaultAccountPool(options) {
32103
32443
  try {
32104
32444
  return await Promise.race([
32105
32445
  read.then(() => true),
32106
- new Promise((resolve34, reject) => {
32446
+ new Promise((resolve35, reject) => {
32107
32447
  const abort = () => reject(signal?.reason);
32108
32448
  signal?.addEventListener("abort", abort, { once: true });
32109
32449
  detachAbort = () => signal?.removeEventListener("abort", abort);
32110
32450
  if (remaining !== void 0)
32111
- cancelTimer2 = schedule2(() => resolve34(false), remaining);
32451
+ cancelTimer2 = schedule2(() => resolve35(false), remaining);
32112
32452
  if (signal?.aborted) abort();
32113
32453
  })
32114
32454
  ]);
@@ -32197,7 +32537,7 @@ function vaultQuotaState(quota, at) {
32197
32537
  }
32198
32538
  async function checkVaultQuota(input2) {
32199
32539
  const state2 = input2.pool.state;
32200
- const rows = [...input2.pool.selector.rows];
32540
+ const routes = input2.routes ?? input2.pool.selector.rows.map((row) => row.route);
32201
32541
  const now2 = input2.now ?? (() => Date.now());
32202
32542
  const reportError = (error) => {
32203
32543
  try {
@@ -32208,11 +32548,11 @@ async function checkVaultQuota(input2) {
32208
32548
  let checked = 0;
32209
32549
  if (state2 === void 0) input2.onOutcome?.("state-invalid");
32210
32550
  const readings = [];
32211
- for (const row of rows) {
32551
+ for (const route of routes) {
32212
32552
  if (input2.signal.aborted || state2 === void 0) break;
32213
32553
  try {
32214
32554
  input2.onStage?.("fetch");
32215
- const answer = await input2.fetchReading(row.route, input2.signal);
32555
+ const answer = await input2.fetchReading(route, input2.signal);
32216
32556
  input2.signal.throwIfAborted();
32217
32557
  if (answer === void 0) {
32218
32558
  input2.onOutcome?.("fetch-failed");
@@ -32236,7 +32576,7 @@ async function checkVaultQuota(input2) {
32236
32576
  }
32237
32577
  }
32238
32578
  if (state2 === void 0 || readings.length === 0 || input2.signal.aborted)
32239
- return { checked, notChecked: rows.length - checked };
32579
+ return { checked, notChecked: routes.length - checked };
32240
32580
  let results;
32241
32581
  try {
32242
32582
  input2.onStage?.("commit");
@@ -32244,8 +32584,11 @@ async function checkVaultQuota(input2) {
32244
32584
  results = await state2.recordQuotas(readings, input2.signal);
32245
32585
  } catch (error) {
32246
32586
  for (const _ of readings) reportError(error);
32247
- return { checked, notChecked: rows.length - checked };
32587
+ return { checked, notChecked: routes.length - checked };
32248
32588
  }
32589
+ const liveByRoute = new Map(
32590
+ input2.pool.selector.rows.map((row) => [row.route.routeId, row])
32591
+ );
32249
32592
  for (const [at, { attribution, quota: reading }] of readings.entries()) {
32250
32593
  const result = results[at];
32251
32594
  if (result === void 0 || result.status === "refused") {
@@ -32263,17 +32606,15 @@ async function checkVaultQuota(input2) {
32263
32606
  }
32264
32607
  checked += 1;
32265
32608
  input2.onOutcome?.("recorded");
32266
- const live = input2.pool.selector.rows.find(
32267
- (candidate) => candidate.route.routeId === attribution.routeId && candidate.route.credentialId === attribution.credentialId && candidate.route.accountIdentity === attribution.accountIdentity
32268
- );
32269
- if (live !== void 0) {
32609
+ const live = liveByRoute.get(attribution.routeId);
32610
+ if (live?.route.credentialId === attribution.credentialId && live.route.accountIdentity === attribution.accountIdentity) {
32270
32611
  const cached = cachedQuotaOf(reading);
32271
32612
  if (cached !== void 0) live.cachedQuota = cached;
32272
32613
  live.cachedQuotaUpdatedAt = reading.cachedQuotaUpdatedAt ?? void 0;
32273
32614
  input2.pool.selector.reconcileQuotaReading(live);
32274
32615
  }
32275
32616
  }
32276
- return { checked, notChecked: rows.length - checked };
32617
+ return { checked, notChecked: routes.length - checked };
32277
32618
  }
32278
32619
  var VaultSendGrant, VAULT_REFRESH_STALL_MS, VAULT_DISPLAY_ROSTER_WAIT_MS;
32279
32620
  var init_vault_request_credentials = __esm({
@@ -32287,7 +32628,9 @@ var init_vault_request_credentials = __esm({
32287
32628
  recordVersion;
32288
32629
  projectId;
32289
32630
  report401;
32290
- constructor(admission, report) {
32631
+ reportCondition;
32632
+ clearCondition;
32633
+ constructor(admission, source) {
32291
32634
  Object.defineProperty(this, "accessToken", {
32292
32635
  value: admission.accessToken,
32293
32636
  enumerable: false
@@ -32297,7 +32640,9 @@ var init_vault_request_credentials = __esm({
32297
32640
  this.recordVersion = admission.recordVersion;
32298
32641
  this.projectId = admission.projectId;
32299
32642
  this.fromKeptReceipt = admission.fromKeptReceipt;
32300
- this.report401 = report;
32643
+ this.report401 = (status) => source.reportServedStatus(admission, status);
32644
+ this.reportCondition = source.reportCondition?.bind(source, admission);
32645
+ this.clearCondition = source.clearCondition?.bind(source, admission);
32301
32646
  }
32302
32647
  };
32303
32648
  VAULT_REFRESH_STALL_MS = 3e4;
@@ -32358,7 +32703,7 @@ var init_vault_insula_quota = __esm({
32358
32703
  });
32359
32704
 
32360
32705
  // src/plugin/vault-custody.ts
32361
- import { chmod as chmod3, mkdir as mkdir13, readFile as readFile12, stat as stat11 } from "node:fs/promises";
32706
+ import { chmod as chmod3, mkdir as mkdir13, readFile as readFile12, stat as stat12 } from "node:fs/promises";
32362
32707
  import { join as join15 } from "node:path";
32363
32708
  async function enrollmentFilesIdentity(paths) {
32364
32709
  const takenAt = performance.now();
@@ -32366,7 +32711,7 @@ async function enrollmentFilesIdentity(paths) {
32366
32711
  const parts = [];
32367
32712
  for (const path5 of [paths.tokenPath, paths.statePath]) {
32368
32713
  try {
32369
- const info = await stat11(path5, { bigint: true });
32714
+ const info = await stat12(path5, { bigint: true });
32370
32715
  if (info.ino === 0n) coarse = true;
32371
32716
  parts.push(
32372
32717
  `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
@@ -32634,11 +32979,11 @@ function createOpenCodeVaultCustody(options) {
32634
32979
  ].join("\n");
32635
32980
  const waitForApproval = async () => {
32636
32981
  while (!closed2) {
32637
- await new Promise((resolve34) => {
32982
+ await new Promise((resolve35) => {
32638
32983
  const done = () => {
32639
32984
  clearTimeout(timer);
32640
32985
  cancelWait = void 0;
32641
- resolve34();
32986
+ resolve35();
32642
32987
  };
32643
32988
  const timer = setTimeout(done, 2e3);
32644
32989
  timer.unref?.();
@@ -33297,7 +33642,7 @@ var init_process_heartbeat = __esm({
33297
33642
  });
33298
33643
 
33299
33644
  // src/version-fence.ts
33300
- import { readdir as readdir4, readFile as readFile14, stat as stat12, unlink as unlink11 } from "node:fs/promises";
33645
+ import { readdir as readdir4, readFile as readFile14, stat as stat13, unlink as unlink11 } from "node:fs/promises";
33301
33646
  import { homedir as homedir3, uptime } from "node:os";
33302
33647
  import { join as join17 } from "node:path";
33303
33648
  function defaultStateHome() {
@@ -33417,7 +33762,7 @@ async function staleRecord(path5, record5, boot, heartbeat) {
33417
33762
  let start = heartbeat ? record5.startedAt : void 0;
33418
33763
  if (start === void 0) {
33419
33764
  try {
33420
- start = (await stat12(path5)).mtimeMs;
33765
+ start = (await stat13(path5)).mtimeMs;
33421
33766
  } catch {
33422
33767
  return false;
33423
33768
  }
@@ -33546,7 +33891,7 @@ import {
33546
33891
  readFile as readFile15,
33547
33892
  rename as rename11,
33548
33893
  rmdir as rmdir2,
33549
- stat as stat13,
33894
+ stat as stat14,
33550
33895
  unlink as unlink12
33551
33896
  } from "node:fs/promises";
33552
33897
  import { basename as basename8, dirname as dirname21, join as join18, resolve as resolve20 } from "node:path";
@@ -34465,7 +34810,7 @@ async function physicalAliases(location, files) {
34465
34810
  async function samePhysical(a, b) {
34466
34811
  const id = async (path5) => {
34467
34812
  try {
34468
- const info = await stat13(path5, { bigint: true });
34813
+ const info = await stat14(path5, { bigint: true });
34469
34814
  return info.ino === 0n ? void 0 : `${info.dev}:${info.ino}`;
34470
34815
  } catch (error) {
34471
34816
  const code2 = error.code;
@@ -34731,7 +35076,7 @@ function lockHolderText(name) {
34731
35076
  }
34732
35077
  async function exists3(path5) {
34733
35078
  try {
34734
- await stat13(path5);
35079
+ await stat14(path5);
34735
35080
  return true;
34736
35081
  } catch (error) {
34737
35082
  const code2 = error.code;
@@ -35634,13 +35979,13 @@ function closeDebugStream(state2) {
35634
35979
  state2.logWriter = () => {
35635
35980
  };
35636
35981
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
35637
- return new Promise((resolve34) => {
35638
- current.once("close", () => resolve34());
35639
- current.once("error", () => resolve34());
35982
+ return new Promise((resolve35) => {
35983
+ current.once("close", () => resolve35());
35984
+ current.once("error", () => resolve35());
35640
35985
  try {
35641
35986
  current.end();
35642
35987
  } catch {
35643
- resolve34();
35988
+ resolve35();
35644
35989
  }
35645
35990
  });
35646
35991
  }
@@ -35905,13 +36250,13 @@ function closeDebugLog() {
35905
36250
  if (!state2 || !current) return Promise.resolve();
35906
36251
  state2.logStream = null;
35907
36252
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
35908
- return new Promise((resolve34) => {
35909
- current.once("close", () => resolve34());
35910
- current.once("error", () => resolve34());
36253
+ return new Promise((resolve35) => {
36254
+ current.once("close", () => resolve35());
36255
+ current.once("error", () => resolve35());
35911
36256
  try {
35912
36257
  current.end();
35913
36258
  } catch {
35914
- resolve34();
36259
+ resolve35();
35915
36260
  }
35916
36261
  });
35917
36262
  }
@@ -36435,12 +36780,12 @@ async function startOAuthListener({
36435
36780
  let resolveCallback;
36436
36781
  let rejectCallback;
36437
36782
  let timeoutHandle;
36438
- const callbackPromise = new Promise((resolve34, reject) => {
36783
+ const callbackPromise = new Promise((resolve35, reject) => {
36439
36784
  resolveCallback = (url) => {
36440
36785
  if (settled) return;
36441
36786
  settled = true;
36442
36787
  if (timeoutHandle) clearTimeout(timeoutHandle);
36443
- resolve34(url);
36788
+ resolve35(url);
36444
36789
  };
36445
36790
  rejectCallback = (error) => {
36446
36791
  if (settled) return;
@@ -36599,7 +36944,7 @@ async function startOAuthListener({
36599
36944
  });
36600
36945
  });
36601
36946
  const bindAddress = getBindAddress();
36602
- await new Promise((resolve34, reject) => {
36947
+ await new Promise((resolve35, reject) => {
36603
36948
  const handleError = (error) => {
36604
36949
  server.off("error", handleError);
36605
36950
  if (error.code === "EADDRINUSE") {
@@ -36615,7 +36960,7 @@ async function startOAuthListener({
36615
36960
  server.once("error", handleError);
36616
36961
  server.listen(port, bindAddress, () => {
36617
36962
  server.off("error", handleError);
36618
- resolve34();
36963
+ resolve35();
36619
36964
  });
36620
36965
  });
36621
36966
  server.on("error", (error) => {
@@ -36623,7 +36968,7 @@ async function startOAuthListener({
36623
36968
  });
36624
36969
  return {
36625
36970
  waitForCallback: () => callbackPromise,
36626
- close: () => new Promise((resolve34, reject) => {
36971
+ close: () => new Promise((resolve35, reject) => {
36627
36972
  server.close((error) => {
36628
36973
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
36629
36974
  reject(error);
@@ -36632,7 +36977,7 @@ async function startOAuthListener({
36632
36977
  if (!settled) {
36633
36978
  rejectCallback(new Error("OAuth listener closed before callback"));
36634
36979
  }
36635
- resolve34();
36980
+ resolve35();
36636
36981
  });
36637
36982
  })
36638
36983
  };
@@ -36648,11 +36993,11 @@ var GA_POOL_PASTE_METHOD_ID = "antigravity-auth-pool-paste";
36648
36993
  var GA_POOL_RECONNECT_METHOD_ID = "antigravity-auth-pool-reconnect";
36649
36994
  var LOGIN_FAILED = "The Antigravity pool login could not be completed.";
36650
36995
  function abortable(pending, signal) {
36651
- return new Promise((resolve34, reject) => {
36996
+ return new Promise((resolve35, reject) => {
36652
36997
  const abort = () => reject(signal.reason);
36653
36998
  if (signal.aborted) abort();
36654
36999
  else signal.addEventListener("abort", abort, { once: true });
36655
- void pending.then(resolve34, reject).finally(() => {
37000
+ void pending.then(resolve35, reject).finally(() => {
36656
37001
  signal.removeEventListener("abort", abort);
36657
37002
  });
36658
37003
  });
@@ -38656,7 +39001,7 @@ function openSettings(definition, options) {
38656
39001
  loaded = windowsSeen.get(path5) !== content;
38657
39002
  windowsSeen.set(path5, content);
38658
39003
  };
38659
- const readFile23 = async ([path5]) => {
39004
+ const readFile24 = async ([path5]) => {
38660
39005
  let text2;
38661
39006
  try {
38662
39007
  text2 = await SettingsFs.readFile(path5, "utf8");
@@ -38693,7 +39038,7 @@ function openSettings(definition, options) {
38693
39038
  snapshot: buildSettingsSnapshot(definition, file, parsed)
38694
39039
  } : { status: "unparseable" };
38695
39040
  };
38696
- const outcome = process.platform === "win32" ? await readFile23([file.path]) : await cache.read([file.path], readFile23);
39041
+ const outcome = process.platform === "win32" ? await readFile24([file.path]) : await cache.read([file.path], readFile24);
38697
39042
  const key2 = JSON.stringify([file.kind, file.path]);
38698
39043
  if (currentSequence <= (committedSequences.get(key2) ?? 0))
38699
39044
  return;
@@ -39871,6 +40216,25 @@ function selectBestVerificationUrl(urls) {
39871
40216
  unique.sort((a, b) => score(b) - score(a));
39872
40217
  return unique[0];
39873
40218
  }
40219
+ function structuredVerificationUrl(bodyText) {
40220
+ const urls = /* @__PURE__ */ new Set();
40221
+ const collect = (payload) => {
40222
+ try {
40223
+ JSON.parse(payload, (key2, value) => {
40224
+ if (typeof value === "string" && /^(?:validation_url|verify_url|verification_url|url)$/i.test(key2) && /^https:\/\//i.test(decodeEscapedText(value).trim()))
40225
+ urls.add(value);
40226
+ return value;
40227
+ });
40228
+ } catch {
40229
+ }
40230
+ };
40231
+ collect(bodyText);
40232
+ for (const rawLine of bodyText.split("\n")) {
40233
+ const line = rawLine.trim();
40234
+ if (line.startsWith("data:")) collect(line.slice(5));
40235
+ }
40236
+ return selectBestVerificationUrl([...urls]);
40237
+ }
39874
40238
  function extractAccountAccessErrorDetails(bodyText) {
39875
40239
  const decodedBody = decodeEscapedText(bodyText);
39876
40240
  const lowerBody = decodedBody.toLowerCase();
@@ -39948,11 +40312,13 @@ function extractAccountAccessErrorDetails(bodyText) {
39948
40312
  (line) => line && !line.startsWith("data:") && /(verify|validation|required|ineligible)/i.test(line)
39949
40313
  );
39950
40314
  }
40315
+ const structuredVerifyUrl = structuredVerificationUrl(bodyText);
39951
40316
  return {
39952
40317
  validationRequired,
39953
40318
  accountIneligible,
39954
40319
  message,
39955
- verifyUrl: selectBestVerificationUrl([...verificationUrls])
40320
+ verifyUrl: selectBestVerificationUrl([...verificationUrls]),
40321
+ ...structuredVerifyUrl && { structuredVerifyUrl }
39956
40322
  };
39957
40323
  }
39958
40324
  function buildAccountAccessProbeRequest(projectId) {
@@ -41133,9 +41499,9 @@ init_dist();
41133
41499
  import { resolve as resolve24 } from "node:path";
41134
41500
 
41135
41501
  // src/sidebar-state.ts
41502
+ import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync8, statSync as statSync6 } from "node:fs";
41136
41503
  init_atomic_write();
41137
41504
  init_file_lock();
41138
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync8 } from "node:fs";
41139
41505
  import { homedir as homedir7 } from "node:os";
41140
41506
  import { dirname as dirname25, join as join23 } from "node:path";
41141
41507
 
@@ -41206,6 +41572,9 @@ function readSidebarState(path5 = getSidebarStateFile()) {
41206
41572
  } catch {
41207
41573
  return { ...DEFAULT_SIDEBAR_STATE };
41208
41574
  }
41575
+ return parseSidebarState(raw);
41576
+ }
41577
+ function parseSidebarState(raw) {
41209
41578
  let parsed;
41210
41579
  try {
41211
41580
  parsed = JSON.parse(raw);
@@ -41546,7 +41915,7 @@ function drainSidebarWrites() {
41546
41915
  return sidebarWriteChain;
41547
41916
  }
41548
41917
  async function sleep3(ms) {
41549
- await new Promise((resolve34) => setTimeout(resolve34, ms));
41918
+ await new Promise((resolve35) => setTimeout(resolve35, ms));
41550
41919
  }
41551
41920
  async function acquireSidebarLockWithRetry(stateFile) {
41552
41921
  const start = Date.now();
@@ -41793,7 +42162,8 @@ function withSidebarPushAfterRefresh(manager, push) {
41793
42162
  refreshOptions
41794
42163
  );
41795
42164
  const lastAccount = accounts[accounts.length - 1];
41796
- if (shouldPush && lastAccount) await pushAfterRefresh(lastAccount);
42165
+ if (shouldPush && refreshOptions.publishSidebar !== false && lastAccount)
42166
+ await pushAfterRefresh(lastAccount);
41797
42167
  return results;
41798
42168
  })()
41799
42169
  );
@@ -41828,10 +42198,29 @@ async function checkAccountsQuotaStandalone(accounts, options) {
41828
42198
  }
41829
42199
  }));
41830
42200
  }
41831
- return checkAccountsQuotaWith(
42201
+ const refused2 = new AbortController();
42202
+ const admit2 = options.assertAdmission;
42203
+ const assertAdmission = admit2 && (async () => {
42204
+ refused2.signal.throwIfAborted();
42205
+ try {
42206
+ await admit2();
42207
+ } catch (error) {
42208
+ refused2.abort(error);
42209
+ throw error;
42210
+ }
42211
+ refused2.signal.throwIfAborted();
42212
+ });
42213
+ const results = await checkAccountsQuotaWith(
41832
42214
  accounts,
41833
- makeFetchAccountQuota(void 0, ANTIGRAVITY_PROVIDER_ID)
42215
+ makeFetchAccountQuota(
42216
+ void 0,
42217
+ ANTIGRAVITY_PROVIDER_ID,
42218
+ void 0,
42219
+ assertAdmission
42220
+ )
41834
42221
  );
42222
+ refused2.signal.throwIfAborted();
42223
+ return results;
41835
42224
  }
41836
42225
  async function pushSidebarQuotaSnapshot(getAccounts, backoffUntil = 0, getActiveIndexByFamily, options = {}) {
41837
42226
  const accounts = getAccounts();
@@ -42105,14 +42494,14 @@ var LocalQuotaGrantStaleError = class extends Error {
42105
42494
  name = "LocalQuotaGrantStaleError";
42106
42495
  };
42107
42496
  function untilQuotaAborted(pending, signal) {
42108
- return new Promise((resolve34, reject) => {
42497
+ return new Promise((resolve35, reject) => {
42109
42498
  const abort = () => reject(signal.reason);
42110
42499
  if (signal.aborted) abort();
42111
42500
  else signal.addEventListener("abort", abort, { once: true });
42112
42501
  void pending.then(
42113
42502
  (value) => {
42114
42503
  signal.removeEventListener("abort", abort);
42115
- resolve34(value);
42504
+ resolve35(value);
42116
42505
  },
42117
42506
  (error) => {
42118
42507
  signal.removeEventListener("abort", abort);
@@ -42210,7 +42599,7 @@ function createAuthorizedFetchAccountQuota(options) {
42210
42599
  }
42211
42600
  };
42212
42601
  }
42213
- function makeFetchAccountQuota(client, providerId, fetchVia) {
42602
+ function makeFetchAccountQuota(client, providerId, fetchVia, assertAdmission) {
42214
42603
  return async (account, signal, purpose = "required") => {
42215
42604
  const index = 0;
42216
42605
  const disabled = account.enabled === false;
@@ -42292,6 +42681,8 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
42292
42681
  }
42293
42682
  try {
42294
42683
  if (accessTokenExpired(auth)) {
42684
+ if (assertAdmission) await assertAdmission();
42685
+ signal.throwIfAborted();
42295
42686
  const refreshed = await refreshAccessToken(
42296
42687
  auth,
42297
42688
  client,
@@ -42305,7 +42696,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
42305
42696
  }
42306
42697
  auth = refreshed;
42307
42698
  }
42308
- const projectContext = await ensureProjectContext(auth);
42699
+ const projectContext = await ensureProjectContext(auth, assertAdmission);
42309
42700
  auth = projectContext.auth;
42310
42701
  const updatedAccount = applyAccountUpdates(
42311
42702
  account,
@@ -42320,11 +42711,20 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
42320
42711
  let fellBackToLegacy = false;
42321
42712
  const authParts = parseRefreshParts(auth.refresh);
42322
42713
  const managedProjectId = authParts.managedProjectId ?? account.managedProjectId;
42714
+ const guarded = assertAdmission ? async (url, init, extra) => {
42715
+ await assertAdmission();
42716
+ signal.throwIfAborted();
42717
+ return fetchWithActiveTimeout(
42718
+ url,
42719
+ { ...init, signal },
42720
+ { timeoutMs: extra.timeoutMs }
42721
+ );
42722
+ } : fetchVia;
42323
42723
  const payloads = await fetchQuotaPayloads({
42324
42724
  accessToken: auth.access ?? "",
42325
42725
  managedProjectId,
42326
42726
  projectId: projectContext.effectiveProjectId,
42327
- fetchVia,
42727
+ fetchVia: guarded,
42328
42728
  logger: log9
42329
42729
  });
42330
42730
  quotaResult = payloads.quota;
@@ -42569,12 +42969,13 @@ function createStoreQuotaService(options) {
42569
42969
  if (options.mayRun && !await options.mayRun())
42570
42970
  return { status: "discarded", result };
42571
42971
  const held2 = target.rowRef === void 0 ? void 0 : heldAccount(manager, target.rowRef);
42572
- if (held2 === void 0) return { status: "discarded", result };
42573
- manager.updateQuotaCache(
42972
+ if (held2 === void 0 || result.checkedAt === void 0 || !manager.updateQuotaCache(
42574
42973
  held2.index,
42575
42974
  result.quota.groups,
42576
- held2.parts.refreshToken
42577
- );
42975
+ held2.parts.refreshToken,
42976
+ result.checkedAt
42977
+ ))
42978
+ return { status: "discarded", result };
42578
42979
  return {
42579
42980
  status: "recorded",
42580
42981
  result,
@@ -42894,12 +43295,12 @@ var BackgroundVaultQuotaRefresh = class {
42894
43295
  outcome.reason = "no-rows";
42895
43296
  return;
42896
43297
  }
42897
- const due = pool.selector.rows.some((row) => {
43298
+ const dueRoutes = pool.selector.rows.filter((row) => {
42898
43299
  const quota = quotaReadingForVaultRoute(row.route, state2);
42899
43300
  const at = quota?.cachedQuotaUpdatedAt;
42900
43301
  return quota?.cachedQuota == null || typeof at !== "number" || !Number.isFinite(at) || at < 0 || now2 - at >= threshold;
42901
- });
42902
- if (!due) {
43302
+ }).map((row) => row.route);
43303
+ if (dueRoutes.length === 0) {
42903
43304
  outcome.reason = "fresh";
42904
43305
  return;
42905
43306
  }
@@ -42908,6 +43309,7 @@ var BackgroundVaultQuotaRefresh = class {
42908
43309
  const report = await checkAndPublishVaultQuota(
42909
43310
  {
42910
43311
  pool,
43312
+ routes: dueRoutes,
42911
43313
  signal: controller.signal,
42912
43314
  now: this.now,
42913
43315
  onStage: (stage) => {
@@ -43036,6 +43438,7 @@ function acquireGaVaultCustody(options) {
43036
43438
  const { custody } = held2;
43037
43439
  let released;
43038
43440
  return {
43441
+ paths: custody.paths,
43039
43442
  readMode: () => custody.readMode(),
43040
43443
  menuSection: () => custody.menuSection(),
43041
43444
  readState: () => custody.readState(),
@@ -43084,7 +43487,12 @@ function sharedVaultQuota(custody, leases, options) {
43084
43487
  source,
43085
43488
  pool: createOpenCodeVaultAccountPool({
43086
43489
  source,
43087
- durable: { source, readState: () => custody.readState() }
43490
+ durable: {
43491
+ source,
43492
+ readState: () => custody.readState(),
43493
+ ...custody.paths ? { stateFile: custody.paths.stateFile } : {},
43494
+ onReadFailure: () => logger3()?.debug("vault-state-read-skipped")
43495
+ }
43088
43496
  })
43089
43497
  };
43090
43498
  return current;
@@ -43322,20 +43730,20 @@ import crypto2 from "node:crypto";
43322
43730
  import { createHash as createHash14 } from "node:crypto";
43323
43731
 
43324
43732
  // src/plugin/cache/signature-cache.ts
43733
+ init_atomic_write();
43325
43734
  init_runtime_paths();
43326
- import {
43327
- existsSync as existsSync9,
43328
- mkdirSync as mkdirSync4,
43329
- readFileSync as readFileSync9,
43330
- renameSync as renameSync4,
43331
- unlinkSync as unlinkSync3,
43332
- writeFileSync as writeFileSync2
43333
- } from "node:fs";
43334
- import { tmpdir as tmpdir3 } from "node:os";
43335
- import { dirname as dirname26, join as join24 } from "node:path";
43735
+ import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
43736
+ import { readFile as readFile16 } from "node:fs/promises";
43737
+ import { resolve as resolve25 } from "node:path";
43336
43738
  function getSignatureCacheFilePath() {
43337
43739
  return stateHomeSignatureCacheFile();
43338
43740
  }
43741
+ var MAX_ENTRIES = 4096;
43742
+ function newestEntries(entries) {
43743
+ if (entries.length <= MAX_ENTRIES) return entries;
43744
+ return entries.sort(([, a], [, b]) => a.timestamp - b.timestamp).slice(-MAX_ENTRIES);
43745
+ }
43746
+ var pendingWrites = /* @__PURE__ */ new Map();
43339
43747
  var SignatureCache = class {
43340
43748
  // In-memory cache: key -> entry with signature and optional thinking text
43341
43749
  cache = /* @__PURE__ */ new Map();
@@ -43350,6 +43758,8 @@ var SignatureCache = class {
43350
43758
  now;
43351
43759
  // State
43352
43760
  dirty = false;
43761
+ revision = 0;
43762
+ pendingWrite;
43353
43763
  writeTimer = null;
43354
43764
  cleanupTimer = null;
43355
43765
  // Statistics
@@ -43386,11 +43796,10 @@ var SignatureCache = class {
43386
43796
  */
43387
43797
  store(key2, signature) {
43388
43798
  if (!this.enabled) return;
43389
- this.cache.set(key2, {
43799
+ this.storeEntry(key2, {
43390
43800
  value: signature,
43391
43801
  timestamp: this.now()
43392
43802
  });
43393
- this.dirty = true;
43394
43803
  }
43395
43804
  /**
43396
43805
  * Retrieve a signature from the cache.
@@ -43441,13 +43850,29 @@ var SignatureCache = class {
43441
43850
  */
43442
43851
  storeThinking(key2, thinkingText, signature, toolIds) {
43443
43852
  if (!this.enabled || !thinkingText || !signature) return;
43444
- this.cache.set(key2, {
43853
+ this.storeEntry(key2, {
43445
43854
  value: signature,
43446
43855
  timestamp: this.now(),
43447
43856
  thinkingText,
43448
43857
  textPreview: thinkingText.slice(0, 100),
43449
43858
  toolIds
43450
43859
  });
43860
+ }
43861
+ storeEntry(key2, entry) {
43862
+ this.cache.delete(key2);
43863
+ this.cache.set(key2, entry);
43864
+ if (this.cache.size > MAX_ENTRIES) {
43865
+ let oldest;
43866
+ let oldestTimestamp = Number.POSITIVE_INFINITY;
43867
+ for (const [candidate, value] of this.cache) {
43868
+ if (oldest === void 0 || value.timestamp < oldestTimestamp) {
43869
+ oldest = candidate;
43870
+ oldestTimestamp = value.timestamp;
43871
+ }
43872
+ }
43873
+ if (oldest !== void 0) this.cache.delete(oldest);
43874
+ }
43875
+ this.revision++;
43451
43876
  this.dirty = true;
43452
43877
  }
43453
43878
  /**
@@ -43516,7 +43941,17 @@ var SignatureCache = class {
43516
43941
  */
43517
43942
  async flush() {
43518
43943
  if (!this.enabled) return true;
43519
- return this.saveToDisk();
43944
+ const path5 = resolve25(this.cacheFilePath);
43945
+ const previous = pendingWrites.get(path5) ?? Promise.resolve(true);
43946
+ const writing = previous.then(() => this.saveToDisk());
43947
+ this.pendingWrite = writing;
43948
+ pendingWrites.set(path5, writing);
43949
+ try {
43950
+ return await writing;
43951
+ } finally {
43952
+ if (this.pendingWrite === writing) this.pendingWrite = void 0;
43953
+ if (pendingWrites.get(path5) === writing) pendingWrites.delete(path5);
43954
+ }
43520
43955
  }
43521
43956
  /**
43522
43957
  * Graceful shutdown: stop timers and flush to disk.
@@ -43531,7 +43966,7 @@ var SignatureCache = class {
43531
43966
  this.cleanupTimer = null;
43532
43967
  }
43533
43968
  if (this.dirty && this.enabled) {
43534
- this.saveToDisk();
43969
+ void this.flush();
43535
43970
  }
43536
43971
  }
43537
43972
  // ===========================================================================
@@ -43566,6 +44001,9 @@ var SignatureCache = class {
43566
44001
  _expired++;
43567
44002
  }
43568
44003
  }
44004
+ if (this.cache.size > MAX_ENTRIES) {
44005
+ this.cache = new Map(newestEntries([...this.cache]));
44006
+ }
43569
44007
  } catch {
43570
44008
  }
43571
44009
  }
@@ -43573,22 +44011,17 @@ var SignatureCache = class {
43573
44011
  * Save cache to disk with atomic write pattern.
43574
44012
  * Merges with existing disk entries that haven't expired.
43575
44013
  */
43576
- saveToDisk() {
44014
+ async saveToDisk() {
43577
44015
  try {
43578
- const dir = dirname26(this.cacheFilePath);
43579
- if (!existsSync9(dir)) {
43580
- mkdirSync4(dir, { recursive: true });
43581
- }
43582
- const now2 = this.now();
43583
44016
  let existingEntries = {};
43584
- if (existsSync9(this.cacheFilePath)) {
43585
- try {
43586
- const content = readFileSync9(this.cacheFilePath, "utf-8");
43587
- const data = JSON.parse(content);
43588
- existingEntries = data.entries || {};
43589
- } catch {
43590
- }
44017
+ try {
44018
+ const content = await readFile16(this.cacheFilePath, "utf-8");
44019
+ const data = JSON.parse(content);
44020
+ existingEntries = data.entries || {};
44021
+ } catch {
43591
44022
  }
44023
+ const now2 = this.now();
44024
+ const revision = this.revision;
43592
44025
  const validDiskEntries = {};
43593
44026
  for (const [key2, entry] of Object.entries(existingEntries)) {
43594
44027
  const age = now2 - entry.timestamp;
@@ -43607,7 +44040,9 @@ var SignatureCache = class {
43607
44040
  version: "1.0",
43608
44041
  memory_ttl_seconds: this.retentionMemoryTtlMs / 1e3,
43609
44042
  disk_ttl_seconds: this.retentionDiskTtlMs / 1e3,
43610
- entries: mergedEntries,
44043
+ entries: Object.fromEntries(
44044
+ newestEntries(Object.entries(mergedEntries))
44045
+ ),
43611
44046
  statistics: {
43612
44047
  memory_hits: this.stats.memoryHits,
43613
44048
  disk_hits: this.stats.diskHits,
@@ -43616,22 +44051,9 @@ var SignatureCache = class {
43616
44051
  last_write: now2
43617
44052
  }
43618
44053
  };
43619
- const tmpPath = join24(
43620
- tmpdir3(),
43621
- `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
43622
- );
43623
- writeFileSync2(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
43624
- try {
43625
- renameSync4(tmpPath, this.cacheFilePath);
43626
- } catch {
43627
- writeFileSync2(this.cacheFilePath, readFileSync9(tmpPath));
43628
- try {
43629
- unlinkSync3(tmpPath);
43630
- } catch {
43631
- }
43632
- }
44054
+ await writeJsonAtomic(this.cacheFilePath, cacheData);
43633
44055
  this.stats.writes++;
43634
- this.dirty = false;
44056
+ if (revision === this.revision) this.dirty = false;
43635
44057
  return true;
43636
44058
  } catch {
43637
44059
  return false;
@@ -43654,8 +44076,8 @@ var SignatureCache = class {
43654
44076
  }
43655
44077
  startWriteTimer() {
43656
44078
  this.writeTimer = setInterval(() => {
43657
- if (this.dirty) {
43658
- this.saveToDisk();
44079
+ if (this.dirty && !this.pendingWrite) {
44080
+ void this.flush();
43659
44081
  }
43660
44082
  }, this.writeIntervalMs);
43661
44083
  }
@@ -43834,11 +44256,18 @@ function createSignatureProcessState(options = {}) {
43834
44256
  updateRetention(shared4.path);
43835
44257
  return;
43836
44258
  }
43837
- if (disks.get(shared4.path) === shared4) disks.delete(shared4.path);
44259
+ const finalWrite = shared4.cache.flush();
44260
+ shared4.finalWrite = finalWrite;
43838
44261
  try {
43839
- await shared4.cache.flush();
44262
+ await finalWrite;
43840
44263
  } finally {
43841
- shared4.cache.shutdown();
44264
+ if (shared4.finalWrite === finalWrite) {
44265
+ shared4.finalWrite = void 0;
44266
+ if (shared4.owners.size === 0) {
44267
+ disks.delete(shared4.path);
44268
+ shared4.cache.shutdown();
44269
+ }
44270
+ }
43842
44271
  }
43843
44272
  };
43844
44273
  return {
@@ -43863,7 +44292,10 @@ function createSignatureProcessState(options = {}) {
43863
44292
  pathReaders.add(consumer);
43864
44293
  updateRetention(path5);
43865
44294
  }
43866
- const readableCache = () => shared4?.cache ?? (path5 ? disks.get(path5)?.cache : void 0);
44295
+ const readableCache = () => {
44296
+ const current = shared4 ?? (path5 ? disks.get(path5) : void 0);
44297
+ if (current?.owners.size) return current.cache;
44298
+ };
43867
44299
  const signatureStore = createSignatureStore();
43868
44300
  let disposed = false;
43869
44301
  return {
@@ -43971,13 +44403,13 @@ function clearSignatureCache(sessionId) {
43971
44403
  }
43972
44404
 
43973
44405
  // src/plugin/image-saver.ts
43974
- import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
44406
+ import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync4, writeFileSync as writeFileSync2 } from "node:fs";
43975
44407
  import { homedir as homedir8 } from "node:os";
43976
- import { join as join25 } from "node:path";
44408
+ import { join as join24 } from "node:path";
43977
44409
  function getImageOutputDir(outputDir) {
43978
- const resolved = outputDir ?? join25(homedir8(), ".opencode", "generated-images");
44410
+ const resolved = outputDir ?? join24(homedir8(), ".opencode", "generated-images");
43979
44411
  if (!existsSync10(resolved)) {
43980
- mkdirSync5(resolved, { recursive: true, mode: 448 });
44412
+ mkdirSync4(resolved, { recursive: true, mode: 448 });
43981
44413
  }
43982
44414
  chmodSync4(resolved, 448);
43983
44415
  return resolved;
@@ -43998,8 +44430,8 @@ function generateImageFilename(mimeType) {
43998
44430
  function saveImageToDisk(base64Data, mimeType, outputDir) {
43999
44431
  try {
44000
44432
  const resolvedOutputDir = getImageOutputDir(outputDir);
44001
- const filePath = join25(resolvedOutputDir, generateImageFilename(mimeType));
44002
- writeFileSync3(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
44433
+ const filePath = join24(resolvedOutputDir, generateImageFilename(mimeType));
44434
+ writeFileSync2(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
44003
44435
  chmodSync4(filePath, 384);
44004
44436
  return filePath;
44005
44437
  } catch (error) {
@@ -44442,6 +44874,49 @@ data: ${JSON.stringify(syntheticUsage)}
44442
44874
  });
44443
44875
  }
44444
44876
 
44877
+ // src/plugin/core/streaming/displayed-thinking.ts
44878
+ var MAX_DISPLAYED_THINKING_SESSIONS = 256;
44879
+ var MAX_DISPLAYED_THINKING_PER_SESSION = 512;
44880
+ var BoundedHashSet = class extends Set {
44881
+ constructor(limit) {
44882
+ super();
44883
+ this.limit = limit;
44884
+ }
44885
+ limit;
44886
+ add(value) {
44887
+ if (!this.has(value) && this.size >= this.limit) {
44888
+ const oldest = this.values().next().value;
44889
+ if (oldest !== void 0) this.delete(oldest);
44890
+ }
44891
+ return super.add(value);
44892
+ }
44893
+ };
44894
+ function createDisplayedThinkingRegistry(limits = {}) {
44895
+ const maxSessions = limits.sessions ?? MAX_DISPLAYED_THINKING_SESSIONS;
44896
+ const perSession = limits.perSession ?? MAX_DISPLAYED_THINKING_PER_SESSION;
44897
+ const sessions = /* @__PURE__ */ new Map();
44898
+ return {
44899
+ forSession(sessionKey) {
44900
+ if (!sessionKey) return void 0;
44901
+ let hashes = sessions.get(sessionKey);
44902
+ if (hashes) {
44903
+ sessions.delete(sessionKey);
44904
+ } else {
44905
+ hashes = new BoundedHashSet(perSession);
44906
+ if (sessions.size >= maxSessions) {
44907
+ const oldest = sessions.keys().next().value;
44908
+ if (oldest !== void 0) sessions.delete(oldest);
44909
+ }
44910
+ }
44911
+ sessions.set(sessionKey, hashes);
44912
+ return hashes;
44913
+ },
44914
+ get sessionCount() {
44915
+ return sessions.size;
44916
+ }
44917
+ };
44918
+ }
44919
+
44445
44920
  // src/plugin/request.ts
44446
44921
  init_debug();
44447
44922
 
@@ -44449,12 +44924,12 @@ init_debug();
44449
44924
  init_dist();
44450
44925
  init_logging_utils();
44451
44926
  import { createHash as createHash15 } from "node:crypto";
44452
- import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
44453
- import { tmpdir as tmpdir4 } from "node:os";
44454
- import { join as join26 } from "node:path";
44927
+ import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
44928
+ import { tmpdir as tmpdir3 } from "node:os";
44929
+ import { join as join25 } from "node:path";
44455
44930
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
44456
44931
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
44457
- var DEFAULT_DUMP_DIR = join26(tmpdir4(), "opencode-antigravity-gemini-dumps");
44932
+ var DEFAULT_DUMP_DIR = join25(tmpdir3(), "opencode-antigravity-gemini-dumps");
44458
44933
  var DUMP_DIR_MODE = 448;
44459
44934
  var DUMP_FILE_MODE = 384;
44460
44935
  var nextDumpId = 0;
@@ -44586,7 +45061,7 @@ function bodyStructureSummary(bodyText) {
44586
45061
  };
44587
45062
  }
44588
45063
  function writeJson(path5, value) {
44589
- writeFileSync4(path5, `${JSON.stringify(value, null, 2)}
45064
+ writeFileSync3(path5, `${JSON.stringify(value, null, 2)}
44590
45065
  `, {
44591
45066
  encoding: "utf8",
44592
45067
  mode: DUMP_FILE_MODE
@@ -44608,8 +45083,8 @@ function writeGeminiDump(input2) {
44608
45083
  nextDumpId += 1;
44609
45084
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
44610
45085
  const dumpDir = getGeminiDumpDirectory();
44611
- const prefix = join26(dumpDir, id);
44612
- mkdirSync6(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
45086
+ const prefix = join25(dumpDir, id);
45087
+ mkdirSync5(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
44613
45088
  const context = {
44614
45089
  id,
44615
45090
  files: {
@@ -44637,11 +45112,11 @@ function writeGeminiDump(input2) {
44637
45112
  }
44638
45113
  }
44639
45114
  };
44640
- writeFileSync4(context.files.request, redactJsonBodyString(input2.body), {
45115
+ writeFileSync3(context.files.request, redactJsonBodyString(input2.body), {
44641
45116
  encoding: "utf8",
44642
45117
  mode: DUMP_FILE_MODE
44643
45118
  });
44644
- writeFileSync4(context.files.response, "", {
45119
+ writeFileSync3(context.files.response, "", {
44645
45120
  encoding: "utf8",
44646
45121
  mode: DUMP_FILE_MODE
44647
45122
  });
@@ -44693,27 +45168,27 @@ init_logger4();
44693
45168
  // src/plugin/recovery/storage.ts
44694
45169
  import {
44695
45170
  existsSync as existsSync11,
44696
- mkdirSync as mkdirSync7,
45171
+ mkdirSync as mkdirSync6,
44697
45172
  readdirSync as readdirSync2,
44698
45173
  readFileSync as readFileSync10,
44699
- unlinkSync as unlinkSync4,
44700
- writeFileSync as writeFileSync5
45174
+ unlinkSync as unlinkSync3,
45175
+ writeFileSync as writeFileSync4
44701
45176
  } from "node:fs";
44702
- import { join as join28 } from "node:path";
45177
+ import { join as join27 } from "node:path";
44703
45178
 
44704
45179
  // src/plugin/recovery/constants.ts
44705
45180
  import { homedir as homedir9 } from "node:os";
44706
- import { join as join27 } from "node:path";
45181
+ import { join as join26 } from "node:path";
44707
45182
  function getXdgData() {
44708
45183
  const platform = process.platform;
44709
45184
  if (platform === "win32") {
44710
- return process.env.APPDATA || join27(homedir9(), "AppData", "Roaming");
45185
+ return process.env.APPDATA || join26(homedir9(), "AppData", "Roaming");
44711
45186
  }
44712
- return process.env.XDG_DATA_HOME || join27(homedir9(), ".local", "share");
45187
+ return process.env.XDG_DATA_HOME || join26(homedir9(), ".local", "share");
44713
45188
  }
44714
- var OPENCODE_STORAGE = join27(getXdgData(), "opencode", "storage");
44715
- var MESSAGE_STORAGE = join27(OPENCODE_STORAGE, "message");
44716
- var PART_STORAGE = join27(OPENCODE_STORAGE, "part");
45189
+ var OPENCODE_STORAGE = join26(getXdgData(), "opencode", "storage");
45190
+ var MESSAGE_STORAGE = join26(OPENCODE_STORAGE, "message");
45191
+ var PART_STORAGE = join26(OPENCODE_STORAGE, "part");
44717
45192
  var THINKING_TYPES = /* @__PURE__ */ new Set([
44718
45193
  "thinking",
44719
45194
  "redacted_thinking",
@@ -44723,13 +45198,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
44723
45198
  // src/plugin/recovery/storage.ts
44724
45199
  function getMessageDir(sessionID) {
44725
45200
  if (!existsSync11(MESSAGE_STORAGE)) return "";
44726
- const directPath = join28(MESSAGE_STORAGE, sessionID);
45201
+ const directPath = join27(MESSAGE_STORAGE, sessionID);
44727
45202
  if (existsSync11(directPath)) {
44728
45203
  return directPath;
44729
45204
  }
44730
45205
  try {
44731
45206
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
44732
- const sessionPath = join28(MESSAGE_STORAGE, dir, sessionID);
45207
+ const sessionPath = join27(MESSAGE_STORAGE, dir, sessionID);
44733
45208
  if (existsSync11(sessionPath)) {
44734
45209
  return sessionPath;
44735
45210
  }
@@ -44746,7 +45221,7 @@ function readMessages(sessionID) {
44746
45221
  for (const file of readdirSync2(messageDir)) {
44747
45222
  if (!file.endsWith(".json")) continue;
44748
45223
  try {
44749
- const content = readFileSync10(join28(messageDir, file), "utf-8");
45224
+ const content = readFileSync10(join27(messageDir, file), "utf-8");
44750
45225
  messages.push(JSON.parse(content));
44751
45226
  } catch {
44752
45227
  }
@@ -44762,14 +45237,14 @@ function readMessages(sessionID) {
44762
45237
  });
44763
45238
  }
44764
45239
  function readParts(messageID) {
44765
- const partDir = join28(PART_STORAGE, messageID);
45240
+ const partDir = join27(PART_STORAGE, messageID);
44766
45241
  if (!existsSync11(partDir)) return [];
44767
45242
  const parts = [];
44768
45243
  try {
44769
45244
  for (const file of readdirSync2(partDir)) {
44770
45245
  if (!file.endsWith(".json")) continue;
44771
45246
  try {
44772
- const content = readFileSync10(join28(partDir, file), "utf-8");
45247
+ const content = readFileSync10(join27(partDir, file), "utf-8");
44773
45248
  parts.push(JSON.parse(content));
44774
45249
  } catch {
44775
45250
  }
@@ -44811,10 +45286,10 @@ function findMessagesWithOrphanThinking(sessionID) {
44811
45286
  return result;
44812
45287
  }
44813
45288
  function prependThinkingPart(sessionID, messageID) {
44814
- const partDir = join28(PART_STORAGE, messageID);
45289
+ const partDir = join27(PART_STORAGE, messageID);
44815
45290
  try {
44816
45291
  if (!existsSync11(partDir)) {
44817
- mkdirSync7(partDir, { recursive: true });
45292
+ mkdirSync6(partDir, { recursive: true });
44818
45293
  }
44819
45294
  const partId = "prt_0000000000_thinking";
44820
45295
  const part = {
@@ -44825,8 +45300,8 @@ function prependThinkingPart(sessionID, messageID) {
44825
45300
  thinking: "",
44826
45301
  synthetic: true
44827
45302
  };
44828
- writeFileSync5(
44829
- join28(partDir, `${partId}.json`),
45303
+ writeFileSync4(
45304
+ join27(partDir, `${partId}.json`),
44830
45305
  JSON.stringify(part, null, 2)
44831
45306
  );
44832
45307
  return true;
@@ -44835,18 +45310,18 @@ function prependThinkingPart(sessionID, messageID) {
44835
45310
  }
44836
45311
  }
44837
45312
  function stripThinkingParts(messageID) {
44838
- const partDir = join28(PART_STORAGE, messageID);
45313
+ const partDir = join27(PART_STORAGE, messageID);
44839
45314
  if (!existsSync11(partDir)) return false;
44840
45315
  let anyRemoved = false;
44841
45316
  try {
44842
45317
  for (const file of readdirSync2(partDir)) {
44843
45318
  if (!file.endsWith(".json")) continue;
44844
45319
  try {
44845
- const filePath = join28(partDir, file);
45320
+ const filePath = join27(partDir, file);
44846
45321
  const content = readFileSync10(filePath, "utf-8");
44847
45322
  const part = JSON.parse(content);
44848
45323
  if (THINKING_TYPES.has(part.type)) {
44849
- unlinkSync4(filePath);
45324
+ unlinkSync3(filePath);
44850
45325
  anyRemoved = true;
44851
45326
  }
44852
45327
  } catch {
@@ -46139,6 +46614,9 @@ function fixToolResponseGrouping(contents) {
46139
46614
  const newContents = [];
46140
46615
  const pendingGroups = [];
46141
46616
  const collectedResponses = /* @__PURE__ */ new Map();
46617
+ const arrivalById = /* @__PURE__ */ new Map();
46618
+ let arrivals = 0;
46619
+ const idsByName = /* @__PURE__ */ new Map();
46142
46620
  for (const content of contents) {
46143
46621
  const role = content.role;
46144
46622
  const parts = content.parts || [];
@@ -46148,6 +46626,15 @@ function fixToolResponseGrouping(contents) {
46148
46626
  const respId = resp.functionResponse?.id || "";
46149
46627
  if (respId && !collectedResponses.has(respId)) {
46150
46628
  collectedResponses.set(respId, resp);
46629
+ const arrival = arrivals++;
46630
+ arrivalById.set(respId, arrival);
46631
+ const name = resp.functionResponse?.name || "";
46632
+ let queue2 = idsByName.get(name);
46633
+ if (!queue2) {
46634
+ queue2 = { entries: [], head: 0 };
46635
+ idsByName.set(name, queue2);
46636
+ }
46637
+ queue2.entries.push({ id: respId, arrival });
46151
46638
  }
46152
46639
  }
46153
46640
  for (let i = pendingGroups.length - 1; i >= 0; i--) {
@@ -46185,7 +46672,20 @@ function fixToolResponseGrouping(contents) {
46185
46672
  newContents.push(content);
46186
46673
  }
46187
46674
  }
46675
+ const firstCollectedNamed = (name) => {
46676
+ const queue2 = idsByName.get(name);
46677
+ if (!queue2) return null;
46678
+ while (queue2.head < queue2.entries.length) {
46679
+ const entry = queue2.entries[queue2.head];
46680
+ if (collectedResponses.has(entry.id) && arrivalById.get(entry.id) === entry.arrival) {
46681
+ return entry.id;
46682
+ }
46683
+ queue2.head++;
46684
+ }
46685
+ return null;
46686
+ };
46188
46687
  pendingGroups.sort((a, b) => b.insertAfterIdx - a.insertAfterIdx);
46688
+ const insertedAfter = /* @__PURE__ */ new Map();
46189
46689
  for (const group of pendingGroups) {
46190
46690
  const groupResponses = [];
46191
46691
  for (let i = 0; i < group.ids.length; i++) {
@@ -46196,20 +46696,9 @@ function fixToolResponseGrouping(contents) {
46196
46696
  collectedResponses.delete(expectedId);
46197
46697
  } else if (collectedResponses.size > 0) {
46198
46698
  let matchedId = null;
46199
- for (const [orphanId, orphanResp] of collectedResponses) {
46200
- const orphanName = orphanResp.functionResponse?.name || "";
46201
- if (orphanName === expectedName) {
46202
- matchedId = orphanId;
46203
- break;
46204
- }
46205
- }
46699
+ matchedId = firstCollectedNamed(expectedName);
46206
46700
  if (!matchedId) {
46207
- for (const [orphanId, orphanResp] of collectedResponses) {
46208
- if (orphanResp.functionResponse?.name === "unknown_function") {
46209
- matchedId = orphanId;
46210
- break;
46211
- }
46212
- }
46701
+ matchedId = firstCollectedNamed("unknown_function");
46213
46702
  }
46214
46703
  if (!matchedId) {
46215
46704
  matchedId = collectedResponses.keys().next().value ?? null;
@@ -46249,13 +46738,20 @@ function fixToolResponseGrouping(contents) {
46249
46738
  }
46250
46739
  }
46251
46740
  if (groupResponses.length > 0) {
46252
- newContents.splice(group.insertAfterIdx + 1, 0, {
46741
+ insertedAfter.set(group.insertAfterIdx, {
46253
46742
  parts: groupResponses,
46254
46743
  role: "user"
46255
46744
  });
46256
46745
  }
46257
46746
  }
46258
- return newContents;
46747
+ if (insertedAfter.size === 0) return newContents;
46748
+ const withRecovered = [];
46749
+ for (let i = 0; i < newContents.length; i++) {
46750
+ withRecovered.push(newContents[i]);
46751
+ const recovered = insertedAfter.get(i);
46752
+ if (recovered) withRecovered.push(recovered);
46753
+ }
46754
+ return withRecovered;
46259
46755
  }
46260
46756
  function findOrphanedToolUseIds(messages) {
46261
46757
  const toolUseIds = /* @__PURE__ */ new Set();
@@ -47170,7 +47666,7 @@ init_dist();
47170
47666
  var log11 = createLogger4("request");
47171
47667
  var PLUGIN_SESSION_ID = `-${crypto2.randomUUID()}`;
47172
47668
  var DEFAULT_AGY_REQUEST_SESSION = createAgyRequestSessionContext();
47173
- var sessionDisplayedThinkingHashes = /* @__PURE__ */ new Set();
47669
+ var openCode1DisplayedThinking = createDisplayedThinkingRegistry();
47174
47670
  var MIN_SIGNATURE_LENGTH = 50;
47175
47671
  var AGY_CLAUDE_THINKING_BUDGET = 1024;
47176
47672
  var ANTIGRAVITY_ENVELOPE_FIELD_ORDER = [
@@ -47316,6 +47812,9 @@ function ensureThinkingFields(obj) {
47316
47812
  ensureThinkingFields(val);
47317
47813
  }
47318
47814
  }
47815
+ function systemInstructionOf(request2) {
47816
+ return request2 && typeof request2 === "object" ? request2.systemInstruction : void 0;
47817
+ }
47319
47818
  function safeStringify(obj) {
47320
47819
  ensureThinkingFields(obj);
47321
47820
  return JSON.stringify(obj, thinkingSafeReplacer);
@@ -47568,9 +48067,6 @@ function stripUnsupportedAntigravityFields(payload) {
47568
48067
  }
47569
48068
  }
47570
48069
  }
47571
- function isGeminiFunctionResponseTurn(content, wireModel) {
47572
- return wireModel.startsWith("gemini-") && content?.role === "model" && Array.isArray(content.parts) && content.parts.length > 0 && content.parts.every((part) => part?.functionResponse);
47573
- }
47574
48070
  function configureAntigravityToolCalling(payload) {
47575
48071
  delete payload.toolConfig;
47576
48072
  if (Array.isArray(payload.tools)) {
@@ -47992,7 +48488,7 @@ var openCode1WireLocation = {
47992
48488
  },
47993
48489
  logger: log11,
47994
48490
  sessionFingerprint: () => getSessionFingerprint(),
47995
- displayedThinkingHashes: sessionDisplayedThinkingHashes,
48491
+ displayedThinking: openCode1DisplayedThinking,
47996
48492
  cacheStats: { last: null }
47997
48493
  };
47998
48494
  function getLastCacheStats() {
@@ -48017,6 +48513,7 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48017
48513
  let sessionId;
48018
48514
  let needsSignedThinkingWarmup = false;
48019
48515
  let thinkingRecoveryMessage;
48516
+ let wireSystemInstruction;
48020
48517
  if (!isGenerativeLanguageRequest(input2)) {
48021
48518
  return {
48022
48519
  request: input2,
@@ -48145,13 +48642,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48145
48642
  normalizeNativeFunctionResponseRoles(req, effectiveModel);
48146
48643
  }
48147
48644
  for (const req of requestObjects) {
48148
- if (Array.isArray(req.contents)) {
48149
- const contents = req.contents;
48150
- const lastContent = contents[contents.length - 1];
48151
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
48152
- contents.push({ role: "user", parts: [{ text: "[Continue]" }] });
48153
- }
48154
- }
48645
+ if (Array.isArray(req.contents))
48646
+ appendAgyContinuation(req.contents, effectiveModel);
48155
48647
  if (Array.isArray(req.messages)) {
48156
48648
  const messages = req.messages;
48157
48649
  const lastMessage = messages[messages.length - 1];
@@ -48201,6 +48693,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48201
48693
  }
48202
48694
  }
48203
48695
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
48696
+ wireSystemInstruction = {
48697
+ body,
48698
+ instruction: systemInstructionOf(wrappedBody.request)
48699
+ };
48204
48700
  } else {
48205
48701
  const requestPayload = { ...parsedBody };
48206
48702
  if (isImageGenerationModel(effectiveModel) && isOpenCodeTitleGenerationRequest(requestPayload)) {
@@ -48587,15 +49083,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48587
49083
  wire.signatures.signatureStore.delete(signatureSessionKey);
48588
49084
  }
48589
49085
  }
48590
- if (Array.isArray(requestPayload.contents)) {
48591
- const lastContent = requestPayload.contents[requestPayload.contents.length - 1];
48592
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
48593
- requestPayload.contents.push({
48594
- role: "user",
48595
- parts: [{ text: "[Continue]" }]
48596
- });
48597
- }
48598
- }
49086
+ if (Array.isArray(requestPayload.contents))
49087
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
48599
49088
  if (Array.isArray(requestPayload.messages)) {
48600
49089
  const lastMessage = requestPayload.messages[requestPayload.messages.length - 1];
48601
49090
  if (lastMessage?.role === "model" || lastMessage?.role === "assistant") {
@@ -48623,15 +49112,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48623
49112
  stripUnsupportedAntigravityFields(requestPayload);
48624
49113
  configureAntigravityToolCalling(requestPayload);
48625
49114
  normalizeNativeFunctionResponseRoles(requestPayload, effectiveModel);
48626
- if (Array.isArray(requestPayload.contents)) {
48627
- const lastContent = requestPayload.contents.at(-1);
48628
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel)) {
48629
- requestPayload.contents.push({
48630
- role: "user",
48631
- parts: [{ text: "[Continue]" }]
48632
- });
48633
- }
48634
- }
49115
+ if (Array.isArray(requestPayload.contents))
49116
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
48635
49117
  }
48636
49118
  const effectiveProjectId = projectId?.trim() || ANTIGRAVITY_DEFAULT_PROJECT_ID;
48637
49119
  resolvedProjectId = effectiveProjectId;
@@ -48656,6 +49138,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48656
49138
  requestType: "agent"
48657
49139
  };
48658
49140
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
49141
+ wireSystemInstruction = {
49142
+ body,
49143
+ instruction: requestPayload.systemInstruction
49144
+ };
48659
49145
  }
48660
49146
  } catch {
48661
49147
  throw new Error("Failed to build Antigravity request body");
@@ -48699,7 +49185,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48699
49185
  toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
48700
49186
  needsSignedThinkingWarmup,
48701
49187
  headerStyle: "antigravity",
48702
- thinkingRecoveryMessage
49188
+ thinkingRecoveryMessage,
49189
+ ...wireSystemInstruction ? { wireSystemInstruction } : {}
48703
49190
  };
48704
49191
  }
48705
49192
  function prepareAntigravityRequest(...args) {
@@ -48817,7 +49304,7 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
48817
49304
  signatureSessionKey: sessionId,
48818
49305
  debugText,
48819
49306
  cacheSignatures,
48820
- displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinkingHashes : void 0
49307
+ displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinking.forSession(sessionId) : void 0
48821
49308
  // injectSyntheticThinking removed - keep_thinking now unified with debug via debugText
48822
49309
  }
48823
49310
  );
@@ -49316,10 +49803,10 @@ async function retainResponseLifetime(response, cancellation) {
49316
49803
  cancellation.release();
49317
49804
  throw error;
49318
49805
  }
49319
- let resolve34 = () => {
49806
+ let resolve35 = () => {
49320
49807
  };
49321
49808
  const settled = new Promise((done) => {
49322
- resolve34 = done;
49809
+ resolve35 = done;
49323
49810
  });
49324
49811
  let stopping = false;
49325
49812
  let finished = false;
@@ -49329,7 +49816,7 @@ async function retainResponseLifetime(response, cancellation) {
49329
49816
  finished = true;
49330
49817
  cancellation.signal.removeEventListener("abort", abort);
49331
49818
  cancellation.release();
49332
- resolve34();
49819
+ resolve35();
49333
49820
  };
49334
49821
  const abort = () => {
49335
49822
  if (finished || stopping) return;
@@ -49614,8 +50101,6 @@ function candidateView(candidates) {
49614
50101
  accounts.push({ account_id: accountId, credential_id: credentialId });
49615
50102
  }
49616
50103
  }
49617
- if (accounts.length === 0)
49618
- return void 0;
49619
50104
  const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
49620
50105
  `, "utf8")).sort(Buffer.compare);
49621
50106
  const hash2 = createHash16("sha256");
@@ -49692,8 +50177,8 @@ async function askRouting(input2) {
49692
50177
  return void 0;
49693
50178
  const requested = input2.deadlineMs ?? 1500;
49694
50179
  const deadlineMs = Number.isNaN(requested) ? 1500 : Math.min(2e3, Math.max(1, requested));
49695
- const expired = new Promise((resolve34) => {
49696
- timer = setTimeout(() => resolve34(void 0), deadlineMs);
50180
+ const expired = new Promise((resolve35) => {
50181
+ timer = setTimeout(() => resolve35(void 0), deadlineMs);
49697
50182
  timer.unref();
49698
50183
  });
49699
50184
  const cap = input2.holdWaitMaxS;
@@ -49707,7 +50192,7 @@ async function askRouting(input2) {
49707
50192
  request2.warm_credential = warmCredentialId;
49708
50193
  }
49709
50194
  const candidates = candidateView(input2.candidates);
49710
- if (candidates)
50195
+ if (candidates.accounts.length > 0 || request2.mode === "continue")
49711
50196
  request2.candidates = candidates;
49712
50197
  const pending = accountFor.call(handle, request2, { deadlineMs });
49713
50198
  if (!isObject2(pending) || typeof pending.then !== "function")
@@ -50083,7 +50568,7 @@ function createRetryState() {
50083
50568
  var MAX_WARMUP_SESSIONS = 1e3;
50084
50569
  var MAX_WARMUP_RETRIES = 2;
50085
50570
  function createWarmupState() {
50086
- const warmupAttemptedSessionIds = /* @__PURE__ */ new Set();
50571
+ const warmupAttemptCounts = /* @__PURE__ */ new Map();
50087
50572
  const warmupSucceededSessionIds = /* @__PURE__ */ new Set();
50088
50573
  let disposed = false;
50089
50574
  function trackAttempt(sessionId) {
@@ -50091,22 +50576,22 @@ function createWarmupState() {
50091
50576
  if (warmupSucceededSessionIds.has(sessionId)) {
50092
50577
  return false;
50093
50578
  }
50094
- if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
50095
- const first = warmupAttemptedSessionIds.values().next().value;
50096
- if (first) {
50097
- warmupAttemptedSessionIds.delete(first);
50098
- warmupSucceededSessionIds.delete(first);
50099
- }
50100
- }
50101
50579
  const attempts2 = getAttemptCount(sessionId);
50102
50580
  if (attempts2 >= MAX_WARMUP_RETRIES) {
50103
50581
  return false;
50104
50582
  }
50105
- warmupAttemptedSessionIds.add(sessionId);
50583
+ if (attempts2 === 0 && warmupAttemptCounts.size >= MAX_WARMUP_SESSIONS) {
50584
+ const first = warmupAttemptCounts.keys().next().value;
50585
+ if (first !== void 0) {
50586
+ warmupAttemptCounts.delete(first);
50587
+ warmupSucceededSessionIds.delete(first);
50588
+ }
50589
+ }
50590
+ warmupAttemptCounts.set(sessionId, attempts2 + 1);
50106
50591
  return true;
50107
50592
  }
50108
50593
  function getAttemptCount(sessionId) {
50109
- return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
50594
+ return warmupAttemptCounts.get(sessionId) ?? 0;
50110
50595
  }
50111
50596
  function markSuccess(sessionId) {
50112
50597
  if (disposed) return;
@@ -50116,12 +50601,14 @@ function createWarmupState() {
50116
50601
  if (first) warmupSucceededSessionIds.delete(first);
50117
50602
  }
50118
50603
  }
50119
- function clearWarmupAttempt(sessionId) {
50604
+ function refundAttempt(sessionId) {
50120
50605
  if (disposed) return;
50121
- warmupAttemptedSessionIds.delete(sessionId);
50606
+ const attempts2 = getAttemptCount(sessionId);
50607
+ if (attempts2 <= 1) warmupAttemptCounts.delete(sessionId);
50608
+ else warmupAttemptCounts.set(sessionId, attempts2 - 1);
50122
50609
  }
50123
50610
  function clear() {
50124
- warmupAttemptedSessionIds.clear();
50611
+ warmupAttemptCounts.clear();
50125
50612
  warmupSucceededSessionIds.clear();
50126
50613
  }
50127
50614
  function dispose() {
@@ -50136,7 +50623,7 @@ function createWarmupState() {
50136
50623
  trackAttempt,
50137
50624
  getAttemptCount,
50138
50625
  markSuccess,
50139
- clearWarmupAttempt,
50626
+ refundAttempt,
50140
50627
  clear,
50141
50628
  dispose
50142
50629
  };
@@ -50202,8 +50689,8 @@ function createAfterHandoff(work, signals, onFailure) {
50202
50689
  let running = false;
50203
50690
  let resolveCompletion = () => {
50204
50691
  };
50205
- const completion = new Promise((resolve34) => {
50206
- resolveCompletion = resolve34;
50692
+ const completion = new Promise((resolve35) => {
50693
+ resolveCompletion = resolve35;
50207
50694
  });
50208
50695
  const finish = () => {
50209
50696
  if (finished) return;
@@ -50250,14 +50737,14 @@ function createAfterHandoff(work, signals, onFailure) {
50250
50737
  };
50251
50738
  }
50252
50739
  function publishResponse(dispatch) {
50253
- return new Promise((resolve34, reject) => {
50740
+ return new Promise((resolve35, reject) => {
50254
50741
  let acknowledge;
50255
50742
  void Promise.resolve().then(
50256
50743
  () => dispatch((callback) => {
50257
50744
  acknowledge = callback;
50258
50745
  })
50259
50746
  ).then((response) => {
50260
- resolve34(response);
50747
+ resolve35(response);
50261
50748
  acknowledge?.();
50262
50749
  }, reject);
50263
50750
  });
@@ -50637,6 +51124,7 @@ function isTitleVaultRequest(kind, headers) {
50637
51124
  var FIRST_RETRY_DELAY_MS = 1e3;
50638
51125
  var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
50639
51126
  var ROUTING_ASK_DEADLINE_MS = 2e3;
51127
+ var FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS = 5;
50640
51128
  var REFUSAL_BODY_TIMEOUT_MS = 2e3;
50641
51129
  var REFUSAL_BODY_MAX_BYTES = 64 * 1024;
50642
51130
  async function readRefusalBody(response, deadline) {
@@ -50665,8 +51153,8 @@ async function readRefusalBody(response, deadline) {
50665
51153
  return false;
50666
51154
  }
50667
51155
  })(),
50668
- new Promise((resolve34) => {
50669
- timer = setTimeout(() => resolve34(false), REFUSAL_BODY_TIMEOUT_MS);
51156
+ new Promise((resolve35) => {
51157
+ timer = setTimeout(() => resolve35(false), REFUSAL_BODY_TIMEOUT_MS);
50670
51158
  })
50671
51159
  ])
50672
51160
  );
@@ -50782,7 +51270,7 @@ function formatWaitTime(ms) {
50782
51270
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
50783
51271
  }
50784
51272
  function sleep4(ms, signal) {
50785
- return new Promise((resolve34, reject) => {
51273
+ return new Promise((resolve35, reject) => {
50786
51274
  if (signal?.aborted) {
50787
51275
  reject(
50788
51276
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -50792,7 +51280,7 @@ function sleep4(ms, signal) {
50792
51280
  const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
50793
51281
  const timeout = setTimeout(() => {
50794
51282
  cleanup2();
50795
- resolve34();
51283
+ resolve35();
50796
51284
  }, timerMs);
50797
51285
  const onAbort = () => {
50798
51286
  cleanup2();
@@ -50865,15 +51353,16 @@ function createLocalQuotaRefresh(accountManager, quotaManager, log19) {
50865
51353
  ...signal ? { signal } : {}
50866
51354
  });
50867
51355
  if (signal?.aborted) return;
50868
- if (result.status === "ok" && result.quota?.groups) {
51356
+ if (result.status === "ok" && result.quota?.groups && result.checkedAt !== void 0) {
50869
51357
  const currentIndex = accountManager.getAccounts().indexOf(account);
50870
51358
  if (currentIndex === -1) return;
50871
- accountManager.updateQuotaCache(
51359
+ if (accountManager.updateQuotaCache(
50872
51360
  currentIndex,
50873
51361
  result.quota.groups,
50874
- expectedRefreshToken
50875
- );
50876
- accountManager.requestSaveToDisk();
51362
+ expectedRefreshToken,
51363
+ result.checkedAt
51364
+ ))
51365
+ accountManager.requestSaveToDisk();
50877
51366
  }
50878
51367
  } catch (err) {
50879
51368
  log19.debug(
@@ -50999,6 +51488,18 @@ function createRequestExecutor(deps) {
50999
51488
  let retired = false;
51000
51489
  let drainPromise;
51001
51490
  let disposePromise;
51491
+ let warnedConditionReceipt = false;
51492
+ const runVaultCondition = (operation) => {
51493
+ void Promise.resolve().then(operation).catch((error) => {
51494
+ if (warnedConditionReceipt || !(error instanceof Error) || !("kind" in error) || error.kind !== "no-receipt")
51495
+ return;
51496
+ warnedConditionReceipt = true;
51497
+ try {
51498
+ log19.warn("vault-condition-no-receipt");
51499
+ } catch {
51500
+ }
51501
+ });
51502
+ };
51002
51503
  const reportVault401 = (admission, status) => {
51003
51504
  if (!admission || status !== 401) return;
51004
51505
  void Promise.resolve().then(() => admission.report401(status)).catch((error) => {
@@ -51110,6 +51611,7 @@ function createRequestExecutor(deps) {
51110
51611
  } : void 0;
51111
51612
  const isChildRequest = requestSessionIdentity.parentSessionId !== null;
51112
51613
  let physicalSendCount = 0;
51614
+ let emptyResponseAttempts = 0;
51113
51615
  if (accountManager.getAccountCount() === 0) {
51114
51616
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
51115
51617
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
@@ -51222,6 +51724,7 @@ function createRequestExecutor(deps) {
51222
51724
  }
51223
51725
  };
51224
51726
  let accountSwitchCount = 0;
51727
+ let capacityExhaustedSelections = 0;
51225
51728
  let unconfirmedRetries = 0;
51226
51729
  const maxAccountSwitches = config.max_account_switches ?? 2;
51227
51730
  let previousAccountIndex = -1;
@@ -51233,6 +51736,7 @@ function createRequestExecutor(deps) {
51233
51736
  let routingPlacementConsidered = false;
51234
51737
  let routedCandidate;
51235
51738
  let continueRouting;
51739
+ let continueOnlyLogin = false;
51236
51740
  const refusedRoutes = /* @__PURE__ */ new Map();
51237
51741
  let routingTitle = false;
51238
51742
  let routingWaitMs = 0;
@@ -51300,10 +51804,12 @@ function createRequestExecutor(deps) {
51300
51804
  const choice = routedCandidate;
51301
51805
  routedCandidate = void 0;
51302
51806
  const exhausted = continueRouting;
51807
+ const onlyLoginContinuation = continueOnlyLogin;
51303
51808
  continueRouting = void 0;
51809
+ continueOnlyLogin = false;
51304
51810
  if (exhausted) refusedRoutes.set(routingIdentityKey(exhausted), exhausted);
51305
51811
  const accountCount = accountManager.getAccountCount();
51306
- if (accountCount === 0) {
51812
+ if (accountCount === 0 && !onlyLoginContinuation) {
51307
51813
  if (choice) return failedRoutedPick();
51308
51814
  return createNoAccountResponse(
51309
51815
  "No Antigravity accounts available. Run `opencode auth login`.",
@@ -51491,7 +51997,7 @@ function createRequestExecutor(deps) {
51491
51997
  const canHold = !!holdCandidate && candidates.some(
51492
51998
  (candidate) => routingIdentityKey(candidate) === holdCandidate
51493
51999
  );
51494
- const answer = await deadline.wait(() => {
52000
+ const ask = () => deadline.wait(() => {
51495
52001
  const input3 = {
51496
52002
  sessionId: accountSessionIdentity.id,
51497
52003
  provider: "antigravity",
@@ -51513,9 +52019,21 @@ function createRequestExecutor(deps) {
51513
52019
  } : input3
51514
52020
  );
51515
52021
  });
52022
+ let answer = await ask();
52023
+ const firstRefusal = !exhausted && answer && "refused" in answer ? answer.refused : void 0;
52024
+ if (firstRefusal?.code === "account_selection_refused" && firstRefusal.retryAfterSecs !== void 0 && firstRefusal.retryAfterSecs <= FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS) {
52025
+ await routingSleep(
52026
+ firstRefusal.retryAfterSecs * 1e3,
52027
+ "account_free"
52028
+ );
52029
+ checkAborted();
52030
+ answer = await ask();
52031
+ }
51516
52032
  checkAborted();
51517
52033
  if (answer && "refused" in answer)
51518
52034
  return routingRefusalResponse(answer.refused);
52035
+ if (!answer && onlyLoginContinuation && candidates.length === 0)
52036
+ return failedRoutedPick();
51519
52037
  if (exhausted && answer?.hold) {
51520
52038
  if (!canHold || routingIdentityKey(answer.candidate) !== holdCandidate)
51521
52039
  return failedRoutedPick();
@@ -51988,12 +52506,14 @@ function createRequestExecutor(deps) {
51988
52506
  streaming: true,
51989
52507
  projectId
51990
52508
  });
52509
+ let warmupDispatched = false;
51991
52510
  try {
51992
52511
  pushDebug("thinking-warmup: start");
51993
52512
  const warmupSend = await credentialForAuxiliarySend(
51994
52513
  warmupInit,
51995
52514
  projectId
51996
52515
  );
52516
+ warmupDispatched = true;
51997
52517
  const warmupResponse = await sendPhysical(
51998
52518
  warmupUrl,
51999
52519
  warmupSend.init,
@@ -52018,7 +52538,7 @@ function createRequestExecutor(deps) {
52018
52538
  warmupState.markSuccess(prepared.sessionId);
52019
52539
  pushDebug("thinking-warmup: done");
52020
52540
  } catch (error) {
52021
- warmupState.clearWarmupAttempt(prepared.sessionId);
52541
+ if (!warmupDispatched) warmupState.refundAttempt(prepared.sessionId);
52022
52542
  if (error instanceof PreResponseTimeoutError) throw error;
52023
52543
  checkAborted();
52024
52544
  if (isLocalGrantError(error)) throw error;
@@ -52351,9 +52871,9 @@ function createRequestExecutor(deps) {
52351
52871
  const routed429 = response.status === 429 ? routedIdentity : void 0;
52352
52872
  if (response.status === 429 && rateLimitReason === "UNKNOWN") {
52353
52873
  await logResponseBody2(debugContext, response, 429);
52354
- const outgoing = JSON.parse(String(prepared.init.body));
52874
+ const carried = prepared.wireSystemInstruction;
52355
52875
  const recognised = systemInstructionHasHarnessIdentity(
52356
- outgoing.request?.systemInstruction
52876
+ carried && carried.body === prepared.init.body ? carried.instruction : JSON.parse(String(prepared.init.body)).request?.systemInstruction
52357
52877
  );
52358
52878
  if (recognised) {
52359
52879
  void response.body?.cancel().catch(() => {
@@ -52477,10 +52997,19 @@ function createRequestExecutor(deps) {
52477
52997
  i -= 1;
52478
52998
  continue;
52479
52999
  }
53000
+ retainHttpFailure(response);
53001
+ capacityExhaustedSelections++;
53002
+ if (capacityExhaustedSelections > 1) {
53003
+ pushDebug(
53004
+ `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted again after one account switch, giving up`
53005
+ );
53006
+ return terminalMainAttemptFailure(
53007
+ "Antigravity has no capacity for this model right now"
53008
+ );
53009
+ }
52480
53010
  pushDebug(
52481
53011
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
52482
53012
  );
52483
- retainHttpFailure(response);
52484
53013
  shouldSwitchAccount = true;
52485
53014
  break;
52486
53015
  }
@@ -52626,6 +53155,10 @@ function createRequestExecutor(deps) {
52626
53155
  i -= 1;
52627
53156
  continue;
52628
53157
  }
53158
+ if (routed429 && exhaustion) {
53159
+ const { accountId, credentialId } = routed429;
53160
+ continueRouting = { accountId, credentialId, ...exhaustion };
53161
+ }
52629
53162
  const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
52630
53163
  if (accountCount > 1) {
52631
53164
  const quotaMsg = reasonInfo.quotaResetTime ? ` (quota resets ${reasonInfo.quotaResetTime})` : ``;
@@ -52634,7 +53167,7 @@ function createRequestExecutor(deps) {
52634
53167
  "warning"
52635
53168
  );
52636
53169
  await sleep4(switchAccountDelayMs, abortSignal);
52637
- } else {
53170
+ } else if (!continueRouting || isHardEligible(account)) {
52638
53171
  const expBackoffMs = Math.min(
52639
53172
  FIRST_RETRY_DELAY_MS * 2 ** (backoff.attempt - 1),
52640
53173
  6e4
@@ -52651,10 +53184,6 @@ function createRequestExecutor(deps) {
52651
53184
  );
52652
53185
  }
52653
53186
  retainHttpFailure(response);
52654
- if (routed429 && exhaustion) {
52655
- const { accountId, credentialId } = routed429;
52656
- continueRouting = { accountId, credentialId, ...exhaustion };
52657
- }
52658
53187
  shouldSwitchAccount = true;
52659
53188
  break;
52660
53189
  }
@@ -52698,6 +53227,19 @@ function createRequestExecutor(deps) {
52698
53227
  () => response.clone().text().catch(() => "")
52699
53228
  );
52700
53229
  const extracted = errorBodyText === void 0 ? void 0 : classifyAccessError(errorBodyText);
53230
+ const served2 = sendAdmission;
53231
+ const reportCondition = (reason) => {
53232
+ if (credentials.domain !== "vault" || !served2?.reportCondition)
53233
+ return;
53234
+ const actionUrl = extracted?.structuredVerifyUrl;
53235
+ waitPolicy.vaultConditions.push(
53236
+ () => served2.reportCondition?.({
53237
+ reason,
53238
+ providerStatus: 403,
53239
+ ...actionUrl && { actionUrl }
53240
+ })
53241
+ );
53242
+ };
52701
53243
  if (routedIdentity && (extracted?.accountIneligible || extracted?.validationRequired)) {
52702
53244
  const { accountId, credentialId } = routedIdentity;
52703
53245
  continueRouting = {
@@ -52727,6 +53269,7 @@ function createRequestExecutor(deps) {
52727
53269
  trackers.health.recordFailure(account.index);
52728
53270
  retainHttpFailure(response);
52729
53271
  shouldSwitchAccount = true;
53272
+ reportCondition("provider_ineligible");
52730
53273
  break;
52731
53274
  }
52732
53275
  if (extracted?.validationRequired) {
@@ -52762,6 +53305,7 @@ function createRequestExecutor(deps) {
52762
53305
  trackers.health.recordFailure(account.index);
52763
53306
  retainHttpFailure(response);
52764
53307
  shouldSwitchAccount = true;
53308
+ reportCondition("provider_verification_required");
52765
53309
  break;
52766
53310
  }
52767
53311
  }
@@ -52841,8 +53385,7 @@ function createRequestExecutor(deps) {
52841
53385
  })
52842
53386
  );
52843
53387
  if (isEmptyResponseBody(bodyText)) {
52844
- const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
52845
- const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
53388
+ const currentAttempts = ++emptyResponseAttempts;
52846
53389
  pushDebug(
52847
53390
  `empty-response: attempt ${currentAttempts}/${maxAttempts}`
52848
53391
  );
@@ -52855,14 +53398,11 @@ function createRequestExecutor(deps) {
52855
53398
  await sleep4(retryDelayMs, abortSignal);
52856
53399
  continue;
52857
53400
  }
52858
- retryState.clearEmptyResponseAttempts();
52859
53401
  return createNativeGoogleErrorResponse({
52860
53402
  status: 502,
52861
53403
  reason: "empty_response"
52862
53404
  });
52863
53405
  }
52864
- const _emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
52865
- retryState.clearEmptyResponseAttempts();
52866
53406
  }
52867
53407
  const routingObservation = credentials.domain === "vault" && sendAdmission && sessionKey && response.ok && hasVaultRoutingAccessor() ? observeVaultUpstream(response, abortSignal) : void 0;
52868
53408
  const transformedResponse = await deadline.wait(
@@ -52899,7 +53439,7 @@ function createRequestExecutor(deps) {
52899
53439
  }
52900
53440
  if (apiRequestCount > 1) {
52901
53441
  pushDebug(
52902
- `[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`
53442
+ `[Quota] Main-request responses on this account selection: ${apiRequestCount}`
52903
53443
  );
52904
53444
  }
52905
53445
  const dailyCounts = accountManager.getDailyRequestCounts(
@@ -52939,6 +53479,9 @@ function createRequestExecutor(deps) {
52939
53479
  const refresh = credentials.refreshQuotaAfterSuccess;
52940
53480
  waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
52941
53481
  }
53482
+ const served = sendAdmission;
53483
+ if (credentials.domain === "vault" && response.ok && transformedResponse.ok && served?.clearCondition)
53484
+ waitPolicy.vaultConditions.push(() => served.clearCondition?.());
52942
53485
  return routingObservation && credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor() && response.ok ? observeVaultServed(
52943
53486
  {
52944
53487
  sessionId: sessionKey,
@@ -52956,6 +53499,7 @@ function createRequestExecutor(deps) {
52956
53499
  trackers.token.refund(account.index);
52957
53500
  tokenConsumed = false;
52958
53501
  }
53502
+ deadline.resume();
52959
53503
  if (credentials.domain === "local" && localGrant?.captured.source === "store" && isLocalGrantError(error)) {
52960
53504
  if (error instanceof LocalGrantSupersededError && !localRecaptureUsed) {
52961
53505
  localRecaptureUsed = true;
@@ -53041,6 +53585,10 @@ function createRequestExecutor(deps) {
53041
53585
  }
53042
53586
  if (shouldSwitchAccount) {
53043
53587
  if (switchedForUnconfirmed) continue;
53588
+ if (accountCount === 1 && continueRouting && (continueRouting.limitWindow === "signed_out" || !isHardEligible(account))) {
53589
+ continueOnlyLogin = true;
53590
+ continue;
53591
+ }
53044
53592
  accountSwitchCount++;
53045
53593
  if (accountSwitchCount > maxAccountSwitches) {
53046
53594
  pushDebug(
@@ -53109,7 +53657,11 @@ function createRequestExecutor(deps) {
53109
53657
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
53110
53658
  () => log19.debug("post-response-advisory-work-failed")
53111
53659
  );
53112
- const waitPolicy = {};
53660
+ const waitPolicy = { vaultConditions: [] };
53661
+ const publishVaultConditions = () => {
53662
+ for (const operation of waitPolicy.vaultConditions.splice(0))
53663
+ runVaultCondition(operation);
53664
+ };
53113
53665
  const selectedCredentials = /* @__PURE__ */ new Set();
53114
53666
  const selectedProjectIds = /* @__PURE__ */ new Set();
53115
53667
  const redactFailure = (error) => {
@@ -53182,7 +53734,21 @@ function createRequestExecutor(deps) {
53182
53734
  cancellation.release();
53183
53735
  throw redactFailure(error);
53184
53736
  }
53185
- ).catch((error) => {
53737
+ ).then((response) => {
53738
+ if (waitPolicy.vaultConditions.length > 0) {
53739
+ if (requestOptions?.onResponseHandoff) {
53740
+ try {
53741
+ requestOptions.onResponseHandoff(publishVaultConditions);
53742
+ return response;
53743
+ } catch {
53744
+ }
53745
+ }
53746
+ setImmediate(publishVaultConditions);
53747
+ }
53748
+ return response;
53749
+ }).catch((error) => {
53750
+ if (waitPolicy.vaultConditions.length > 0)
53751
+ setImmediate(publishVaultConditions);
53186
53752
  handoff.cancel();
53187
53753
  deadline.dispose();
53188
53754
  cancellation.release();
@@ -53269,13 +53835,13 @@ function extractRateLimitBodyInfo(body, status, headers) {
53269
53835
 
53270
53836
  // src/plugin/shared/runtime.ts
53271
53837
  init_dist();
53272
- import { join as join32 } from "node:path";
53838
+ import { join as join31 } from "node:path";
53273
53839
 
53274
53840
  // src/settings/runtime.ts
53275
53841
  init_dist();
53276
- import { readFile as readFile18, stat as stat14 } from "node:fs/promises";
53842
+ import { readFile as readFile19, stat as stat15 } from "node:fs/promises";
53277
53843
  import { homedir as homedir10 } from "node:os";
53278
- import { basename as basename11, join as join31 } from "node:path";
53844
+ import { basename as basename11, join as join30 } from "node:path";
53279
53845
  init_process_heartbeat();
53280
53846
  init_version_fence();
53281
53847
 
@@ -53322,10 +53888,10 @@ async function resolveSettingsLocation(options) {
53322
53888
  }
53323
53889
 
53324
53890
  // src/settings/move.ts
53325
- import { readFile as readFile16 } from "node:fs/promises";
53891
+ import { readFile as readFile17 } from "node:fs/promises";
53326
53892
  async function readIfPresent(path5) {
53327
53893
  try {
53328
- return await readFile16(path5, "utf8");
53894
+ return await readFile17(path5, "utf8");
53329
53895
  } catch {
53330
53896
  return void 0;
53331
53897
  }
@@ -53389,9 +53955,9 @@ async function runSettingsMove(input2) {
53389
53955
 
53390
53956
  // src/settings/protection.ts
53391
53957
  init_runtime_paths();
53392
- import { join as join29 } from "node:path";
53958
+ import { join as join28 } from "node:path";
53393
53959
  function defaultProtectionStatePath() {
53394
- return join29(pluginStateDir(), PROTECTION_STATE_FILE_NAME);
53960
+ return join28(pluginStateDir(), PROTECTION_STATE_FILE_NAME);
53395
53961
  }
53396
53962
  function createProtectionStore2(path5 = defaultProtectionStatePath()) {
53397
53963
  return createProtectionStore(path5);
@@ -53400,19 +53966,19 @@ function createProtectionStore2(path5 = defaultProtectionStatePath()) {
53400
53966
  // src/settings/report.ts
53401
53967
  init_dist();
53402
53968
  init_runtime_paths();
53403
- import { mkdir as mkdir16, readFile as readFile17, rm as rm6 } from "node:fs/promises";
53404
- import { basename as basename10, dirname as dirname27, join as join30 } from "node:path";
53969
+ import { mkdir as mkdir16, readFile as readFile18, rm as rm6 } from "node:fs/promises";
53970
+ import { basename as basename10, dirname as dirname26, join as join29 } from "node:path";
53405
53971
  var MOVE_REPORT_FILE_NAME = "settings-move-report.json";
53406
53972
  function defaultMoveReportPath() {
53407
- return join30(pluginStateDir(), MOVE_REPORT_FILE_NAME);
53973
+ return join29(pluginStateDir(), MOVE_REPORT_FILE_NAME);
53408
53974
  }
53409
53975
  async function writeMoveReport(path5, report) {
53410
- await mkdir16(dirname27(path5), { recursive: true, mode: 448 });
53976
+ await mkdir16(dirname26(path5), { recursive: true, mode: 448 });
53411
53977
  await writeJsonAtomic(path5, { version: 1, ...report });
53412
53978
  }
53413
53979
  async function readMoveReport(path5) {
53414
53980
  try {
53415
- const parsed = JSON.parse(await readFile17(path5, "utf8"));
53981
+ const parsed = JSON.parse(await readFile18(path5, "utf8"));
53416
53982
  if (parsed?.version !== 1 || !Array.isArray(parsed.unmapped))
53417
53983
  return void 0;
53418
53984
  return parsed;
@@ -53521,7 +54087,7 @@ function applyHotValues(target, next) {
53521
54087
  var DEFAULT_RETRY_DELAYS_MS = [5e3, 15e3, 6e4, 3e5];
53522
54088
  async function exists4(path5) {
53523
54089
  try {
53524
- await stat14(path5);
54090
+ await stat15(path5);
53525
54091
  return true;
53526
54092
  } catch {
53527
54093
  return false;
@@ -53822,12 +54388,12 @@ function createSettingsRuntime(options) {
53822
54388
  if (movedHere || moveReport) return [];
53823
54389
  let text2;
53824
54390
  try {
53825
- text2 = await readFile18(legacyUserFile, "utf8");
54391
+ text2 = await readFile19(legacyUserFile, "utf8");
53826
54392
  } catch {
53827
54393
  return [];
53828
54394
  }
53829
54395
  try {
53830
- const note = await readFile18(`${legacyUserFile}.MOVED_READPLEASE`, "utf8");
54396
+ const note = await readFile19(`${legacyUserFile}.MOVED_READPLEASE`, "utf8");
53831
54397
  if (note.includes(file)) return [];
53832
54398
  } catch {
53833
54399
  }
@@ -53847,7 +54413,7 @@ function createSettingsRuntime(options) {
53847
54413
  if (!handle) return [];
53848
54414
  const projectFiles = /* @__PURE__ */ new Set([
53849
54415
  getProjectConfigPath(entry.project),
53850
- join31(entry.project, ".cortexkit", "antigravity-auth.jsonc")
54416
+ join30(entry.project, ".cortexkit", "antigravity-auth.jsonc")
53851
54417
  ]);
53852
54418
  return handle.report().filter(
53853
54419
  (item) => item.file.kind === "user" && item.file.path === file || projectFiles.has(item.file.path)
@@ -54126,16 +54692,10 @@ var BackgroundQuotaRefresh = class {
54126
54692
  if (this.timer.unref) this.timer.unref();
54127
54693
  }
54128
54694
  async runTick() {
54129
- if (this.mayRun && !await this.mayRun()) {
54695
+ if (!await this.canRun()) {
54130
54696
  if (!this.disposed) this.scheduleNext(this.jitteredInterval());
54131
54697
  return;
54132
54698
  }
54133
- if (this.disposed) return;
54134
- const freshnessThresholdMs = Math.max(
54135
- this.intervalMs - MIN_INTERVAL_MS,
54136
- Math.floor(this.intervalMs / 2)
54137
- );
54138
- const ageMs = this.now() - this.snapshots.lastCheckedAt();
54139
54699
  const lockPath = this.snapshots.pollLockPath;
54140
54700
  let lock = null;
54141
54701
  try {
@@ -54153,9 +54713,7 @@ var BackgroundQuotaRefresh = class {
54153
54713
  return;
54154
54714
  }
54155
54715
  try {
54156
- if (this.disposed || this.mayRun && !await this.mayRun()) return;
54157
- if (ageMs >= freshnessThresholdMs) await this.refresh();
54158
- else await this.refreshTierSlot();
54716
+ if (await this.canRun()) await this.refresh();
54159
54717
  } finally {
54160
54718
  await lock.release().catch(() => {
54161
54719
  });
@@ -54164,22 +54722,36 @@ var BackgroundQuotaRefresh = class {
54164
54722
  this.scheduleNext(this.jitteredInterval());
54165
54723
  }
54166
54724
  }
54725
+ async canRun() {
54726
+ return !this.disposed && (!this.mayRun || await this.mayRun()) && !this.disposed;
54727
+ }
54167
54728
  async refresh() {
54168
54729
  const refreshedQuota = await this.refreshQuota();
54169
- if (!this.disposed && (!this.mayRun || await this.mayRun()))
54170
- await this.refreshTierSlot();
54171
- if (refreshedQuota) await this.pushSnapshot();
54730
+ if (await this.canRun()) await this.refreshTierSlot();
54731
+ if (refreshedQuota && await this.canRun()) await this.pushSnapshot();
54172
54732
  }
54173
54733
  async refreshQuota() {
54174
- if (this.disposed || this.mayRun && !await this.mayRun()) return false;
54175
54734
  const manager = this.getAccountManager();
54176
54735
  if (!manager) return false;
54177
- const accounts = manager.getAccountsForQuotaCheck();
54736
+ const observed = await (manager.readAccountsForQuotaPoll?.() ?? this.localObservations(manager));
54737
+ if (!await this.canRun()) return false;
54738
+ const now2 = this.now();
54739
+ const freshnessThresholdMs = Math.max(
54740
+ this.intervalMs - MIN_INTERVAL_MS,
54741
+ Math.floor(this.intervalMs / 2)
54742
+ );
54743
+ const accounts = observed.filter(
54744
+ ({ enabled, cachedQuotaUpdatedAt: at }) => enabled !== false && (at === void 0 || !Number.isFinite(at) || at <= 0 || at > now2 || now2 - at >= freshnessThresholdMs)
54745
+ );
54178
54746
  if (accounts.length === 0) return false;
54179
54747
  let results;
54180
54748
  try {
54749
+ const indexes = new Map(
54750
+ accounts.map((account, index) => [account, index])
54751
+ );
54181
54752
  results = await this.quotaManager.refreshAccounts(accounts, {
54182
- indexFor: (account) => accounts.indexOf(account),
54753
+ indexFor: (account) => indexes.get(account),
54754
+ publishSidebar: false,
54183
54755
  // Do not force: the quota manager's per-account dedup and backoff
54184
54756
  // apply — an account that already refreshed recently is skipped.
54185
54757
  force: false
@@ -54187,7 +54759,7 @@ var BackgroundQuotaRefresh = class {
54187
54759
  } catch {
54188
54760
  return false;
54189
54761
  }
54190
- if (this.disposed) return false;
54762
+ if (!await this.canRun()) return false;
54191
54763
  const liveAccounts = manager.getAccounts();
54192
54764
  const liveIndexByToken = /* @__PURE__ */ new Map();
54193
54765
  for (const entry of liveAccounts) {
@@ -54196,7 +54768,8 @@ var BackgroundQuotaRefresh = class {
54196
54768
  let anyUpdated = false;
54197
54769
  for (let i = 0; i < results.length; i++) {
54198
54770
  const result = results[i];
54199
- if (result?.status !== "ok" || !result.quota?.groups) continue;
54771
+ if (result?.status !== "ok" || !result.quota?.groups || result.checkedAt === void 0)
54772
+ continue;
54200
54773
  const candidateTokens = [
54201
54774
  result.updatedAccount?.refreshToken,
54202
54775
  accounts[i]?.refreshToken
@@ -54205,7 +54778,13 @@ var BackgroundQuotaRefresh = class {
54205
54778
  if (liveIndex === void 0) continue;
54206
54779
  const liveToken = liveAccounts[liveIndex]?.parts.refreshToken;
54207
54780
  if (!liveToken) continue;
54208
- manager.updateQuotaCache(liveIndex, result.quota.groups, liveToken);
54781
+ if (manager.updateQuotaCache(
54782
+ liveIndex,
54783
+ result.quota.groups,
54784
+ liveToken,
54785
+ result.checkedAt
54786
+ ) === false)
54787
+ continue;
54209
54788
  const uaTier = toCapturedTier(result.updatedAccount ?? {});
54210
54789
  if (uaTier !== void 0) {
54211
54790
  manager.applyUpdatedAccount(
@@ -54221,9 +54800,24 @@ var BackgroundQuotaRefresh = class {
54221
54800
  }
54222
54801
  anyUpdated = true;
54223
54802
  }
54224
- if (anyUpdated) manager.requestSaveToDisk();
54803
+ if (anyUpdated && await this.canRun()) {
54804
+ if (manager.saveToDisk) await manager.saveToDisk();
54805
+ else manager.requestSaveToDisk();
54806
+ }
54225
54807
  return true;
54226
54808
  }
54809
+ localObservations(manager) {
54810
+ const accounts = new Map(
54811
+ manager.getAccounts().map((row) => [row.parts.refreshToken, row])
54812
+ );
54813
+ return manager.getAccountsForQuotaCheck().map((target) => {
54814
+ const row = accounts.get(target.refreshToken);
54815
+ return {
54816
+ ...target,
54817
+ cachedQuotaUpdatedAt: row?.cachedQuota && row.cachedQuotaUpdatedAt
54818
+ };
54819
+ });
54820
+ }
54227
54821
  async refreshTierSlot() {
54228
54822
  if (this.disposed || !this.loadAccountTier) return;
54229
54823
  const manager = this.getAccountManager();
@@ -54248,7 +54842,7 @@ var BackgroundQuotaRefresh = class {
54248
54842
  if (!accountForTier) return;
54249
54843
  try {
54250
54844
  const tier = await this.loadAccountTier(accountForTier);
54251
- if (tier === null || this.disposed) return;
54845
+ if (tier === null || !await this.canRun()) return;
54252
54846
  const liveEntry = manager.getAccounts().find((entry) => entry.parts.refreshToken === refreshToken);
54253
54847
  if (!liveEntry) return;
54254
54848
  manager.applyUpdatedAccount(
@@ -54284,6 +54878,7 @@ var BackgroundQuotaRefresh = class {
54284
54878
  enabled: entry.enabled,
54285
54879
  coolingDownUntil: entry.coolingDownUntil,
54286
54880
  cachedQuota: entry.cachedQuota,
54881
+ cachedQuotaUpdatedAt: entry.cachedQuotaUpdatedAt,
54287
54882
  cachedQuotaAccountId: entry.cachedQuotaAccountId,
54288
54883
  // An account reorder changes which cached reading occupies an index.
54289
54884
  // Use a refresh-token-derived account ID to detect that mismatch
@@ -54688,7 +55283,7 @@ async function buildLocationRuntime(options, scope) {
54688
55283
  directory: options.directory,
54689
55284
  config: settings.config,
54690
55285
  keepThinking: settings.config.keep_thinking,
54691
- projectConfigPath: legacyConfig?.projectConfigPath ?? join32(options.directory, ".cortexkit", "antigravity-auth.jsonc"),
55286
+ projectConfigPath: legacyConfig?.projectConfigPath ?? join31(options.directory, ".cortexkit", "antigravity-auth.jsonc"),
54692
55287
  userConfigPath: legacyConfig?.userConfigPath ?? settings.operator.sourcePath()
54693
55288
  };
54694
55289
  settingsLease.runtime.startMove();
@@ -54718,6 +55313,7 @@ async function buildLocationRuntime(options, scope) {
54718
55313
  enabled: entry.enabled,
54719
55314
  coolingDownUntil: entry.coolingDownUntil,
54720
55315
  cachedQuota: entry.cachedQuota,
55316
+ cachedQuotaUpdatedAt: entry.cachedQuotaUpdatedAt,
54721
55317
  cachedQuotaAccountId: entry.cachedQuotaAccountId,
54722
55318
  ...identity4 ? { currentQuotaAccountId: identity4(entry.parts.refreshToken) } : {},
54723
55319
  tier: toCapturedTier(entry)
@@ -55292,7 +55888,7 @@ function createGaReauthorize(input2) {
55292
55888
  const continuations = /* @__PURE__ */ new Set();
55293
55889
  const shutdown = new AbortController();
55294
55890
  let disposed = false;
55295
- const waitForRedirect = (code2) => new Promise((resolve34, reject) => {
55891
+ const waitForRedirect = (code2) => new Promise((resolve35, reject) => {
55296
55892
  const detach = () => shutdown.signal.removeEventListener("abort", abort);
55297
55893
  const abort = () => {
55298
55894
  detach();
@@ -55303,7 +55899,7 @@ function createGaReauthorize(input2) {
55303
55899
  void code2.then(
55304
55900
  (value) => {
55305
55901
  detach();
55306
- resolve34(value);
55902
+ resolve35(value);
55307
55903
  },
55308
55904
  (error) => {
55309
55905
  detach();
@@ -55961,6 +56557,8 @@ async function createGaVaultLocationServices(input2) {
55961
56557
  durable: {
55962
56558
  source,
55963
56559
  readState: () => custody.readState(),
56560
+ ...custody.paths ? { stateFile: custody.paths.stateFile } : {},
56561
+ onReadFailure: () => vaultLogger.debug("vault-state-read-skipped"),
55964
56562
  onError: (error) => vaultLogger.debug("vault-state-write-dropped", {
55965
56563
  error: error instanceof Error ? error.name : "unknown"
55966
56564
  })
@@ -56990,6 +57588,7 @@ var MAX_NOTIFICATIONS_PER_STATE = ANTIGRAVITY_RPC_LIMITS.notificationsPerState;
56990
57588
  var ANTIGRAVITY_STATE_RESETS = [
56991
57589
  "initial",
56992
57590
  "generation-changed",
57591
+ "queue-changed",
56993
57592
  "cursor-ahead"
56994
57593
  ];
56995
57594
  var Issues = class {
@@ -57803,7 +58402,7 @@ function validateStateInput(value, issues) {
57803
58402
  path5,
57804
58403
  issues,
57805
58404
  ["version", "scope", "cursor"],
57806
- ["generation"]
58405
+ ["generation", "queueID"]
57807
58406
  )) {
57808
58407
  return;
57809
58408
  }
@@ -57814,6 +58413,8 @@ function validateStateInput(value, issues) {
57814
58413
  }
57815
58414
  if (present4(value, "scope")) checkScope(value.scope, ["scope"], issues);
57816
58415
  if (present4(value, "cursor")) checkCursor(value.cursor, ["cursor"], issues);
58416
+ if (present4(value, "queueID") && value.queueID !== null)
58417
+ checkGeneration(value.queueID, ["queueID"], issues);
57817
58418
  }
57818
58419
  function validateApplyInput(value, issues) {
57819
58420
  const path5 = [];
@@ -57910,7 +58511,7 @@ function validateStateOutput(value, issues) {
57910
58511
  "status",
57911
58512
  "settings"
57912
58513
  ],
57913
- ["reset", "route", "vaultHostStatus"]
58514
+ ["reset", "route", "vaultHostStatus", "queueID"]
57914
58515
  )) {
57915
58516
  return;
57916
58517
  }
@@ -57926,6 +58527,8 @@ function validateStateOutput(value, issues) {
57926
58527
  checkLiteral(value.reset, ANTIGRAVITY_STATE_RESETS, ["reset"], issues);
57927
58528
  }
57928
58529
  if (present4(value, "cursor")) checkCursor(value.cursor, ["cursor"], issues);
58530
+ if (present4(value, "queueID"))
58531
+ checkGeneration(value.queueID, ["queueID"], issues);
57929
58532
  if (present4(value, "dropped")) {
57930
58533
  checkCursor(value.dropped, ["dropped"], issues);
57931
58534
  }
@@ -58464,8 +59067,7 @@ async function startGaLoopbackBridge(options) {
58464
59067
  response.end(JSON.stringify({ error: { message: "unknown job" } }));
58465
59068
  return;
58466
59069
  }
58467
- queued.delete(id);
58468
- clearTimeout(entry.timer);
59070
+ entry.release();
58469
59071
  const state2 = {
58470
59072
  id,
58471
59073
  failure: void 0,
@@ -58534,11 +59136,11 @@ async function startGaLoopbackBridge(options) {
58534
59136
  }
58535
59137
  }
58536
59138
  };
58537
- await new Promise((resolve34, reject) => {
59139
+ await new Promise((resolve35, reject) => {
58538
59140
  server.once("error", reject);
58539
59141
  server.listen(0, BRIDGE_HOST, () => {
58540
59142
  server.off("error", reject);
58541
- resolve34();
59143
+ resolve35();
58542
59144
  });
58543
59145
  });
58544
59146
  server.unref();
@@ -58549,20 +59151,27 @@ async function startGaLoopbackBridge(options) {
58549
59151
  origin,
58550
59152
  rewrite(original, job, env3) {
58551
59153
  if (closing) throw new Error("The Antigravity bridge is disposed");
59154
+ const signal = original.signal;
59155
+ signal.throwIfAborted();
58552
59156
  const id = randomUUID21();
58553
59157
  const target = `${origin}/agy/${id}`;
58554
59158
  assertLoopbackProxyGuard({ env: env3, target });
58555
- const timer = setTimeout(() => {
58556
- queued.delete(id);
58557
- }, GA_UNCLAIMED_JOB_TTL_MS);
58558
- timer.unref?.();
58559
- queued.set(id, { job, timer });
58560
- return new Request(target, {
59159
+ const rewritten = new Request(target, {
58561
59160
  method: "POST",
58562
59161
  headers: { "content-type": "application/json" },
58563
59162
  body: "{}",
58564
- signal: original.signal
59163
+ signal
58565
59164
  });
59165
+ const release3 = () => {
59166
+ clearTimeout(timer);
59167
+ signal.removeEventListener("abort", release3);
59168
+ queued.delete(id);
59169
+ };
59170
+ const timer = setTimeout(release3, GA_UNCLAIMED_JOB_TTL_MS);
59171
+ timer.unref?.();
59172
+ queued.set(id, { job, release: release3 });
59173
+ signal.addEventListener("abort", release3, { once: true });
59174
+ return rewritten;
58566
59175
  },
58567
59176
  adaptResponse(request2, response) {
58568
59177
  let url;
@@ -58640,10 +59249,9 @@ async function startGaLoopbackBridge(options) {
58640
59249
  if (!disposal) {
58641
59250
  closing = true;
58642
59251
  disposal = (async () => {
58643
- for (const { timer } of queued.values()) clearTimeout(timer);
58644
- queued.clear();
58645
- const closed2 = new Promise((resolve34) => {
58646
- server.close(() => resolve34());
59252
+ for (const entry of queued.values()) entry.release();
59253
+ const closed2 = new Promise((resolve35) => {
59254
+ server.close(() => resolve35());
58647
59255
  });
58648
59256
  for (const controller of running) {
58649
59257
  controller.abort(
@@ -58710,9 +59318,14 @@ async function pipeResponse(upstream, response, onFailure, onHandoff) {
58710
59318
  return;
58711
59319
  }
58712
59320
  if (!response.write(value) && !response.destroyed) {
58713
- await new Promise((resolve34) => {
58714
- response.once("drain", resolve34);
58715
- response.once("close", resolve34);
59321
+ await new Promise((resolve35) => {
59322
+ const resume = () => {
59323
+ response.off("drain", resume);
59324
+ response.off("close", resume);
59325
+ resolve35();
59326
+ };
59327
+ response.once("drain", resume);
59328
+ response.once("close", resume);
58716
59329
  });
58717
59330
  }
58718
59331
  if (response.destroyed) {
@@ -58842,6 +59455,7 @@ function createGaRpcActivation(options) {
58842
59455
  scopes.delete(key2);
58843
59456
  } else {
58844
59457
  queue2 = {
59458
+ id: randomUUID21(),
58845
59459
  lastIssued: 0,
58846
59460
  evictedThrough: 0,
58847
59461
  notifications: [],
@@ -58940,6 +59554,8 @@ function createGaRpcActivation(options) {
58940
59554
  let reset = null;
58941
59555
  if (request2.generation === null) reset = "initial";
58942
59556
  else if (request2.generation !== generation) reset = "generation-changed";
59557
+ else if (request2.queueID !== void 0 && request2.queueID !== queue2.id && (request2.queueID !== null || request2.cursor !== 0))
59558
+ reset = "queue-changed";
58943
59559
  else if (request2.cursor > queue2.lastIssued) reset = "cursor-ahead";
58944
59560
  const acknowledged = reset === null ? request2.cursor : 0;
58945
59561
  queue2.notifications = queue2.notifications.filter(
@@ -58960,6 +59576,7 @@ function createGaRpcActivation(options) {
58960
59576
  scope: request2.scope,
58961
59577
  reset,
58962
59578
  cursor,
59579
+ ...request2.queueID !== void 0 ? { queueID: queue2.id } : {},
58963
59580
  dropped: Math.max(0, queue2.evictedThrough - acknowledged),
58964
59581
  more: queue2.notifications.length > delivered.length,
58965
59582
  notifications: delivered,
@@ -59419,13 +60036,13 @@ function createGaAntigravityPlugin(overrides = {}) {
59419
60036
  init_dist();
59420
60037
  init_runtime_layout();
59421
60038
  import { createHash as createHash24, randomUUID as randomUUID26 } from "node:crypto";
59422
- import { join as join47, resolve as resolve33 } from "node:path";
60039
+ import { join as join46, resolve as resolve34 } from "node:path";
59423
60040
 
59424
60041
  // src/cli.ts
59425
60042
  init_dist();
59426
60043
  import { execFile } from "node:child_process";
59427
60044
  import { realpathSync as realpathSync6 } from "node:fs";
59428
- import { resolve as resolve29 } from "node:path";
60045
+ import { resolve as resolve30 } from "node:path";
59429
60046
  import { createInterface } from "node:readline/promises";
59430
60047
  import { fileURLToPath as fileURLToPath2 } from "node:url";
59431
60048
  import { promisify } from "node:util";
@@ -59481,8 +60098,8 @@ init_runtime_paths();
59481
60098
 
59482
60099
  // src/setup.ts
59483
60100
  init_dist();
59484
- import { lstat as lstat10, readFile as readFile22 } from "node:fs/promises";
59485
- import { join as join38, resolve as resolve28 } from "node:path";
60101
+ import { lstat as lstat10, readFile as readFile23 } from "node:fs/promises";
60102
+ import { join as join37, resolve as resolve29 } from "node:path";
59486
60103
 
59487
60104
  // src/common-auth-embedded/auth-menu/ansi.js
59488
60105
  var ANSI2 = {
@@ -59650,7 +60267,7 @@ async function select2(terminal, items, options) {
59650
60267
  writeLine("");
59651
60268
  renderedLines = lines;
59652
60269
  };
59653
- return new Promise((resolve34) => {
60270
+ return new Promise((resolve35) => {
59654
60271
  const wasRaw = stdin.isRaw ?? false;
59655
60272
  const cleanup2 = () => {
59656
60273
  if (cleaned)
@@ -59670,7 +60287,7 @@ async function select2(terminal, items, options) {
59670
60287
  };
59671
60288
  const finish = (value) => {
59672
60289
  cleanup2();
59673
- resolve34(value);
60290
+ resolve35(value);
59674
60291
  };
59675
60292
  const onSignal = () => finish(null);
59676
60293
  const onKey = (data) => {
@@ -59710,7 +60327,7 @@ async function select2(terminal, items, options) {
59710
60327
  stdin.setRawMode(true);
59711
60328
  } catch {
59712
60329
  cleanup2();
59713
- resolve34(null);
60330
+ resolve35(null);
59714
60331
  return;
59715
60332
  }
59716
60333
  stdin.resume();
@@ -59723,13 +60340,13 @@ async function select2(terminal, items, options) {
59723
60340
  // src/common-auth-embedded/claustrum/enrollment.js
59724
60341
  import { createHash as createHash19, randomBytes as randomBytes6, randomUUID as randomUUID23 } from "node:crypto";
59725
60342
  import { constants as fsConstants2 } from "node:fs";
59726
- import { chmod as chmod6, mkdir as mkdir18, open as open11, readFile as readFile20, realpath as realpath6, rename as rename13, stat as stat17, unlink as unlink14 } from "node:fs/promises";
59727
- import { basename as basename13, dirname as dirname29, extname as extname2, isAbsolute as isAbsolute4, join as join34, resolve as resolve27 } from "node:path";
60343
+ import { chmod as chmod6, mkdir as mkdir18, open as open11, readFile as readFile21, realpath as realpath6, rename as rename13, stat as stat18, unlink as unlink14 } from "node:fs/promises";
60344
+ import { basename as basename13, dirname as dirname28, extname as extname2, isAbsolute as isAbsolute4, join as join33, resolve as resolve28 } from "node:path";
59728
60345
  import { ClaustrumCredentialError as ClaustrumCredentialError9, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
59729
60346
 
59730
60347
  // src/common-auth-embedded/fs/file-read-cache.js
59731
- import { lstat as lstat8, stat as stat15 } from "node:fs/promises";
59732
- import { resolve as resolve25 } from "node:path";
60348
+ import { lstat as lstat8, stat as stat16 } from "node:fs/promises";
60349
+ import { resolve as resolve26 } from "node:path";
59733
60350
  async function identity3(path5, probe) {
59734
60351
  try {
59735
60352
  const metadata = await probe(path5);
@@ -59747,10 +60364,10 @@ var FileReadCache2 = class {
59747
60364
  #probe;
59748
60365
  #entries = /* @__PURE__ */ new Map();
59749
60366
  constructor(options = {}) {
59750
- this.#probe = options.followSymlinks ? (path5) => (options.stat ?? stat15)(path5) : (path5) => (options.lstat ?? lstat8)(path5);
60367
+ this.#probe = options.followSymlinks ? (path5) => (options.stat ?? stat16)(path5) : (path5) => (options.lstat ?? lstat8)(path5);
59751
60368
  }
59752
60369
  async read(paths, read, validateHit) {
59753
- const resolvedPaths = paths.map((path5) => resolve25(path5));
60370
+ const resolvedPaths = paths.map((path5) => resolve26(path5));
59754
60371
  const key2 = JSON.stringify(resolvedPaths);
59755
60372
  const probed = await Promise.all(resolvedPaths.map((path5) => identity3(path5, this.#probe)));
59756
60373
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
@@ -59801,12 +60418,12 @@ init_private_files2();
59801
60418
  // src/common-auth-embedded/fs/refresh-file-lock.js
59802
60419
  init_logger3();
59803
60420
  import { randomUUID as randomUUID22 } from "node:crypto";
59804
- import { link as link4, lstat as lstat9, mkdir as mkdir17, open as open10, readdir as readdir6, readFile as readFile19, rename as rename12, rm as rm7, stat as stat16, unlink as unlink13 } from "node:fs/promises";
59805
- import { basename as basename12, dirname as dirname28, join as join33 } from "node:path";
60421
+ import { link as link4, lstat as lstat9, mkdir as mkdir17, open as open10, readdir as readdir6, readFile as readFile20, rename as rename12, rm as rm7, stat as stat17, unlink as unlink13 } from "node:fs/promises";
60422
+ import { basename as basename12, dirname as dirname27, join as join32 } from "node:path";
59806
60423
 
59807
60424
  // src/common-auth-embedded/fs/lock-record.js
59808
60425
  init_private_files2();
59809
- import { resolve as resolve26 } from "node:path";
60426
+ import { resolve as resolve27 } from "node:path";
59810
60427
  var DisappearedLockRecordError2 = class extends Error {
59811
60428
  path;
59812
60429
  code = "ENOENT";
@@ -59816,10 +60433,10 @@ var DisappearedLockRecordError2 = class extends Error {
59816
60433
  }
59817
60434
  };
59818
60435
  function isWindowsAccessDeniedRead2(error, paths) {
59819
- return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path5) => resolve26(path5) === error.path);
60436
+ return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path5) => resolve27(path5) === error.path);
59820
60437
  }
59821
60438
  function isWindowsAccessDeniedCreate2(error, paths, stage) {
59822
- return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path5) => resolve26(path5) === error.path);
60439
+ return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path5) => resolve27(path5) === error.path);
59823
60440
  }
59824
60441
  async function readLockRecord2(path5, read) {
59825
60442
  try {
@@ -59961,14 +60578,14 @@ async function readStagedOwner2(path5) {
59961
60578
  return { identity: before, expiresAt };
59962
60579
  }
59963
60580
  async function sweepAbandonedStaging2(lockPath, ttlMs, now2) {
59964
- const directory = dirname28(lockPath);
60581
+ const directory = dirname27(lockPath);
59965
60582
  const lockName = basename12(lockPath);
59966
60583
  const hooks = stagingSweepTestHooks2;
59967
60584
  const names = await (hooks?.readdir ?? readdir6)(directory);
59968
60585
  const candidates = names.filter((name) => isStagingName2(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES2);
59969
60586
  const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS2);
59970
60587
  for (const name of candidates) {
59971
- const path5 = join33(directory, name);
60588
+ const path5 = join32(directory, name);
59972
60589
  try {
59973
60590
  if (now2() - (await lstat9(path5)).mtimeMs < marginMs)
59974
60591
  continue;
@@ -60014,7 +60631,7 @@ function acquireRefreshFileLock2(options) {
60014
60631
  }
60015
60632
  async function acquireRefreshFileLockWithClock2(options) {
60016
60633
  const lockPath = lockPathFor2(options.path, options.name);
60017
- const legacyOwnerPath = join33(lockPath, "owner.json");
60634
+ const legacyOwnerPath = join32(lockPath, "owner.json");
60018
60635
  const ownerId = randomUUID22();
60019
60636
  const now2 = options.now ?? Date.now;
60020
60637
  let renewTimer = null;
@@ -60022,8 +60639,8 @@ async function acquireRefreshFileLockWithClock2(options) {
60022
60639
  let releaseConfirmed = false;
60023
60640
  let loss;
60024
60641
  let resolveLoss;
60025
- const lostPromise = new Promise((resolve34) => {
60026
- resolveLoss = resolve34;
60642
+ const lostPromise = new Promise((resolve35) => {
60643
+ resolveLoss = resolve35;
60027
60644
  });
60028
60645
  function notifyTimerStep(event) {
60029
60646
  try {
@@ -60057,7 +60674,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60057
60674
  let terminalIOError;
60058
60675
  let renewalInFlight = null;
60059
60676
  const evictPath = `${lockPath}.evicting`;
60060
- const evictOwnerPath = join33(evictPath, "owner.json");
60677
+ const evictOwnerPath = join32(evictPath, "owner.json");
60061
60678
  const evictOwnerId = randomUUID22();
60062
60679
  const EVICT_TTL = 5e3;
60063
60680
  const MAX_STEAL_ATTEMPTS = 8;
@@ -60076,12 +60693,12 @@ async function acquireRefreshFileLockWithClock2(options) {
60076
60693
  }
60077
60694
  }
60078
60695
  try {
60079
- return JSON.parse(await readFile19(lockPath, "utf8"));
60696
+ return JSON.parse(await readFile20(lockPath, "utf8"));
60080
60697
  } catch (error) {
60081
60698
  const code2 = error.code;
60082
60699
  if (code2 !== "EISDIR")
60083
60700
  throw error;
60084
- return JSON.parse(await readFile19(legacyOwnerPath, "utf8"));
60701
+ return JSON.parse(await readFile20(legacyOwnerPath, "utf8"));
60085
60702
  }
60086
60703
  }
60087
60704
  async function writeOwner() {
@@ -60161,7 +60778,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60161
60778
  }
60162
60779
  async function tryAcquire() {
60163
60780
  if (windowsPrivateFiles2)
60164
- await ensurePrivateDirectory2(dirname28(lockPath));
60781
+ await ensurePrivateDirectory2(dirname27(lockPath));
60165
60782
  try {
60166
60783
  await createLease();
60167
60784
  return true;
@@ -60171,9 +60788,9 @@ async function acquireRefreshFileLockWithClock2(options) {
60171
60788
  return false;
60172
60789
  if (code2 === "ENOENT") {
60173
60790
  if (windowsPrivateFiles2)
60174
- await ensurePrivateDirectory2(dirname28(lockPath));
60791
+ await ensurePrivateDirectory2(dirname27(lockPath));
60175
60792
  else
60176
- await mkdir17(dirname28(lockPath), { recursive: true });
60793
+ await mkdir17(dirname27(lockPath), { recursive: true });
60177
60794
  try {
60178
60795
  await createLease();
60179
60796
  return true;
@@ -60187,7 +60804,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60187
60804
  }
60188
60805
  }
60189
60806
  async function backoff() {
60190
- await new Promise((resolve34) => setTimeout(resolve34, Math.floor(Math.random() * 4)));
60807
+ await new Promise((resolve35) => setTimeout(resolve35, Math.floor(Math.random() * 4)));
60191
60808
  }
60192
60809
  async function readLockState(notifyReady = true) {
60193
60810
  if (notifyReady && options.onStep)
@@ -60211,7 +60828,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60211
60828
  };
60212
60829
  }
60213
60830
  try {
60214
- const current = await stat16(lockPath);
60831
+ const current = await stat17(lockPath);
60215
60832
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
60216
60833
  if (legacyExpiry > now2())
60217
60834
  return { status: "live" };
@@ -60280,7 +60897,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60280
60897
  const remainingMs = deadline - performance.now();
60281
60898
  if (remainingMs <= 0)
60282
60899
  throw original;
60283
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
60900
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(delayMs, remainingMs)));
60284
60901
  if (performance.now() >= deadline)
60285
60902
  throw original;
60286
60903
  delayMs = Math.min(delayMs * 2, 50);
@@ -60305,7 +60922,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60305
60922
  if (!ownedDirectory)
60306
60923
  return false;
60307
60924
  try {
60308
- await stat16(evictOwnerPath);
60925
+ await stat17(evictOwnerPath);
60309
60926
  return false;
60310
60927
  } catch (error) {
60311
60928
  if (error.code !== "ENOENT")
@@ -60326,7 +60943,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60326
60943
  return false;
60327
60944
  stillOurs = true;
60328
60945
  try {
60329
- await stat16(evictOwnerPath);
60946
+ await stat17(evictOwnerPath);
60330
60947
  return false;
60331
60948
  } catch (error) {
60332
60949
  return error.code === "ENOENT";
@@ -60376,7 +60993,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60376
60993
  async function recoverStaleEvictionMarker(deadline) {
60377
60994
  let evictStat;
60378
60995
  try {
60379
- evictStat = await stat16(evictPath);
60996
+ evictStat = await stat17(evictPath);
60380
60997
  } catch (error) {
60381
60998
  if (error.code === "ENOENT")
60382
60999
  return "missing";
@@ -60394,7 +61011,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60394
61011
  if (evictStat.mtimeMs + EVICT_TTL > now2()) {
60395
61012
  let hasOwner = true;
60396
61013
  try {
60397
- await stat16(evictOwnerPath);
61014
+ await stat17(evictOwnerPath);
60398
61015
  } catch (error) {
60399
61016
  if (error.code === "ENOENT")
60400
61017
  hasOwner = false;
@@ -60783,7 +61400,7 @@ async function acquireRefreshFileLockWithClock2(options) {
60783
61400
  const remainingMs = deadline - performance.now();
60784
61401
  if (remainingMs <= 0)
60785
61402
  break;
60786
- await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
61403
+ await new Promise((resolve35) => setTimeout(resolve35, Math.min(delayMs, remainingMs)));
60787
61404
  if (windowsPrivateFiles2 && performance.now() >= deadline)
60788
61405
  break;
60789
61406
  delayMs = Math.min(delayMs * 2, 50);
@@ -60864,7 +61481,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
60864
61481
  const extension = extname2(tokenPath) || ".json";
60865
61482
  const stem = basename13(tokenPath, extname2(tokenPath));
60866
61483
  return {
60867
- statePath: join34(dirname29(tokenPath), `${stem}-state${extension}`),
61484
+ statePath: join33(dirname28(tokenPath), `${stem}-state${extension}`),
60868
61485
  tokenPath
60869
61486
  };
60870
61487
  }
@@ -60872,7 +61489,7 @@ function hostEnrollmentPaths2(input2) {
60872
61489
  const override = input2.override?.trim();
60873
61490
  if (override && !isAbsolute4(override) && !input2.cwd)
60874
61491
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
60875
- const tokenPath = override ? isAbsolute4(override) ? override : resolve27(input2.cwd, override) : join34(input2.stateDir, `${input2.host}-enrollment.json`);
61492
+ const tokenPath = override ? isAbsolute4(override) ? override : resolve28(input2.cwd, override) : join33(input2.stateDir, `${input2.host}-enrollment.json`);
60876
61493
  return getClaustrumEnrollmentPaths2(tokenPath);
60877
61494
  }
60878
61495
  function isRecord11(value) {
@@ -60978,7 +61595,7 @@ function parseSecretJson2(text2) {
60978
61595
  async function readBoundedJson2(path5) {
60979
61596
  if (windowsPrivateFiles2) {
60980
61597
  try {
60981
- await ensurePrivateDirectory2(dirname29(path5));
61598
+ await ensurePrivateDirectory2(dirname28(path5));
60982
61599
  const text2 = await readPrivateText2(path5, true);
60983
61600
  if (Buffer.byteLength(text2) > ENROLLMENT_FILE_MAX_BYTES2) {
60984
61601
  throw new ClaustrumConsumerError2("unsafe-file", "Claustrum enrollment file is too large");
@@ -61025,8 +61642,8 @@ function accountRecords2(text2, fields2) {
61025
61642
  async function isPrivateGroup2(uid, gid, options) {
61026
61643
  try {
61027
61644
  const [passwdText, groupText] = await Promise.all([
61028
- readFile20(options.passwdPath ?? "/etc/passwd", "utf8"),
61029
- readFile20(options.groupPath ?? "/etc/group", "utf8")
61645
+ readFile21(options.passwdPath ?? "/etc/passwd", "utf8"),
61646
+ readFile21(options.groupPath ?? "/etc/group", "utf8")
61030
61647
  ]);
61031
61648
  const users = accountRecords2(passwdText, 7);
61032
61649
  const groups = accountRecords2(groupText, 4);
@@ -61048,7 +61665,7 @@ function ancestorPolicyOptions2(options) {
61048
61665
  return void 0;
61049
61666
  return {
61050
61667
  fs: {
61051
- readFile: (path5) => readFile20(path5 === "/etc/passwd" ? options.passwdPath ?? path5 : path5 === "/etc/group" ? options.groupPath ?? path5 : path5)
61668
+ readFile: (path5) => readFile21(path5 === "/etc/passwd" ? options.passwdPath ?? path5 : path5 === "/etc/group" ? options.groupPath ?? path5 : path5)
61052
61669
  }
61053
61670
  };
61054
61671
  }
@@ -61066,7 +61683,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
61066
61683
  }
61067
61684
  let privateGroup;
61068
61685
  for (; ; ) {
61069
- const metadata = await stat17(component).catch(() => void 0);
61686
+ const metadata = await stat18(component).catch(() => void 0);
61070
61687
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
61071
61688
  if (privateGroup === void 0) {
61072
61689
  privateGroup = gid !== void 0 && await isPrivateGroup2(uid, gid, options);
@@ -61075,7 +61692,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
61075
61692
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
61076
61693
  }
61077
61694
  }
61078
- const next = dirname29(component);
61695
+ const next = dirname28(component);
61079
61696
  if (next === component)
61080
61697
  return;
61081
61698
  component = next;
@@ -61095,7 +61712,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
61095
61712
  return;
61096
61713
  }
61097
61714
  await mkdir18(directory, { recursive: true, mode: 448 });
61098
- const metadata = await stat17(directory);
61715
+ const metadata = await stat18(directory);
61099
61716
  const uid = process.geteuid?.();
61100
61717
  if (uid !== void 0 && metadata.uid !== uid) {
61101
61718
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -61104,7 +61721,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
61104
61721
  await chmod6(directory, 448);
61105
61722
  }
61106
61723
  async function writeStateAtomic2(path5, state2, ancestorOptions = {}) {
61107
- const parent = dirname29(path5);
61724
+ const parent = dirname28(path5);
61108
61725
  await ensureClaustrumPrivateDirectory2(parent, ancestorOptions);
61109
61726
  await refuseWritableAncestor2(parent, ancestorOptions);
61110
61727
  const bytes = `${JSON.stringify(state2)}
@@ -61114,7 +61731,7 @@ async function writeStateAtomic2(path5, state2, ancestorOptions = {}) {
61114
61731
  }
61115
61732
  if (windowsPrivateFiles2)
61116
61733
  return writePrivateAtomic2(path5, bytes);
61117
- const temporary = join34(parent, `.${basename13(path5)}.${process.pid}.${randomUUID23()}.tmp`);
61734
+ const temporary = join33(parent, `.${basename13(path5)}.${process.pid}.${randomUUID23()}.tmp`);
61118
61735
  let descriptor;
61119
61736
  let created = false;
61120
61737
  try {
@@ -61293,7 +61910,7 @@ var ClaustrumEnrollmentManager2 = class {
61293
61910
  return statusFromState2(blocked);
61294
61911
  }
61295
61912
  async reconcile() {
61296
- await ensureClaustrumPrivateDirectory2(dirname29(this.#paths.statePath), this.#ancestorOptions);
61913
+ await ensureClaustrumPrivateDirectory2(dirname28(this.#paths.statePath), this.#ancestorOptions);
61297
61914
  const lock = await acquireRefreshFileLock2({
61298
61915
  name: "ceremony",
61299
61916
  path: this.#paths.statePath,
@@ -61446,8 +62063,8 @@ var ClaustrumEnrollmentManager2 = class {
61446
62063
  await writeStateAtomic2(this.#paths.statePath, denied, this.#ancestorOptions);
61447
62064
  return statusFromState2(denied);
61448
62065
  }
61449
- await ensureClaustrumPrivateDirectory2(dirname29(this.#paths.tokenPath), this.#ancestorOptions);
61450
- await refuseWritableAncestor2(dirname29(this.#paths.tokenPath), this.#ancestorOptions);
62066
+ await ensureClaustrumPrivateDirectory2(dirname28(this.#paths.tokenPath), this.#ancestorOptions);
62067
+ await refuseWritableAncestor2(dirname28(this.#paths.tokenPath), this.#ancestorOptions);
61451
62068
  await this.#writeTokenFile(this.#paths.tokenPath, {
61452
62069
  token: outcome.token,
61453
62070
  token_generation: outcome.tokenGeneration
@@ -61484,7 +62101,7 @@ var ClaustrumEnrollmentManager2 = class {
61484
62101
  }
61485
62102
  };
61486
62103
  async function resetClaustrumEnrollmentState2(paths, proposedName) {
61487
- await ensureClaustrumPrivateDirectory2(dirname29(paths.statePath));
62104
+ await ensureClaustrumPrivateDirectory2(dirname28(paths.statePath));
61488
62105
  const lock = await acquireRefreshFileLock2({
61489
62106
  name: "ceremony",
61490
62107
  path: paths.statePath,
@@ -61566,7 +62183,7 @@ var ByteTail = class {
61566
62183
  };
61567
62184
  var defaultCommandRunner = {
61568
62185
  run(file, args, options = {}) {
61569
- return new Promise((resolve34) => {
62186
+ return new Promise((resolve35) => {
61570
62187
  const started = performance.now();
61571
62188
  const timeoutMs = options.timeoutMs ?? 15e3;
61572
62189
  const stderr = new ByteTail();
@@ -61584,7 +62201,7 @@ var defaultCommandRunner = {
61584
62201
  stdio: ["ignore", "pipe", "pipe"]
61585
62202
  });
61586
62203
  } catch {
61587
- resolve34({
62204
+ resolve35({
61588
62205
  exitCode: 1,
61589
62206
  stdout: "",
61590
62207
  stderr: "",
@@ -61619,7 +62236,7 @@ var defaultCommandRunner = {
61619
62236
  settled = true;
61620
62237
  if (timer)
61621
62238
  clearTimeout(timer);
61622
- resolve34({
62239
+ resolve35({
61623
62240
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
61624
62241
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
61625
62242
  stderr: stderr.toString(),
@@ -61775,10 +62392,10 @@ function recordSetupEnrollment(failure2, enrollment) {
61775
62392
  }
61776
62393
 
61777
62394
  // src/common-auth-embedded/setup/detect.js
61778
- import { accessSync, constants as constants3, existsSync as existsSync12, readFileSync as readFileSync11, realpathSync as realpathSync5, statSync as statSync6 } from "node:fs";
62395
+ import { accessSync, constants as constants3, existsSync as existsSync12, readFileSync as readFileSync11, realpathSync as realpathSync5, statSync as statSync7 } from "node:fs";
61779
62396
  import { mkdtemp, rm as rm8 } from "node:fs/promises";
61780
- import { tmpdir as tmpdir5 } from "node:os";
61781
- import { join as join35 } from "node:path";
62397
+ import { tmpdir as tmpdir4 } from "node:os";
62398
+ import { join as join34 } from "node:path";
61782
62399
  import { parse } from "jsonc-parser";
61783
62400
 
61784
62401
  // src/common-auth-embedded/setup/paths.js
@@ -61813,21 +62430,21 @@ function setupPaths(io = {}) {
61813
62430
  }
61814
62431
 
61815
62432
  // src/common-auth-embedded/setup/detect.js
61816
- function stat18(path5, kind) {
62433
+ function stat19(path5, kind) {
61817
62434
  try {
61818
- return statSync6(path5)[kind]();
62435
+ return statSync7(path5)[kind]();
61819
62436
  } catch {
61820
62437
  return false;
61821
62438
  }
61822
62439
  }
61823
62440
  var defaultSetupFileSystem = {
61824
62441
  exists: existsSync12,
61825
- isFile: (path5) => stat18(path5, "isFile"),
61826
- isDirectory: (path5) => stat18(path5, "isDirectory"),
62442
+ isFile: (path5) => stat19(path5, "isFile"),
62443
+ isDirectory: (path5) => stat19(path5, "isDirectory"),
61827
62444
  isExecutable(path5) {
61828
62445
  try {
61829
62446
  accessSync(path5, constants3.X_OK);
61830
- return stat18(path5, "isFile");
62447
+ return stat19(path5, "isFile");
61831
62448
  } catch {
61832
62449
  return false;
61833
62450
  }
@@ -61949,7 +62566,7 @@ async function detectHosts(plugin2, io = {}) {
61949
62566
  return null;
61950
62567
  let root;
61951
62568
  try {
61952
- root = await mkdtemp(join35(tmpdir5(), "common-auth-setup-version-"));
62569
+ root = await mkdtemp(join34(tmpdir4(), "common-auth-setup-version-"));
61953
62570
  const probeEnv = {
61954
62571
  ...env3,
61955
62572
  HOME: root,
@@ -62016,14 +62633,14 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
62016
62633
 
62017
62634
  // src/common-auth-embedded/setup/process-fence.js
62018
62635
  init_logger3();
62019
- import { statSync as statSync7 } from "node:fs";
62636
+ import { statSync as statSync8 } from "node:fs";
62020
62637
  import { win32 as win325 } from "node:path";
62021
62638
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
62022
62639
  var log13 = createLogger3("setup-process-fence");
62023
62640
  var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
62024
62641
  function isFile(file) {
62025
62642
  try {
62026
- return statSync7(file).isFile();
62643
+ return statSync8(file).isFile();
62027
62644
  } catch {
62028
62645
  return false;
62029
62646
  }
@@ -62628,23 +63245,23 @@ import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtL
62628
63245
 
62629
63246
  // src/common-auth-embedded/setup/config-write.js
62630
63247
  import { randomUUID as randomUUID24 } from "node:crypto";
62631
- import { mkdir as mkdir19, open as open12, rename as rename14, stat as stat19, unlink as unlink15 } from "node:fs/promises";
62632
- import { basename as basename14, dirname as dirname30, join as join36 } from "node:path";
63248
+ import { mkdir as mkdir19, open as open12, rename as rename14, stat as stat20, unlink as unlink15 } from "node:fs/promises";
63249
+ import { basename as basename14, dirname as dirname29, join as join35 } from "node:path";
62633
63250
  import { setTimeout as delay3 } from "node:timers/promises";
62634
63251
  async function writeHostConfigAtomic(file, content, options = {}) {
62635
63252
  const windows2 = (options.platform ?? process.platform) === "win32";
62636
- const parent = dirname30(file);
63253
+ const parent = dirname29(file);
62637
63254
  await mkdir19(parent, { recursive: true });
62638
63255
  let mode;
62639
63256
  if (!windows2) {
62640
63257
  try {
62641
- mode = (await stat19(file)).mode & 4095;
63258
+ mode = (await stat20(file)).mode & 4095;
62642
63259
  } catch (error) {
62643
63260
  if (error.code !== "ENOENT")
62644
63261
  throw error;
62645
63262
  }
62646
63263
  }
62647
- const stage = join36(parent, `.${basename14(file)}.${(options.stageName ?? randomUUID24)()}.tmp`);
63264
+ const stage = join35(parent, `.${basename14(file)}.${(options.stageName ?? randomUUID24)()}.tmp`);
62648
63265
  let created = false;
62649
63266
  try {
62650
63267
  const handle = await open12(stage, "wx", mode ?? 438);
@@ -63094,13 +63711,13 @@ init_storage();
63094
63711
 
63095
63712
  // src/plugin/vault-activation.ts
63096
63713
  init_dist();
63097
- import { readFile as readFile21 } from "node:fs/promises";
63714
+ import { readFile as readFile22 } from "node:fs/promises";
63098
63715
  import { homedir as homedir12 } from "node:os";
63099
- import { join as join37 } from "node:path";
63716
+ import { join as join36 } from "node:path";
63100
63717
  var V1_VAULT_ACTIVATION_LABEL = "Activate approved Antigravity vault";
63101
63718
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir12()) {
63102
- return join37(
63103
- env3.XDG_DATA_HOME || join37(home, ".local", "share"),
63719
+ return join36(
63720
+ env3.XDG_DATA_HOME || join36(home, ".local", "share"),
63104
63721
  "opencode",
63105
63722
  "auth.json"
63106
63723
  );
@@ -63119,7 +63736,7 @@ function createV1VaultActivationMethod(input2) {
63119
63736
  return { type: "failed" };
63120
63737
  try {
63121
63738
  const value = JSON.parse(
63122
- await readFile21(
63739
+ await readFile22(
63123
63740
  (input2.authFile ?? nativeOpenCodeAuthPath)(),
63124
63741
  "utf8"
63125
63742
  )
@@ -63171,7 +63788,7 @@ function openCodeVaultDir(accountFile) {
63171
63788
  return folder.vaultDir;
63172
63789
  }
63173
63790
  function nativeAuthPath(host, context) {
63174
- return host === "opencode" ? nativeOpenCodeAuthPath() : join38(context.piAgentDir, "auth.json");
63791
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join37(context.piAgentDir, "auth.json");
63175
63792
  }
63176
63793
  function provider(host) {
63177
63794
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -63184,7 +63801,7 @@ async function readNativeAuth(path5) {
63184
63801
  const info = await lstat10(path5);
63185
63802
  if (!info.isFile() || info.nlink !== 1)
63186
63803
  throw new Error("Native auth must be a regular, unaliased file.");
63187
- const value = JSON.parse(await readFile22(path5, "utf8"));
63804
+ const value = JSON.parse(await readFile23(path5, "utf8"));
63188
63805
  if (!value || typeof value !== "object" || Array.isArray(value))
63189
63806
  throw new Error("Native auth is invalid; refusing to replace it.");
63190
63807
  return value;
@@ -63193,19 +63810,31 @@ async function readNativeAuth(path5) {
63193
63810
  throw error;
63194
63811
  }
63195
63812
  }
63813
+ async function readOpenCodeAuthority(legacyPath) {
63814
+ try {
63815
+ const claustrum = await loadCommonAuthClaustrum();
63816
+ if (claustrum.hasVaultHost()) return "host";
63817
+ return await vaultAuthority2(
63818
+ claustrum.hostEnrollmentPaths({
63819
+ stateDir: openCodeVaultDir(
63820
+ legacyPath ?? resolve29(accountFileForVault())
63821
+ ),
63822
+ host: "opencode"
63823
+ }),
63824
+ OPENCODE_VAULT_ENROLLMENT_NAME,
63825
+ claustrum
63826
+ );
63827
+ } catch {
63828
+ return "unreadable";
63829
+ }
63830
+ }
63196
63831
  async function assertLocalOpenCodeLogin(legacyPath, generation) {
63197
- const claustrum = await loadCommonAuthClaustrum();
63198
- if (await claustrum.vaultAuthority(
63199
- claustrum.hostEnrollmentPaths({
63200
- stateDir: openCodeVaultDir(legacyPath),
63201
- host: "opencode"
63202
- }),
63203
- OPENCODE_VAULT_ENROLLMENT_NAME
63204
- ) !== "local")
63832
+ if (await readOpenCodeAuthority(legacyPath) !== "local")
63205
63833
  throw new Error(
63206
63834
  "Vault enrollment excludes local sign-in. Resolve vault access before choosing local setup."
63207
63835
  );
63208
63836
  if (generation === "2") return;
63837
+ const claustrum = await loadCommonAuthClaustrum();
63209
63838
  claustrum.assertHostSlotMatchesMode({
63210
63839
  mode: "local",
63211
63840
  auth: (await readNativeAuth(nativeOpenCodeAuthPath()))[OPENCODE_VAULT_PROVIDER],
@@ -63227,7 +63856,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
63227
63856
  beforeRename: async () => {
63228
63857
  await assertSetupHostsStopped();
63229
63858
  const claustrum = await loadCommonAuthClaustrum();
63230
- const stateDir = host === "opencode" ? openCodeVaultDir(resolve28(accountFileForVault())) : getPiAntigravityVaultDir();
63859
+ const stateDir = host === "opencode" ? openCodeVaultDir(resolve29(accountFileForVault())) : getPiAntigravityVaultDir();
63231
63860
  if (await claustrum.vaultAuthority(
63232
63861
  claustrum.hostEnrollmentPaths({ stateDir, host }),
63233
63862
  `antigravity-auth-${host}`
@@ -63272,7 +63901,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
63272
63901
  // `beforeSignIn`, which may move it after this plugin is built.
63273
63902
  paths: {
63274
63903
  get stateDir() {
63275
- return openCodeVaultDir(resolve28(accountFileForVault()));
63904
+ return openCodeVaultDir(resolve29(accountFileForVault()));
63276
63905
  },
63277
63906
  host: "opencode"
63278
63907
  }
@@ -63296,7 +63925,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
63296
63925
  const assertLocal = async (host, context) => {
63297
63926
  if (host === "opencode")
63298
63927
  return assertLocalOpenCodeLogin(
63299
- resolve28(accountFileForVault()),
63928
+ resolve29(accountFileForVault()),
63300
63929
  context.opencodeGeneration
63301
63930
  );
63302
63931
  if (await authority(host) !== "local")
@@ -63312,7 +63941,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
63312
63941
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
63313
63942
  if ((await openPiSlot2({
63314
63943
  authPath: nativeAuthPath(host, context),
63315
- stashPath: join38(piDir, "google-login-stash.json"),
63944
+ stashPath: join37(piDir, "google-login-stash.json"),
63316
63945
  provider: ANTIGRAVITY_PROVIDER_ID,
63317
63946
  placeholderKey: PI_PLACEHOLDER_KEY
63318
63947
  }).inspect()).slot === "placeholder")
@@ -63330,7 +63959,7 @@ Setup has not completed the OpenCode 2 native Google connection.
63330
63959
  );
63331
63960
  };
63332
63961
  const manifest = JSON.parse(
63333
- await readFile22(new URL("../package.json", import.meta.url), "utf8")
63962
+ await readFile23(new URL("../package.json", import.meta.url), "utf8")
63334
63963
  );
63335
63964
  return {
63336
63965
  packages: {
@@ -63359,7 +63988,7 @@ Setup has not completed the OpenCode 2 native Google connection.
63359
63988
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
63360
63989
  await openPiSlot2({
63361
63990
  authPath: nativeAuthPath("pi", context),
63362
- stashPath: join38(piDir, "google-login-stash.json"),
63991
+ stashPath: join37(piDir, "google-login-stash.json"),
63363
63992
  provider: ANTIGRAVITY_PROVIDER_ID,
63364
63993
  placeholderKey: PI_PLACEHOLDER_KEY
63365
63994
  }).inspect();
@@ -63472,7 +64101,7 @@ Setup has not completed the OpenCode 2 native Google connection.
63472
64101
  await assertSetupHostsStopped();
63473
64102
  await openPiSlot2({
63474
64103
  authPath: nativeAuthPath(host, context),
63475
- stashPath: join38(piDir, "google-login-stash.json"),
64104
+ stashPath: join37(piDir, "google-login-stash.json"),
63476
64105
  provider: ANTIGRAVITY_PROVIDER_ID,
63477
64106
  placeholderKey: PI_PLACEHOLDER_KEY
63478
64107
  }).enterVault();
@@ -63821,6 +64450,16 @@ async function runCli(argv, deps) {
63821
64450
  return 0;
63822
64451
  }
63823
64452
  try {
64453
+ const assertLocalAccounts = async () => {
64454
+ const authority = await (deps.readAuthority ?? readOpenCodeAuthority)();
64455
+ if (authority === "local") return;
64456
+ 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.";
64457
+ throw new Error(
64458
+ `${source2} Use the /antigravity menu in OpenCode to see them and their quota.`
64459
+ );
64460
+ };
64461
+ if (parsed.value.command === "list" || parsed.value.command === "quota")
64462
+ await assertLocalAccounts();
63824
64463
  if (parsed.value.command !== "setup") {
63825
64464
  if (parsed.value.command === "login") await deps.prepareVaultFolder?.();
63826
64465
  await deps.processHeartbeat?.();
@@ -63925,7 +64564,8 @@ async function runCli(argv, deps) {
63925
64564
  return 0;
63926
64565
  }
63927
64566
  const results = await deps.getQuota(storage?.accounts ?? [], {
63928
- refresh: parsed.value.refresh
64567
+ refresh: parsed.value.refresh,
64568
+ ...parsed.value.refresh ? { assertAdmission: assertLocalAccounts } : {}
63929
64569
  });
63930
64570
  deps.stdout.write(
63931
64571
  parsed.value.json ? `${JSON.stringify(quotaSummary(results))}
@@ -63948,7 +64588,7 @@ async function runCliProcess(argv, deps) {
63948
64588
  ...deps,
63949
64589
  prepareVaultFolder: deps.prepareVaultFolder ?? (async (options) => {
63950
64590
  const folder = await prepareVaultFolder({
63951
- accountFile: resolve29(accountFileForVault()),
64591
+ accountFile: resolve30(accountFileForVault()),
63952
64592
  ...options
63953
64593
  });
63954
64594
  if (folder.refusal) throw folder.refusal;
@@ -63994,11 +64634,11 @@ function createDefaultCliDependencies() {
63994
64634
  );
63995
64635
  if (host !== "pi")
63996
64636
  await assertLocalOpenCodeLogin(
63997
- resolve29(accountFileForVault()),
64637
+ resolve30(accountFileForVault()),
63998
64638
  context?.opencodeGeneration
63999
64639
  );
64000
64640
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(
64001
- resolve29(getStoragePath()),
64641
+ resolve30(getStoragePath()),
64002
64642
  context?.opencodeGeneration
64003
64643
  );
64004
64644
  try {
@@ -64014,7 +64654,7 @@ function createDefaultCliDependencies() {
64014
64654
  }
64015
64655
  if (host === "opencode") await assertSetupHostsStopped();
64016
64656
  await assertLocalOpenCodeLogin(
64017
- resolve29(accountFileForVault()),
64657
+ resolve30(accountFileForVault()),
64018
64658
  context?.opencodeGeneration
64019
64659
  );
64020
64660
  await persistCliStoreLogin(
@@ -64034,7 +64674,7 @@ function createDefaultCliDependencies() {
64034
64674
  };
64035
64675
  }
64036
64676
  async function prepareCliLoginStore(legacyPath, generation) {
64037
- await assertLocalOpenCodeLogin(resolve29(accountFileForVault()), generation);
64677
+ await assertLocalOpenCodeLogin(resolve30(accountFileForVault()), generation);
64038
64678
  const modules = await loadCommonAuthStoreModules();
64039
64679
  const options = {
64040
64680
  legacyPath,
@@ -64179,7 +64819,7 @@ async function readAccountStore(legacyPath) {
64179
64819
  function createDefaultAccountStoreOperations() {
64180
64820
  const offline = { processesStopped: true };
64181
64821
  return {
64182
- legacyPath: () => resolve29(
64822
+ legacyPath: () => resolve30(
64183
64823
  decidedAccountStoreAnchor(runtimeLayoutLocation()) ? getStoragePath() : discoveredAccountFile()
64184
64824
  ),
64185
64825
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
@@ -64210,7 +64850,7 @@ function createDefaultAccountStoreOperations() {
64210
64850
  };
64211
64851
  }
64212
64852
  function samePath(left, right) {
64213
- return process.platform === "win32" ? resolve29(left).toLowerCase() === resolve29(right).toLowerCase() : resolve29(left) === resolve29(right);
64853
+ return process.platform === "win32" ? resolve30(left).toLowerCase() === resolve30(right).toLowerCase() : resolve30(left) === resolve30(right);
64214
64854
  }
64215
64855
  function isCliEntry() {
64216
64856
  if (import.meta.main !== void 0) return import.meta.main;
@@ -64389,8 +65029,8 @@ function getLocalDevPath(directory) {
64389
65029
  }
64390
65030
  function findPackageJsonUp(startPath) {
64391
65031
  try {
64392
- const stat21 = fs6.statSync(startPath);
64393
- let dir = stat21.isDirectory() ? startPath : path4.dirname(startPath);
65032
+ const stat22 = fs6.statSync(startPath);
65033
+ let dir = stat22.isDirectory() ? startPath : path4.dirname(startPath);
64394
65034
  for (let i = 0; i < 10; i++) {
64395
65035
  const pkgPath = path4.join(dir, "package.json");
64396
65036
  if (fs6.existsSync(pkgPath)) {
@@ -64699,17 +65339,17 @@ function isTuiConnected(sessionId) {
64699
65339
 
64700
65340
  // src/rpc/rpc-dir.ts
64701
65341
  import { createHash as createHash20 } from "node:crypto";
64702
- import { homedir as homedir14, tmpdir as tmpdir6 } from "node:os";
64703
- import { isAbsolute as isAbsolute5, join as join42, resolve as resolve30 } from "node:path";
65342
+ import { homedir as homedir14, tmpdir as tmpdir5 } from "node:os";
65343
+ import { isAbsolute as isAbsolute5, join as join41, resolve as resolve31 } from "node:path";
64704
65344
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
64705
65345
  function getRpcDir(projectDirectory) {
64706
65346
  const override = process.env[RPC_DIR_ENV]?.trim();
64707
65347
  if (override) {
64708
- return isAbsolute5(override) ? override : resolve30(projectDirectory, override);
65348
+ return isAbsolute5(override) ? override : resolve31(projectDirectory, override);
64709
65349
  }
64710
- const projectHash = createHash20("sha256").update(resolve30(projectDirectory)).digest("hex").slice(0, 16);
64711
- const stateHome = process.env.XDG_STATE_HOME ?? join42(homedir14(), ".local", "state");
64712
- return join42(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
65350
+ const projectHash = createHash20("sha256").update(resolve31(projectDirectory)).digest("hex").slice(0, 16);
65351
+ const stateHome = process.env.XDG_STATE_HOME ?? join41(homedir14(), ".local", "state");
65352
+ return join41(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
64713
65353
  }
64714
65354
 
64715
65355
  // src/common-auth-embedded/rpc/notifications.js
@@ -64720,9 +65360,9 @@ function isSessionId(value) {
64720
65360
  // src/common-auth-embedded/rpc/port-file.js
64721
65361
  init_private_files2();
64722
65362
  import { createHash as createHash21, randomUUID as randomUUID25 } from "node:crypto";
64723
- import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename16, rmdir as rmdir3, stat as stat20, unlink as unlink16 } from "node:fs/promises";
65363
+ import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename16, rmdir as rmdir3, stat as stat21, unlink as unlink16 } from "node:fs/promises";
64724
65364
  import { uptime as uptime2 } from "node:os";
64725
- import { join as join43, resolve as resolve31 } from "node:path";
65365
+ import { join as join42, resolve as resolve32 } from "node:path";
64726
65366
  function staleBefore(clock2) {
64727
65367
  return (clock2.now ?? Date.now)() - (clock2.uptime ?? uptime2)() * 1e3 - 3e5;
64728
65368
  }
@@ -64736,7 +65376,7 @@ async function removeStalePortFile(path5, raw, info, beforeRemove2) {
64736
65376
  await beforeRemove2?.(path5);
64737
65377
  try {
64738
65378
  const current = await readPrivateText2(path5);
64739
- const identity4 = await stat20(path5);
65379
+ const identity4 = await stat21(path5);
64740
65380
  if (current === raw && identity4.dev === info.dev && identity4.ino === info.ino && identity4.mtimeMs === info.mtimeMs && identity4.size === info.size)
64741
65381
  await unlink16(path5).catch(() => {
64742
65382
  });
@@ -64775,7 +65415,7 @@ async function removeCorruptPortFile(portFile, log19) {
64775
65415
  }
64776
65416
  async function writePortFile(dir, entry, options = {}) {
64777
65417
  const writeOnce = async () => {
64778
- const target = join43(dir, `port-${entry.pid}.json`);
65418
+ const target = join42(dir, `port-${entry.pid}.json`);
64779
65419
  if (windowsPrivateFiles2) {
64780
65420
  await ensurePrivateDirectory2(dir, options.secureDir ?? false);
64781
65421
  await options.beforeWrite?.();
@@ -64819,7 +65459,7 @@ async function writePortFile(dir, entry, options = {}) {
64819
65459
  } catch (error) {
64820
65460
  if (error.code !== "ENOENT" || attempt === 5)
64821
65461
  throw error;
64822
- await new Promise((resolve34) => setTimeout(resolve34, 25));
65462
+ await new Promise((resolve35) => setTimeout(resolve35, 25));
64823
65463
  }
64824
65464
  }
64825
65465
  }
@@ -64833,15 +65473,15 @@ async function sweepRpcState(root, activeDir, isManagedDir, log19, options = {})
64833
65473
  return;
64834
65474
  throw error;
64835
65475
  }
64836
- const active2 = resolve31(activeDir);
65476
+ const active2 = resolve32(activeDir);
64837
65477
  for (const projectDir of projectDirs) {
64838
65478
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
64839
65479
  continue;
64840
65480
  }
64841
- const dir = join43(root, projectDir.name);
65481
+ const dir = join42(root, projectDir.name);
64842
65482
  if (!await sweepRpcDirectory(dir, log19, options, cutoff))
64843
65483
  continue;
64844
- if (resolve31(dir) !== active2)
65484
+ if (resolve32(dir) !== active2)
64845
65485
  await rmdir3(dir).catch(() => {
64846
65486
  });
64847
65487
  }
@@ -64858,8 +65498,8 @@ async function sweepRpcDirectory(dir, log19, options = {}, cutoff = staleBefore(
64858
65498
  for (const name of names) {
64859
65499
  if (!name.startsWith("port-") || !name.endsWith(".json"))
64860
65500
  continue;
64861
- const portFile = join43(dir, name);
64862
- const info = await stat20(portFile).catch(() => void 0);
65501
+ const portFile = join42(dir, name);
65502
+ const info = await stat21(portFile).catch(() => void 0);
64863
65503
  let raw;
64864
65504
  try {
64865
65505
  raw = await readPrivateText2(portFile);
@@ -64899,11 +65539,11 @@ init_private_files2();
64899
65539
  import { randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
64900
65540
  import { unlink as unlink17 } from "node:fs/promises";
64901
65541
  import { createServer as createServer3 } from "node:http";
64902
- import { join as join44 } from "node:path";
65542
+ import { join as join43 } from "node:path";
64903
65543
 
64904
65544
  // src/common-auth-embedded/rpc/startup-sweep.js
64905
65545
  import { lstat as lstat11 } from "node:fs/promises";
64906
- import { basename as basename15, dirname as dirname32, resolve as resolve32 } from "node:path";
65546
+ import { basename as basename15, dirname as dirname31, resolve as resolve33 } from "node:path";
64907
65547
  var globals = globalThis;
64908
65548
  var key = /* @__PURE__ */ Symbol.for("common-auth.rpc.startup-sweep");
64909
65549
  globals[key] ??= {};
@@ -64912,8 +65552,8 @@ var now = Date.now;
64912
65552
  async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log19) {
64913
65553
  const time = now();
64914
65554
  if (state.lastSweepAt !== void 0 && time - state.lastSweepAt < 6e4) {
64915
- const active2 = resolve32(activeDir);
64916
- if (dirname32(active2) === resolve32(root) && isManagedDir(basename15(active2)) && (await lstat11(active2).catch((error) => {
65555
+ const active2 = resolve33(activeDir);
65556
+ if (dirname31(active2) === resolve33(root) && isManagedDir(basename15(active2)) && (await lstat11(active2).catch((error) => {
64917
65557
  if (error.code !== "ENOENT")
64918
65558
  throw error;
64919
65559
  return void 0;
@@ -64945,7 +65585,7 @@ var BodyTooLargeError = class extends Error {
64945
65585
  }
64946
65586
  };
64947
65587
  function readBody(req) {
64948
- return new Promise((resolve34, reject) => {
65588
+ return new Promise((resolve35, reject) => {
64949
65589
  const tooLarge = (declaredOversize = false) => {
64950
65590
  req.removeAllListeners("data");
64951
65591
  req.on("data", () => {
@@ -64968,7 +65608,7 @@ function readBody(req) {
64968
65608
  }
64969
65609
  chunks.push(chunk);
64970
65610
  });
64971
- req.on("end", () => resolve34(Buffer.concat(chunks).toString("utf8")));
65611
+ req.on("end", () => resolve35(Buffer.concat(chunks).toString("utf8")));
64972
65612
  req.on("error", reject);
64973
65613
  });
64974
65614
  }
@@ -65147,12 +65787,12 @@ async function startRpcServer(options) {
65147
65787
  json(500, { error: "internal error" });
65148
65788
  }
65149
65789
  }
65150
- const port = await new Promise((resolve34, reject) => {
65790
+ const port = await new Promise((resolve35, reject) => {
65151
65791
  server.on("error", reject);
65152
65792
  server.listen(0, "127.0.0.1", () => {
65153
65793
  const addr = server.address();
65154
65794
  if (addr && typeof addr === "object")
65155
- resolve34(addr.port);
65795
+ resolve35(addr.port);
65156
65796
  else
65157
65797
  reject(new Error("no port"));
65158
65798
  });
@@ -65175,20 +65815,20 @@ async function startRpcServer(options) {
65175
65815
  rpcPort: port
65176
65816
  });
65177
65817
  } catch (error) {
65178
- await new Promise((resolve34) => server.close(() => resolve34()));
65818
+ await new Promise((resolve35) => server.close(() => resolve35()));
65179
65819
  throw error;
65180
65820
  }
65181
65821
  return {
65182
65822
  port,
65183
65823
  token,
65184
65824
  async stop() {
65185
- await new Promise((resolve34) => {
65825
+ await new Promise((resolve35) => {
65186
65826
  server.closeAllConnections?.();
65187
- server.close(() => resolve34());
65827
+ server.close(() => resolve35());
65188
65828
  for (const socket of connections)
65189
65829
  socket.destroy();
65190
65830
  });
65191
- const portFile = join44(options.dir, `port-${process.pid}.json`);
65831
+ const portFile = join43(options.dir, `port-${process.pid}.json`);
65192
65832
  const current = await readPrivateText2(portFile).then((raw) => JSON.parse(raw)).catch((error) => {
65193
65833
  if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
65194
65834
  throw error;
@@ -65509,9 +66149,9 @@ import { stdin as input, stdout as output } from "node:process";
65509
66149
  import { createInterface as createInterface2 } from "node:readline/promises";
65510
66150
 
65511
66151
  // src/plugin/config/updater.ts
65512
- import { existsSync as existsSync15, mkdirSync as mkdirSync8, readFileSync as readFileSync14, writeFileSync as writeFileSync8 } from "node:fs";
66152
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, readFileSync as readFileSync14, writeFileSync as writeFileSync7 } from "node:fs";
65513
66153
  import { homedir as homedir15 } from "node:os";
65514
- import { dirname as dirname33, join as join45 } from "node:path";
66154
+ import { dirname as dirname32, join as join44 } from "node:path";
65515
66155
 
65516
66156
  // src/plugin/model-registry.ts
65517
66157
  init_dist();
@@ -65544,13 +66184,13 @@ function stripJsonCommentsAndTrailingCommas(json) {
65544
66184
  ).replace(/,(\s*[}\]])/g, "$1");
65545
66185
  }
65546
66186
  function getOpencodeConfigDir() {
65547
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join45(homedir15(), ".config");
65548
- return join45(xdgConfig2, "opencode");
66187
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join44(homedir15(), ".config");
66188
+ return join44(xdgConfig2, "opencode");
65549
66189
  }
65550
66190
  function getOpencodeConfigPath() {
65551
66191
  const configDir = getOpencodeConfigDir();
65552
- const jsoncPath = join45(configDir, OPENCODE_JSONC_FILENAME);
65553
- const jsonPath = join45(configDir, OPENCODE_JSON_FILENAME);
66192
+ const jsoncPath = join44(configDir, OPENCODE_JSONC_FILENAME);
66193
+ const jsonPath = join44(configDir, OPENCODE_JSON_FILENAME);
65554
66194
  if (existsSync15(jsoncPath)) {
65555
66195
  return jsoncPath;
65556
66196
  }
@@ -65595,11 +66235,11 @@ async function updateOpencodeConfig(options = {}) {
65595
66235
  }
65596
66236
  config.provider.google.models = getOpencode1ModelDefinitions();
65597
66237
  config.provider.google.whitelist = getAntigravityOpencodeModelIds();
65598
- const configDir = dirname33(configPath);
66238
+ const configDir = dirname32(configPath);
65599
66239
  if (!existsSync15(configDir)) {
65600
- mkdirSync8(configDir, { recursive: true });
66240
+ mkdirSync7(configDir, { recursive: true });
65601
66241
  }
65602
- writeFileSync8(configPath, JSON.stringify(config, null, 2), "utf-8");
66242
+ writeFileSync7(configPath, JSON.stringify(config, null, 2), "utf-8");
65603
66243
  return {
65604
66244
  success: true,
65605
66245
  configPath
@@ -65809,7 +66449,7 @@ async function select3(items, options) {
65809
66449
  }
65810
66450
  renderedLines = linesWritten;
65811
66451
  };
65812
- return new Promise((resolve34) => {
66452
+ return new Promise((resolve35) => {
65813
66453
  const wasRaw = stdin.isRaw ?? false;
65814
66454
  const cleanup2 = () => {
65815
66455
  if (isCleanedUp) return;
@@ -65830,11 +66470,11 @@ async function select3(items, options) {
65830
66470
  };
65831
66471
  const onSignal = () => {
65832
66472
  cleanup2();
65833
- resolve34(null);
66473
+ resolve35(null);
65834
66474
  };
65835
66475
  const finishWithValue = (value) => {
65836
66476
  cleanup2();
65837
- resolve34(value);
66477
+ resolve35(value);
65838
66478
  };
65839
66479
  const findNextSelectable = (from, direction) => {
65840
66480
  if (items.length === 0) return from;
@@ -65880,7 +66520,7 @@ async function select3(items, options) {
65880
66520
  stdin.setRawMode(true);
65881
66521
  } catch {
65882
66522
  cleanup2();
65883
- resolve34(null);
66523
+ resolve35(null);
65884
66524
  return;
65885
66525
  }
65886
66526
  stdin.resume();
@@ -68104,16 +68744,21 @@ function createAuthLoader({
68104
68744
  };
68105
68745
  let storeOpening = null;
68106
68746
  const openStore = () => {
68107
- storeOpening ??= deps.openAccountStore().then((opening) => {
68108
- if (opening.status === "ready") {
68109
- lifecycle.register({
68110
- async dispose() {
68111
- await opening.repository.dispose();
68112
- }
68113
- });
68114
- }
68115
- return opening;
68116
- });
68747
+ if (!storeOpening) {
68748
+ const attempt = deps.openAccountStore().then((opening) => {
68749
+ if (opening.status === "ready") {
68750
+ lifecycle.register({
68751
+ async dispose() {
68752
+ await opening.repository.dispose();
68753
+ }
68754
+ });
68755
+ } else if (opening.status === "refused" && opening.admission.status === "busy" && opening.admission.retryable && storeOpening === attempt) {
68756
+ storeOpening = null;
68757
+ }
68758
+ return opening;
68759
+ });
68760
+ storeOpening = attempt;
68761
+ }
68117
68762
  return storeOpening;
68118
68763
  };
68119
68764
  const initializeFreshStore = async () => {
@@ -68892,15 +69537,15 @@ init_debug();
68892
69537
  // src/plugin/dependencies.ts
68893
69538
  init_dist();
68894
69539
  import { homedir as homedir16 } from "node:os";
68895
- import { join as join46 } from "node:path";
69540
+ import { join as join45 } from "node:path";
68896
69541
  function defaultFilesystemRoots() {
68897
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join46(homedir16(), ".config");
68898
- const xdgState2 = process.env.XDG_STATE_HOME ?? join46(homedir16(), ".local", "state");
69542
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join45(homedir16(), ".config");
69543
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join45(homedir16(), ".local", "state");
68899
69544
  return {
68900
69545
  projectRoot: process.cwd(),
68901
- userConfigRoot: join46(xdgConfig2, "opencode"),
68902
- sidebarStateRoot: join46(xdgState2, "cortexkit", "antigravity-auth"),
68903
- rpcRoot: join46(xdgState2, "cortexkit", "antigravity-auth", "rpc")
69546
+ userConfigRoot: join45(xdgConfig2, "opencode"),
69547
+ sidebarStateRoot: join45(xdgState2, "cortexkit", "antigravity-auth"),
69548
+ rpcRoot: join45(xdgState2, "cortexkit", "antigravity-auth", "rpc")
68904
69549
  };
68905
69550
  }
68906
69551
  function resolvePluginDependencies(overrides = {}) {
@@ -68929,10 +69574,10 @@ function resolvePluginDependencies(overrides = {}) {
68929
69574
  }
68930
69575
  async function defaultSleep(ms, signal) {
68931
69576
  if (ms <= 0) return;
68932
- await new Promise((resolve34, reject) => {
69577
+ await new Promise((resolve35, reject) => {
68933
69578
  const timer = setTimeout(() => {
68934
69579
  signal?.removeEventListener("abort", onAbort);
68935
- resolve34();
69580
+ resolve35();
68936
69581
  }, ms);
68937
69582
  timer.unref?.();
68938
69583
  const onAbort = () => {
@@ -69664,8 +70309,8 @@ function createPluginLifecycle(options) {
69664
70309
  };
69665
70310
  let failDisposal = () => {
69666
70311
  };
69667
- disposal = new Promise((resolve34, reject) => {
69668
- finishDisposal = resolve34;
70312
+ disposal = new Promise((resolve35, reject) => {
70313
+ finishDisposal = resolve35;
69669
70314
  failDisposal = reject;
69670
70315
  });
69671
70316
  void (async () => {
@@ -69771,7 +70416,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
69771
70416
  // Diagnostics. Before the move they load from and write to the
69772
70417
  // project or user antigravity.json through the operator writer.
69773
70418
  operator: () => createOperatorSettingsController({
69774
- projectConfigPath: join47(directory, ".opencode", "antigravity.json"),
70419
+ projectConfigPath: join46(directory, ".opencode", "antigravity.json"),
69775
70420
  // getUserConfigPath() already returns the full file path including
69776
70421
  // 'antigravity.json' — do NOT join again or the path double-nests
69777
70422
  // into <dir>/antigravity.json/antigravity.json.
@@ -69833,7 +70478,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
69833
70478
  await drainSidebarWrites();
69834
70479
  }
69835
70480
  });
69836
- const accountFile = resolve33(accountFileForVault());
70481
+ const accountFile = resolve34(accountFileForVault());
69837
70482
  const vaultFolder = await prepareVaultFolder({ accountFile });
69838
70483
  const unavailableMessage = vaultFolder.refusal?.message ?? VAULT_ACCOUNT_REMEDY;
69839
70484
  let vaultQuotaPoller;
@@ -69866,7 +70511,12 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
69866
70511
  source,
69867
70512
  pool: createOpenCodeVaultAccountPool({
69868
70513
  source,
69869
- durable: { source, readState: () => vaultCustody.readState() }
70514
+ durable: {
70515
+ source,
70516
+ readState: () => vaultCustody.readState(),
70517
+ stateFile: vaultCustody.paths.stateFile,
70518
+ onReadFailure: () => logger2.debug("vault-state-read-skipped")
70519
+ }
69870
70520
  })
69871
70521
  };
69872
70522
  return vaultPool;