@cortexkit/opencode-antigravity-auth 3.1.10 → 3.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/dist/cli.js +357 -58
  2. package/dist/cli.js.map +3 -3
  3. package/dist/cli.meta.json +37 -32
  4. package/dist/index.js +986 -426
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +86 -63
  7. package/dist/server.js +1131 -551
  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/quota.d.ts +10 -2
  66. package/dist/src/plugin/quota.d.ts.map +1 -1
  67. package/dist/src/plugin/quota.js +38 -10
  68. package/dist/src/plugin/quota.js.map +1 -1
  69. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  70. package/dist/src/plugin/request-helpers.js +51 -19
  71. package/dist/src/plugin/request-helpers.js.map +1 -1
  72. package/dist/src/plugin/request.d.ts +12 -1
  73. package/dist/src/plugin/request.d.ts.map +1 -1
  74. package/dist/src/plugin/request.js +27 -42
  75. package/dist/src/plugin/request.js.map +1 -1
  76. package/dist/src/plugin/shared/request-services.d.ts +4 -1
  77. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  78. package/dist/src/plugin/shared/request-services.js +142 -24
  79. package/dist/src/plugin/shared/request-services.js.map +1 -1
  80. package/dist/src/plugin/shared/runtime.d.ts +3 -4
  81. package/dist/src/plugin/shared/runtime.d.ts.map +1 -1
  82. package/dist/src/plugin/shared/runtime.js +2 -2
  83. package/dist/src/plugin/shared/runtime.js.map +1 -1
  84. package/dist/src/plugin/shared/vault-request-credentials.d.ts +13 -7
  85. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  86. package/dist/src/plugin/shared/vault-request-credentials.js +24 -18
  87. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  88. package/dist/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  89. package/dist/src/setup.d.ts +3 -0
  90. package/dist/src/setup.d.ts.map +1 -1
  91. package/dist/src/setup.js +18 -6
  92. package/dist/src/setup.js.map +1 -1
  93. package/dist/src/sidebar-state.d.ts +20 -7
  94. package/dist/src/sidebar-state.d.ts.map +1 -1
  95. package/dist/src/sidebar-state.js +57 -8
  96. package/dist/src/sidebar-state.js.map +1 -1
  97. package/dist/src/tui.d.ts.map +1 -1
  98. package/dist/src/tui.js +43 -23
  99. package/dist/src/tui.js.map +1 -1
  100. package/dist/tui-build-map.json +9 -9
  101. package/dist/tui-ga-build-map.json +5 -5
  102. package/dist/types/src/cli.d.ts +3 -1
  103. package/dist/types/src/cli.d.ts.map +1 -1
  104. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  105. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +39 -1
  106. package/dist/types/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  107. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  108. package/dist/types/src/ga/rpc/protocol.d.ts +11 -5
  109. package/dist/types/src/ga/rpc/protocol.d.ts.map +1 -1
  110. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  111. package/dist/types/src/plugin/account-access.d.ts +1 -0
  112. package/dist/types/src/plugin/account-access.d.ts.map +1 -1
  113. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  114. package/dist/types/src/plugin/background-quota-refresh.d.ts +11 -24
  115. package/dist/types/src/plugin/background-quota-refresh.d.ts.map +1 -1
  116. package/dist/types/src/plugin/background-vault-quota-refresh.d.ts.map +1 -1
  117. package/dist/types/src/plugin/cache/signature-cache.d.ts +3 -0
  118. package/dist/types/src/plugin/cache/signature-cache.d.ts.map +1 -1
  119. package/dist/types/src/plugin/cache.d.ts.map +1 -1
  120. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts +23 -0
  121. package/dist/types/src/plugin/core/streaming/displayed-thinking.d.ts.map +1 -0
  122. package/dist/types/src/plugin/fetch/warmup.d.ts +9 -2
  123. package/dist/types/src/plugin/fetch/warmup.d.ts.map +1 -1
  124. package/dist/types/src/plugin/quota.d.ts +10 -2
  125. package/dist/types/src/plugin/quota.d.ts.map +1 -1
  126. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  127. package/dist/types/src/plugin/request.d.ts +12 -1
  128. package/dist/types/src/plugin/request.d.ts.map +1 -1
  129. package/dist/types/src/plugin/shared/request-services.d.ts +4 -1
  130. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  131. package/dist/types/src/plugin/shared/runtime.d.ts +3 -4
  132. package/dist/types/src/plugin/shared/runtime.d.ts.map +1 -1
  133. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +13 -7
  134. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  135. package/dist/types/src/plugin/vault-sidebar-projection.d.ts.map +1 -1
  136. package/dist/types/src/setup.d.ts +3 -0
  137. package/dist/types/src/setup.d.ts.map +1 -1
  138. package/dist/types/src/sidebar-state.d.ts +20 -7
  139. package/dist/types/src/sidebar-state.d.ts.map +1 -1
  140. package/package.json +3 -3
  141. package/src/common-auth-embedded/claustrum/consumer.d.ts +20 -1
  142. package/src/common-auth-embedded/claustrum/consumer.js +32 -0
  143. package/src/common-auth-embedded/claustrum/custody.d.ts +39 -1
  144. package/src/common-auth-embedded/claustrum/custody.js +145 -8
  145. package/src/common-auth-embedded/claustrum/host.js +8 -0
  146. package/src/common-auth-embedded/claustrum/hub.d.ts +3 -2
  147. package/src/common-auth-embedded/claustrum/hub.js +10 -0
  148. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  149. package/src/common-auth-embedded/routing-accessor/index.js +5 -3
  150. package/src/common-auth-embedded/source-output.json +35 -35
  151. package/src/sidebar-state.ts +77 -8
  152. package/src/tui-compiled/sidebar-state.js +40 -1
  153. package/src/tui-compiled/tui.js +49 -24
  154. package/src/tui-ga-compiled/host-ga.js +11 -5
  155. package/src/tui-ga-raw/host-ga.tsx +17 -6
  156. package/src/tui-raw/sidebar-state.js +40 -1
  157. package/src/tui-raw/tui.tsx +40 -24
  158. package/src/tui.tsx +40 -24
package/dist/index.js CHANGED
@@ -385,6 +385,11 @@ function mergeQuotaState(stored, observation) {
385
385
  if (stored === void 0)
386
386
  return incoming;
387
387
  const prior = encodeQuotaState(decodeQuotaState(stored));
388
+ const previousAt = prior.cachedQuotaUpdatedAt;
389
+ const observedAt = incoming.cachedQuotaUpdatedAt;
390
+ if (typeof previousAt === "number" && typeof observedAt === "number" && observedAt < previousAt) {
391
+ throw new StaleQuotaObservationError();
392
+ }
388
393
  return encodeQuotaState(decodeQuotaState({ ...prior, ...incoming }));
389
394
  }
390
395
  function decodeRoutingSettings(raw) {
@@ -420,7 +425,7 @@ function createProviderStateCodec(policy) {
420
425
  }
421
426
  };
422
427
  }
423
- var AccountCodecError, MAX_JSON_DEPTH, IDENTIFIER, jsonValue, string, nonEmptyString, finiteNumber, count, credentialEpoch, boolean, rowId, required, optional, EXTENSIONS, CREDENTIAL_REFUSAL, CREDENTIAL_KEYS, POOL_FIELD_REFUSAL, QUOTA_FIELD_REFUSAL, LEGACY_FIELD_REFUSAL, METADATA_FIELD_REFUSAL, clientMetadataCodec, fingerprintCodec, fingerprintVersionCodec, dailyRequestCountsCodec, metadataShape, quotaShape, metadataForbidden, quotaForbidden, metadataCodec, providerStateCodec, quotaCodec, rowRefCodec, routingCodec, QUOTA_CODEC;
428
+ var AccountCodecError, MAX_JSON_DEPTH, IDENTIFIER, jsonValue, string, nonEmptyString, finiteNumber, count, credentialEpoch, boolean, rowId, required, optional, EXTENSIONS, CREDENTIAL_REFUSAL, CREDENTIAL_KEYS, POOL_FIELD_REFUSAL, QUOTA_FIELD_REFUSAL, LEGACY_FIELD_REFUSAL, METADATA_FIELD_REFUSAL, clientMetadataCodec, fingerprintCodec, fingerprintVersionCodec, dailyRequestCountsCodec, metadataShape, quotaShape, metadataForbidden, quotaForbidden, metadataCodec, providerStateCodec, quotaCodec, rowRefCodec, routingCodec, StaleQuotaObservationError, QUOTA_CODEC;
424
429
  var init_account_repository_codecs = __esm({
425
430
  "../core/dist/account-repository-codecs.js"() {
426
431
  "use strict";
@@ -590,6 +595,11 @@ var init_account_repository_codecs = __esm({
590
595
  gemini: optional(nullable(rowRefCodec))
591
596
  })))
592
597
  }, { forbidden: CREDENTIAL_KEYS });
598
+ StaleQuotaObservationError = class extends Error {
599
+ constructor() {
600
+ super("A newer quota observation is already stored");
601
+ }
602
+ };
593
603
  QUOTA_CODEC = {
594
604
  validate: isValidQuotaState,
595
605
  merge: mergeQuotaState
@@ -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((resolve33) => setTimeout(resolve33, ms));
8325
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => {
8424
- lostResolve = resolve33;
8441
+ let lostPromise = new Promise((resolve34) => {
8442
+ lostResolve = resolve34;
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 resolve33 = lostResolve;
8452
+ const resolve34 = lostResolve;
8435
8453
  lostResolve = null;
8436
- resolve33?.();
8454
+ resolve34?.();
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((resolve33) => setTimeout(resolve33, ms));
9077
+ const sleep5 = (ms) => new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => setTimeout(resolve33, ms));
9125
+ DEFAULT_SLEEP = (ms) => new Promise((resolve34) => setTimeout(resolve34, 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((resolve33, reject) => {
10362
- this.savePromiseResolvers.push({ resolve: resolve33, reject });
10379
+ return new Promise((resolve34, reject) => {
10380
+ this.savePromiseResolvers.push({ resolve: resolve34, 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: resolve33 } of resolvers)
10406
- resolve33();
10423
+ for (const { resolve: resolve34 } of resolvers)
10424
+ resolve34();
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: resolve33 } of resolvers) {
10421
- resolve33();
10438
+ for (const { resolve: resolve34 } of resolvers) {
10439
+ resolve34();
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: resolve33 } of resolvers) {
10429
- resolve33();
10446
+ for (const { resolve: resolve34 } of resolvers) {
10447
+ resolve34();
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((resolve33, reject) => {
10992
+ return new Promise((resolve34, 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(() => resolve33({ head, leftover }));
11015
+ cleanup2(() => resolve34({ 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((resolve33, reject) => {
11029
+ await new Promise((resolve34, 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
- resolve33();
11038
+ resolve34();
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((resolve33, reject) => {
11063
+ return await new Promise((resolve34, 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
- resolve33(tlsSocket);
11079
+ resolve34(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((resolve33, reject) => {
11088
+ return await new Promise((resolve34, 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
- resolve33(socket);
11105
+ resolve34(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((resolve33) => {
13859
- resolveLoss = resolve33;
13967
+ const lostPromise = new Promise((resolve34) => {
13968
+ resolveLoss = resolve34;
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((resolve33) => setTimeout(resolve33, Math.floor(Math.random() * 4)));
14132
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
14225
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
14728
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => setTimeout(resolve33, Math.min(25, Math.ceil(remaining))));
14813
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => setTimeout(resolve33, Math.min(options.retryMs + jitter, remaining)));
14903
+ await new Promise((resolve34) => setTimeout(resolve34, 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((resolve33) => {
17816
+ await new Promise((resolve34) => {
17708
17817
  const done = () => {
17709
17818
  clearTimeout(timer);
17710
17819
  this.wake.delete(done);
17711
- resolve33();
17820
+ resolve34();
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((resolve33) => {
20951
+ return new Promise((resolve34) => {
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
- resolve33(value);
20971
+ resolve34(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
- resolve33(null);
21011
+ resolve34(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((resolve33) => {
23037
+ new Promise((resolve34) => {
22921
23038
  timer = setTimeout(() => {
22922
23039
  expired = true;
22923
- resolve33();
23040
+ resolve34();
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((resolve33, reject) => {
23884
+ return new Promise((resolve34, 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
- resolve33();
23892
+ resolve34();
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((resolve33, reject) => {
25214
+ return new Promise((resolve34, 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
- resolve33(value);
25229
+ resolve34(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((resolve33, reject) => {
26065
+ return new Promise((resolve34, 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
- resolve33(value);
26070
+ resolve34(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);
@@ -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((resolve33) => {
28083
- setTimeout(resolve33, ms);
28362
+ return new Promise((resolve34) => {
28363
+ setTimeout(resolve34, 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((resolve33, reject) => {
30779
+ return new Promise((resolve34, 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(resolve33, reject).finally(() => signal.removeEventListener("abort", abort));
30784
+ pending.then(resolve34, 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({
@@ -32933,13 +33219,13 @@ function closeDebugStream(state2) {
32933
33219
  state2.logWriter = () => {
32934
33220
  };
32935
33221
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
32936
- return new Promise((resolve33) => {
32937
- current.once("close", () => resolve33());
32938
- current.once("error", () => resolve33());
33222
+ return new Promise((resolve34) => {
33223
+ current.once("close", () => resolve34());
33224
+ current.once("error", () => resolve34());
32939
33225
  try {
32940
33226
  current.end();
32941
33227
  } catch {
32942
- resolve33();
33228
+ resolve34();
32943
33229
  }
32944
33230
  });
32945
33231
  }
@@ -33204,13 +33490,13 @@ function closeDebugLog() {
33204
33490
  if (!state2 || !current) return Promise.resolve();
33205
33491
  state2.logStream = null;
33206
33492
  if (state2.logFilePath) liveLogFilePaths.delete(state2.logFilePath);
33207
- return new Promise((resolve33) => {
33208
- current.once("close", () => resolve33());
33209
- current.once("error", () => resolve33());
33493
+ return new Promise((resolve34) => {
33494
+ current.once("close", () => resolve34());
33495
+ current.once("error", () => resolve34());
33210
33496
  try {
33211
33497
  current.end();
33212
33498
  } catch {
33213
- resolve33();
33499
+ resolve34();
33214
33500
  }
33215
33501
  });
33216
33502
  }
@@ -33478,10 +33764,7 @@ function createVaultRequestCredentials(source, onAdmitted) {
33478
33764
  const admission = await source.admit(account.route, signal);
33479
33765
  if (onAdmitted)
33480
33766
  onAdmitted.admitted(account, onAdmitted.source.attribution(admission));
33481
- const grant = new VaultSendGrant(
33482
- admission,
33483
- (status) => source.reportServedStatus(admission, status)
33484
- );
33767
+ const grant = new VaultSendGrant(admission, source);
33485
33768
  issued.set(grant, admission);
33486
33769
  return grant;
33487
33770
  }
@@ -33900,12 +34183,12 @@ function createVaultAccountPool(options) {
33900
34183
  try {
33901
34184
  return await Promise.race([
33902
34185
  read.then(() => true),
33903
- new Promise((resolve33, reject) => {
34186
+ new Promise((resolve34, reject) => {
33904
34187
  const abort = () => reject(signal?.reason);
33905
34188
  signal?.addEventListener("abort", abort, { once: true });
33906
34189
  detachAbort = () => signal?.removeEventListener("abort", abort);
33907
34190
  if (remaining !== void 0)
33908
- cancelTimer2 = schedule2(() => resolve33(false), remaining);
34191
+ cancelTimer2 = schedule2(() => resolve34(false), remaining);
33909
34192
  if (signal?.aborted) abort();
33910
34193
  })
33911
34194
  ]);
@@ -33994,7 +34277,7 @@ function vaultQuotaState(quota, at) {
33994
34277
  }
33995
34278
  async function checkVaultQuota(input2) {
33996
34279
  const state2 = input2.pool.state;
33997
- const rows = [...input2.pool.selector.rows];
34280
+ const routes = input2.routes ?? input2.pool.selector.rows.map((row) => row.route);
33998
34281
  const now2 = input2.now ?? (() => Date.now());
33999
34282
  const reportError = (error) => {
34000
34283
  try {
@@ -34005,11 +34288,11 @@ async function checkVaultQuota(input2) {
34005
34288
  let checked = 0;
34006
34289
  if (state2 === void 0) input2.onOutcome?.("state-invalid");
34007
34290
  const readings = [];
34008
- for (const row of rows) {
34291
+ for (const route of routes) {
34009
34292
  if (input2.signal.aborted || state2 === void 0) break;
34010
34293
  try {
34011
34294
  input2.onStage?.("fetch");
34012
- const answer = await input2.fetchReading(row.route, input2.signal);
34295
+ const answer = await input2.fetchReading(route, input2.signal);
34013
34296
  input2.signal.throwIfAborted();
34014
34297
  if (answer === void 0) {
34015
34298
  input2.onOutcome?.("fetch-failed");
@@ -34033,7 +34316,7 @@ async function checkVaultQuota(input2) {
34033
34316
  }
34034
34317
  }
34035
34318
  if (state2 === void 0 || readings.length === 0 || input2.signal.aborted)
34036
- return { checked, notChecked: rows.length - checked };
34319
+ return { checked, notChecked: routes.length - checked };
34037
34320
  let results;
34038
34321
  try {
34039
34322
  input2.onStage?.("commit");
@@ -34041,8 +34324,11 @@ async function checkVaultQuota(input2) {
34041
34324
  results = await state2.recordQuotas(readings, input2.signal);
34042
34325
  } catch (error) {
34043
34326
  for (const _ of readings) reportError(error);
34044
- return { checked, notChecked: rows.length - checked };
34327
+ return { checked, notChecked: routes.length - checked };
34045
34328
  }
34329
+ const liveByRoute = new Map(
34330
+ input2.pool.selector.rows.map((row) => [row.route.routeId, row])
34331
+ );
34046
34332
  for (const [at, { attribution, quota: reading }] of readings.entries()) {
34047
34333
  const result = results[at];
34048
34334
  if (result === void 0 || result.status === "refused") {
@@ -34060,17 +34346,15 @@ async function checkVaultQuota(input2) {
34060
34346
  }
34061
34347
  checked += 1;
34062
34348
  input2.onOutcome?.("recorded");
34063
- const live = input2.pool.selector.rows.find(
34064
- (candidate) => candidate.route.routeId === attribution.routeId && candidate.route.credentialId === attribution.credentialId && candidate.route.accountIdentity === attribution.accountIdentity
34065
- );
34066
- if (live !== void 0) {
34349
+ const live = liveByRoute.get(attribution.routeId);
34350
+ if (live?.route.credentialId === attribution.credentialId && live.route.accountIdentity === attribution.accountIdentity) {
34067
34351
  const cached = cachedQuotaOf(reading);
34068
34352
  if (cached !== void 0) live.cachedQuota = cached;
34069
34353
  live.cachedQuotaUpdatedAt = reading.cachedQuotaUpdatedAt ?? void 0;
34070
34354
  input2.pool.selector.reconcileQuotaReading(live);
34071
34355
  }
34072
34356
  }
34073
- return { checked, notChecked: rows.length - checked };
34357
+ return { checked, notChecked: routes.length - checked };
34074
34358
  }
34075
34359
  var VaultSendGrant, VAULT_REFRESH_STALL_MS, VAULT_DISPLAY_ROSTER_WAIT_MS;
34076
34360
  var init_vault_request_credentials = __esm({
@@ -34084,7 +34368,9 @@ var init_vault_request_credentials = __esm({
34084
34368
  recordVersion;
34085
34369
  projectId;
34086
34370
  report401;
34087
- constructor(admission, report) {
34371
+ reportCondition;
34372
+ clearCondition;
34373
+ constructor(admission, source) {
34088
34374
  Object.defineProperty(this, "accessToken", {
34089
34375
  value: admission.accessToken,
34090
34376
  enumerable: false
@@ -34094,7 +34380,9 @@ var init_vault_request_credentials = __esm({
34094
34380
  this.recordVersion = admission.recordVersion;
34095
34381
  this.projectId = admission.projectId;
34096
34382
  this.fromKeptReceipt = admission.fromKeptReceipt;
34097
- this.report401 = report;
34383
+ this.report401 = (status) => source.reportServedStatus(admission, status);
34384
+ this.reportCondition = source.reportCondition?.bind(source, admission);
34385
+ this.clearCondition = source.clearCondition?.bind(source, admission);
34098
34386
  }
34099
34387
  };
34100
34388
  VAULT_REFRESH_STALL_MS = 3e4;
@@ -34431,11 +34719,11 @@ function createOpenCodeVaultCustody(options) {
34431
34719
  ].join("\n");
34432
34720
  const waitForApproval = async () => {
34433
34721
  while (!closed2) {
34434
- await new Promise((resolve33) => {
34722
+ await new Promise((resolve34) => {
34435
34723
  const done = () => {
34436
34724
  clearTimeout(timer);
34437
34725
  cancelWait = void 0;
34438
- resolve33();
34726
+ resolve34();
34439
34727
  };
34440
34728
  const timer = setTimeout(done, 2e3);
34441
34729
  timer.unref?.();
@@ -36231,7 +36519,7 @@ var init_runtime_layout = __esm({
36231
36519
  init_dist();
36232
36520
  init_runtime_layout();
36233
36521
  import { createHash as createHash24, randomUUID as randomUUID25 } from "node:crypto";
36234
- import { join as join46, resolve as resolve32 } from "node:path";
36522
+ import { join as join45, resolve as resolve33 } from "node:path";
36235
36523
 
36236
36524
  // src/cli.ts
36237
36525
  init_dist();
@@ -36475,9 +36763,9 @@ init_dist();
36475
36763
  init_dist();
36476
36764
 
36477
36765
  // src/sidebar-state.ts
36766
+ import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, statSync as statSync5 } from "node:fs";
36478
36767
  init_atomic_write();
36479
36768
  init_file_lock();
36480
- import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3 } from "node:fs";
36481
36769
  import { homedir as homedir6 } from "node:os";
36482
36770
  import { dirname as dirname19, join as join19 } from "node:path";
36483
36771
 
@@ -36548,6 +36836,9 @@ function readSidebarState(path5 = getSidebarStateFile()) {
36548
36836
  } catch {
36549
36837
  return { ...DEFAULT_SIDEBAR_STATE };
36550
36838
  }
36839
+ return parseSidebarState(raw);
36840
+ }
36841
+ function parseSidebarState(raw) {
36551
36842
  let parsed;
36552
36843
  try {
36553
36844
  parsed = JSON.parse(raw);
@@ -36888,7 +37179,7 @@ function drainSidebarWrites() {
36888
37179
  return sidebarWriteChain;
36889
37180
  }
36890
37181
  async function sleep3(ms) {
36891
- await new Promise((resolve33) => setTimeout(resolve33, ms));
37182
+ await new Promise((resolve34) => setTimeout(resolve34, ms));
36892
37183
  }
36893
37184
  async function acquireSidebarLockWithRetry(stateFile) {
36894
37185
  const start = Date.now();
@@ -37428,7 +37719,8 @@ function withSidebarPushAfterRefresh(manager, push) {
37428
37719
  refreshOptions
37429
37720
  );
37430
37721
  const lastAccount = accounts[accounts.length - 1];
37431
- if (shouldPush && lastAccount) await pushAfterRefresh(lastAccount);
37722
+ if (shouldPush && refreshOptions.publishSidebar !== false && lastAccount)
37723
+ await pushAfterRefresh(lastAccount);
37432
37724
  return results;
37433
37725
  })()
37434
37726
  );
@@ -37463,10 +37755,29 @@ async function checkAccountsQuotaStandalone(accounts, options) {
37463
37755
  }
37464
37756
  }));
37465
37757
  }
37466
- return checkAccountsQuotaWith(
37758
+ const refused2 = new AbortController();
37759
+ const admit2 = options.assertAdmission;
37760
+ const assertAdmission = admit2 && (async () => {
37761
+ refused2.signal.throwIfAborted();
37762
+ try {
37763
+ await admit2();
37764
+ } catch (error) {
37765
+ refused2.abort(error);
37766
+ throw error;
37767
+ }
37768
+ refused2.signal.throwIfAborted();
37769
+ });
37770
+ const results = await checkAccountsQuotaWith(
37467
37771
  accounts,
37468
- makeFetchAccountQuota(void 0, ANTIGRAVITY_PROVIDER_ID)
37772
+ makeFetchAccountQuota(
37773
+ void 0,
37774
+ ANTIGRAVITY_PROVIDER_ID,
37775
+ void 0,
37776
+ assertAdmission
37777
+ )
37469
37778
  );
37779
+ refused2.signal.throwIfAborted();
37780
+ return results;
37470
37781
  }
37471
37782
  async function pushSidebarQuotaSnapshot(getAccounts, backoffUntil = 0, getActiveIndexByFamily, options = {}) {
37472
37783
  const accounts = getAccounts();
@@ -37740,14 +38051,14 @@ var LocalQuotaGrantStaleError = class extends Error {
37740
38051
  name = "LocalQuotaGrantStaleError";
37741
38052
  };
37742
38053
  function untilQuotaAborted(pending, signal) {
37743
- return new Promise((resolve33, reject) => {
38054
+ return new Promise((resolve34, reject) => {
37744
38055
  const abort = () => reject(signal.reason);
37745
38056
  if (signal.aborted) abort();
37746
38057
  else signal.addEventListener("abort", abort, { once: true });
37747
38058
  void pending.then(
37748
38059
  (value) => {
37749
38060
  signal.removeEventListener("abort", abort);
37750
- resolve33(value);
38061
+ resolve34(value);
37751
38062
  },
37752
38063
  (error) => {
37753
38064
  signal.removeEventListener("abort", abort);
@@ -37845,7 +38156,7 @@ function createAuthorizedFetchAccountQuota(options) {
37845
38156
  }
37846
38157
  };
37847
38158
  }
37848
- function makeFetchAccountQuota(client, providerId, fetchVia) {
38159
+ function makeFetchAccountQuota(client, providerId, fetchVia, assertAdmission) {
37849
38160
  return async (account, signal, purpose = "required") => {
37850
38161
  const index = 0;
37851
38162
  const disabled = account.enabled === false;
@@ -37927,6 +38238,8 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37927
38238
  }
37928
38239
  try {
37929
38240
  if (accessTokenExpired(auth)) {
38241
+ if (assertAdmission) await assertAdmission();
38242
+ signal.throwIfAborted();
37930
38243
  const refreshed = await refreshAccessToken(
37931
38244
  auth,
37932
38245
  client,
@@ -37940,7 +38253,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37940
38253
  }
37941
38254
  auth = refreshed;
37942
38255
  }
37943
- const projectContext = await ensureProjectContext(auth);
38256
+ const projectContext = await ensureProjectContext(auth, assertAdmission);
37944
38257
  auth = projectContext.auth;
37945
38258
  const updatedAccount = applyAccountUpdates(
37946
38259
  account,
@@ -37955,11 +38268,20 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
37955
38268
  let fellBackToLegacy = false;
37956
38269
  const authParts = parseRefreshParts(auth.refresh);
37957
38270
  const managedProjectId = authParts.managedProjectId ?? account.managedProjectId;
38271
+ const guarded = assertAdmission ? async (url, init, extra) => {
38272
+ await assertAdmission();
38273
+ signal.throwIfAborted();
38274
+ return fetchWithActiveTimeout(
38275
+ url,
38276
+ { ...init, signal },
38277
+ { timeoutMs: extra.timeoutMs }
38278
+ );
38279
+ } : fetchVia;
37958
38280
  const payloads = await fetchQuotaPayloads({
37959
38281
  accessToken: auth.access ?? "",
37960
38282
  managedProjectId,
37961
38283
  projectId: projectContext.effectiveProjectId,
37962
- fetchVia,
38284
+ fetchVia: guarded,
37963
38285
  logger: log8
37964
38286
  });
37965
38287
  quotaResult = payloads.quota;
@@ -38204,12 +38526,13 @@ function createStoreQuotaService(options) {
38204
38526
  if (options.mayRun && !await options.mayRun())
38205
38527
  return { status: "discarded", result };
38206
38528
  const held2 = target.rowRef === void 0 ? void 0 : heldAccount(manager, target.rowRef);
38207
- if (held2 === void 0) return { status: "discarded", result };
38208
- manager.updateQuotaCache(
38529
+ if (held2 === void 0 || result.checkedAt === void 0 || !manager.updateQuotaCache(
38209
38530
  held2.index,
38210
38531
  result.quota.groups,
38211
- held2.parts.refreshToken
38212
- );
38532
+ held2.parts.refreshToken,
38533
+ result.checkedAt
38534
+ ))
38535
+ return { status: "discarded", result };
38213
38536
  return {
38214
38537
  status: "recorded",
38215
38538
  result,
@@ -38368,12 +38691,12 @@ async function startOAuthListener({
38368
38691
  let resolveCallback;
38369
38692
  let rejectCallback;
38370
38693
  let timeoutHandle;
38371
- const callbackPromise = new Promise((resolve33, reject) => {
38694
+ const callbackPromise = new Promise((resolve34, reject) => {
38372
38695
  resolveCallback = (url) => {
38373
38696
  if (settled) return;
38374
38697
  settled = true;
38375
38698
  if (timeoutHandle) clearTimeout(timeoutHandle);
38376
- resolve33(url);
38699
+ resolve34(url);
38377
38700
  };
38378
38701
  rejectCallback = (error) => {
38379
38702
  if (settled) return;
@@ -38532,7 +38855,7 @@ async function startOAuthListener({
38532
38855
  });
38533
38856
  });
38534
38857
  const bindAddress = getBindAddress();
38535
- await new Promise((resolve33, reject) => {
38858
+ await new Promise((resolve34, reject) => {
38536
38859
  const handleError = (error) => {
38537
38860
  server.off("error", handleError);
38538
38861
  if (error.code === "EADDRINUSE") {
@@ -38548,7 +38871,7 @@ async function startOAuthListener({
38548
38871
  server.once("error", handleError);
38549
38872
  server.listen(port, bindAddress, () => {
38550
38873
  server.off("error", handleError);
38551
- resolve33();
38874
+ resolve34();
38552
38875
  });
38553
38876
  });
38554
38877
  server.on("error", (error) => {
@@ -38556,7 +38879,7 @@ async function startOAuthListener({
38556
38879
  });
38557
38880
  return {
38558
38881
  waitForCallback: () => callbackPromise,
38559
- close: () => new Promise((resolve33, reject) => {
38882
+ close: () => new Promise((resolve34, reject) => {
38560
38883
  server.close((error) => {
38561
38884
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
38562
38885
  reject(error);
@@ -38565,7 +38888,7 @@ async function startOAuthListener({
38565
38888
  if (!settled) {
38566
38889
  rejectCallback(new Error("OAuth listener closed before callback"));
38567
38890
  }
38568
- resolve33();
38891
+ resolve34();
38569
38892
  });
38570
38893
  })
38571
38894
  };
@@ -38757,7 +39080,7 @@ async function select2(terminal, items, options) {
38757
39080
  writeLine("");
38758
39081
  renderedLines = lines;
38759
39082
  };
38760
- return new Promise((resolve33) => {
39083
+ return new Promise((resolve34) => {
38761
39084
  const wasRaw = stdin.isRaw ?? false;
38762
39085
  const cleanup2 = () => {
38763
39086
  if (cleaned)
@@ -38777,7 +39100,7 @@ async function select2(terminal, items, options) {
38777
39100
  };
38778
39101
  const finish = (value) => {
38779
39102
  cleanup2();
38780
- resolve33(value);
39103
+ resolve34(value);
38781
39104
  };
38782
39105
  const onSignal = () => finish(null);
38783
39106
  const onKey = (data) => {
@@ -38817,7 +39140,7 @@ async function select2(terminal, items, options) {
38817
39140
  stdin.setRawMode(true);
38818
39141
  } catch {
38819
39142
  cleanup2();
38820
- resolve33(null);
39143
+ resolve34(null);
38821
39144
  return;
38822
39145
  }
38823
39146
  stdin.resume();
@@ -39129,8 +39452,8 @@ async function acquireRefreshFileLockWithClock2(options) {
39129
39452
  let releaseConfirmed = false;
39130
39453
  let loss;
39131
39454
  let resolveLoss;
39132
- const lostPromise = new Promise((resolve33) => {
39133
- resolveLoss = resolve33;
39455
+ const lostPromise = new Promise((resolve34) => {
39456
+ resolveLoss = resolve34;
39134
39457
  });
39135
39458
  function notifyTimerStep(event) {
39136
39459
  try {
@@ -39294,7 +39617,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39294
39617
  }
39295
39618
  }
39296
39619
  async function backoff() {
39297
- await new Promise((resolve33) => setTimeout(resolve33, Math.floor(Math.random() * 4)));
39620
+ await new Promise((resolve34) => setTimeout(resolve34, Math.floor(Math.random() * 4)));
39298
39621
  }
39299
39622
  async function readLockState(notifyReady = true) {
39300
39623
  if (notifyReady && options.onStep)
@@ -39387,7 +39710,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39387
39710
  const remainingMs = deadline - performance.now();
39388
39711
  if (remainingMs <= 0)
39389
39712
  throw original;
39390
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
39713
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
39391
39714
  if (performance.now() >= deadline)
39392
39715
  throw original;
39393
39716
  delayMs = Math.min(delayMs * 2, 50);
@@ -39890,7 +40213,7 @@ async function acquireRefreshFileLockWithClock2(options) {
39890
40213
  const remainingMs = deadline - performance.now();
39891
40214
  if (remainingMs <= 0)
39892
40215
  break;
39893
- await new Promise((resolve33) => setTimeout(resolve33, Math.min(delayMs, remainingMs)));
40216
+ await new Promise((resolve34) => setTimeout(resolve34, Math.min(delayMs, remainingMs)));
39894
40217
  if (windowsPrivateFiles2 && performance.now() >= deadline)
39895
40218
  break;
39896
40219
  delayMs = Math.min(delayMs * 2, 50);
@@ -40771,7 +41094,7 @@ var ByteTail = class {
40771
41094
  };
40772
41095
  var defaultCommandRunner = {
40773
41096
  run(file, args, options = {}) {
40774
- return new Promise((resolve33) => {
41097
+ return new Promise((resolve34) => {
40775
41098
  const started = performance.now();
40776
41099
  const timeoutMs = options.timeoutMs ?? 15e3;
40777
41100
  const stderr = new ByteTail();
@@ -40789,7 +41112,7 @@ var defaultCommandRunner = {
40789
41112
  stdio: ["ignore", "pipe", "pipe"]
40790
41113
  });
40791
41114
  } catch {
40792
- resolve33({
41115
+ resolve34({
40793
41116
  exitCode: 1,
40794
41117
  stdout: "",
40795
41118
  stderr: "",
@@ -40824,7 +41147,7 @@ var defaultCommandRunner = {
40824
41147
  settled = true;
40825
41148
  if (timer)
40826
41149
  clearTimeout(timer);
40827
- resolve33({
41150
+ resolve34({
40828
41151
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
40829
41152
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
40830
41153
  stderr: stderr.toString(),
@@ -40980,7 +41303,7 @@ function recordSetupEnrollment(failure2, enrollment) {
40980
41303
  }
40981
41304
 
40982
41305
  // src/common-auth-embedded/setup/detect.js
40983
- import { accessSync, constants as constants3, existsSync as existsSync6, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync5 } from "node:fs";
41306
+ import { accessSync, constants as constants3, existsSync as existsSync6, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync6 } from "node:fs";
40984
41307
  import { mkdtemp, rm as rm7 } from "node:fs/promises";
40985
41308
  import { tmpdir as tmpdir3 } from "node:os";
40986
41309
  import { join as join22 } from "node:path";
@@ -41020,7 +41343,7 @@ function setupPaths(io = {}) {
41020
41343
  // src/common-auth-embedded/setup/detect.js
41021
41344
  function stat15(path5, kind) {
41022
41345
  try {
41023
- return statSync5(path5)[kind]();
41346
+ return statSync6(path5)[kind]();
41024
41347
  } catch {
41025
41348
  return false;
41026
41349
  }
@@ -41221,14 +41544,14 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
41221
41544
 
41222
41545
  // src/common-auth-embedded/setup/process-fence.js
41223
41546
  init_logger3();
41224
- import { statSync as statSync6 } from "node:fs";
41547
+ import { statSync as statSync7 } from "node:fs";
41225
41548
  import { win32 as win323 } from "node:path";
41226
41549
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
41227
41550
  var log9 = createLogger3("setup-process-fence");
41228
41551
  var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
41229
41552
  function isFile(file) {
41230
41553
  try {
41231
- return statSync6(file).isFile();
41554
+ return statSync7(file).isFile();
41232
41555
  } catch {
41233
41556
  return false;
41234
41557
  }
@@ -42398,19 +42721,31 @@ async function readNativeAuth(path5) {
42398
42721
  throw error;
42399
42722
  }
42400
42723
  }
42724
+ async function readOpenCodeAuthority(legacyPath) {
42725
+ try {
42726
+ const claustrum = await loadCommonAuthClaustrum();
42727
+ if (claustrum.hasVaultHost()) return "host";
42728
+ return await vaultAuthority2(
42729
+ claustrum.hostEnrollmentPaths({
42730
+ stateDir: openCodeVaultDir(
42731
+ legacyPath ?? resolve23(accountFileForVault())
42732
+ ),
42733
+ host: "opencode"
42734
+ }),
42735
+ OPENCODE_VAULT_ENROLLMENT_NAME,
42736
+ claustrum
42737
+ );
42738
+ } catch {
42739
+ return "unreadable";
42740
+ }
42741
+ }
42401
42742
  async function assertLocalOpenCodeLogin(legacyPath, generation) {
42402
- const claustrum = await loadCommonAuthClaustrum();
42403
- if (await claustrum.vaultAuthority(
42404
- claustrum.hostEnrollmentPaths({
42405
- stateDir: openCodeVaultDir(legacyPath),
42406
- host: "opencode"
42407
- }),
42408
- OPENCODE_VAULT_ENROLLMENT_NAME
42409
- ) !== "local")
42743
+ if (await readOpenCodeAuthority(legacyPath) !== "local")
42410
42744
  throw new Error(
42411
42745
  "Vault enrollment excludes local sign-in. Resolve vault access before choosing local setup."
42412
42746
  );
42413
42747
  if (generation === "2") return;
42748
+ const claustrum = await loadCommonAuthClaustrum();
42414
42749
  claustrum.assertHostSlotMatchesMode({
42415
42750
  mode: "local",
42416
42751
  auth: (await readNativeAuth(nativeOpenCodeAuthPath()))[OPENCODE_VAULT_PROVIDER],
@@ -43026,6 +43361,16 @@ async function runCli(argv, deps) {
43026
43361
  return 0;
43027
43362
  }
43028
43363
  try {
43364
+ const assertLocalAccounts = async () => {
43365
+ const authority = await (deps.readAuthority ?? readOpenCodeAuthority)();
43366
+ if (authority === "local") return;
43367
+ const source2 = authority === "vault" ? "Accounts are served by the vault, not this computer's local sign-ins." : authority === "host" ? "Accounts are served by Thalamus, not this computer's local sign-ins." : "Account authority could not be read, so this computer's local sign-ins were not used.";
43368
+ throw new Error(
43369
+ `${source2} Use the /antigravity menu in OpenCode to see them and their quota.`
43370
+ );
43371
+ };
43372
+ if (parsed.value.command === "list" || parsed.value.command === "quota")
43373
+ await assertLocalAccounts();
43029
43374
  if (parsed.value.command !== "setup") {
43030
43375
  if (parsed.value.command === "login") await deps.prepareVaultFolder?.();
43031
43376
  await deps.processHeartbeat?.();
@@ -43130,7 +43475,8 @@ async function runCli(argv, deps) {
43130
43475
  return 0;
43131
43476
  }
43132
43477
  const results = await deps.getQuota(storage?.accounts ?? [], {
43133
- refresh: parsed.value.refresh
43478
+ refresh: parsed.value.refresh,
43479
+ ...parsed.value.refresh ? { assertAdmission: assertLocalAccounts } : {}
43134
43480
  });
43135
43481
  deps.stdout.write(
43136
43482
  parsed.value.json ? `${JSON.stringify(quotaSummary(results))}
@@ -44024,7 +44370,7 @@ async function writePortFile(dir, entry, options = {}) {
44024
44370
  } catch (error) {
44025
44371
  if (error.code !== "ENOENT" || attempt === 5)
44026
44372
  throw error;
44027
- await new Promise((resolve33) => setTimeout(resolve33, 25));
44373
+ await new Promise((resolve34) => setTimeout(resolve34, 25));
44028
44374
  }
44029
44375
  }
44030
44376
  }
@@ -44150,7 +44496,7 @@ var BodyTooLargeError = class extends Error {
44150
44496
  }
44151
44497
  };
44152
44498
  function readBody(req) {
44153
- return new Promise((resolve33, reject) => {
44499
+ return new Promise((resolve34, reject) => {
44154
44500
  const tooLarge = (declaredOversize = false) => {
44155
44501
  req.removeAllListeners("data");
44156
44502
  req.on("data", () => {
@@ -44173,7 +44519,7 @@ function readBody(req) {
44173
44519
  }
44174
44520
  chunks.push(chunk);
44175
44521
  });
44176
- req.on("end", () => resolve33(Buffer.concat(chunks).toString("utf8")));
44522
+ req.on("end", () => resolve34(Buffer.concat(chunks).toString("utf8")));
44177
44523
  req.on("error", reject);
44178
44524
  });
44179
44525
  }
@@ -44352,12 +44698,12 @@ async function startRpcServer(options) {
44352
44698
  json(500, { error: "internal error" });
44353
44699
  }
44354
44700
  }
44355
- const port = await new Promise((resolve33, reject) => {
44701
+ const port = await new Promise((resolve34, reject) => {
44356
44702
  server.on("error", reject);
44357
44703
  server.listen(0, "127.0.0.1", () => {
44358
44704
  const addr = server.address();
44359
44705
  if (addr && typeof addr === "object")
44360
- resolve33(addr.port);
44706
+ resolve34(addr.port);
44361
44707
  else
44362
44708
  reject(new Error("no port"));
44363
44709
  });
@@ -44380,16 +44726,16 @@ async function startRpcServer(options) {
44380
44726
  rpcPort: port
44381
44727
  });
44382
44728
  } catch (error) {
44383
- await new Promise((resolve33) => server.close(() => resolve33()));
44729
+ await new Promise((resolve34) => server.close(() => resolve34()));
44384
44730
  throw error;
44385
44731
  }
44386
44732
  return {
44387
44733
  port,
44388
44734
  token,
44389
44735
  async stop() {
44390
- await new Promise((resolve33) => {
44736
+ await new Promise((resolve34) => {
44391
44737
  server.closeAllConnections?.();
44392
- server.close(() => resolve33());
44738
+ server.close(() => resolve34());
44393
44739
  for (const socket of connections)
44394
44740
  socket.destroy();
44395
44741
  });
@@ -45314,7 +45660,7 @@ import { join as join33, resolve as resolve29 } from "node:path";
45314
45660
  // ../core/dist/common-auth-embedded/tui-prefs/watcher.js
45315
45661
  init_canonical_file_path();
45316
45662
  init_private_files();
45317
- import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync8, watch } from "node:fs";
45663
+ import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync9, watch } from "node:fs";
45318
45664
  import { readFile as readFile17, stat as stat18 } from "node:fs/promises";
45319
45665
  import { basename as basename11, dirname as dirname25, join as join32, resolve as resolve28 } from "node:path";
45320
45666
  import { clearTimeout as clearTimeout2, setTimeout as setTimeout2 } from "node:timers";
@@ -45358,7 +45704,7 @@ function watchFile(file, onChange, options, settings) {
45358
45704
  let lastSeen = null;
45359
45705
  if (settings || !windowsPrivateFiles)
45360
45706
  try {
45361
- const metadata = identity3((options.fs?.statSync ?? statSync8)(path5), settings);
45707
+ const metadata = identity3((options.fs?.statSync ?? statSync9)(path5), settings);
45362
45708
  lastSeen = (options.fs?.readFileSync ?? ((file2) => readFileSync8(file2, "utf8")))(path5);
45363
45709
  lastMetadata = metadata;
45364
45710
  } catch {
@@ -46244,7 +46590,7 @@ function openSettings(definition, options) {
46244
46590
  loaded = windowsSeen.get(path5) !== content;
46245
46591
  windowsSeen.set(path5, content);
46246
46592
  };
46247
- const readFile23 = async ([path5]) => {
46593
+ const readFile24 = async ([path5]) => {
46248
46594
  let text2;
46249
46595
  try {
46250
46596
  text2 = await SettingsFs.readFile(path5, "utf8");
@@ -46281,7 +46627,7 @@ function openSettings(definition, options) {
46281
46627
  snapshot: buildSettingsSnapshot(definition, file, parsed)
46282
46628
  } : { status: "unparseable" };
46283
46629
  };
46284
- const outcome = process.platform === "win32" ? await readFile23([file.path]) : await cache.read([file.path], readFile23);
46630
+ const outcome = process.platform === "win32" ? await readFile24([file.path]) : await cache.read([file.path], readFile24);
46285
46631
  const key2 = JSON.stringify([file.kind, file.path]);
46286
46632
  if (currentSequence <= (committedSequences.get(key2) ?? 0))
46287
46633
  return;
@@ -48378,6 +48724,25 @@ function selectBestVerificationUrl(urls) {
48378
48724
  unique.sort((a, b) => score(b) - score(a));
48379
48725
  return unique[0];
48380
48726
  }
48727
+ function structuredVerificationUrl(bodyText) {
48728
+ const urls = /* @__PURE__ */ new Set();
48729
+ const collect = (payload) => {
48730
+ try {
48731
+ JSON.parse(payload, (key2, value) => {
48732
+ if (typeof value === "string" && /^(?:validation_url|verify_url|verification_url|url)$/i.test(key2) && /^https:\/\//i.test(decodeEscapedText(value).trim()))
48733
+ urls.add(value);
48734
+ return value;
48735
+ });
48736
+ } catch {
48737
+ }
48738
+ };
48739
+ collect(bodyText);
48740
+ for (const rawLine of bodyText.split("\n")) {
48741
+ const line = rawLine.trim();
48742
+ if (line.startsWith("data:")) collect(line.slice(5));
48743
+ }
48744
+ return selectBestVerificationUrl([...urls]);
48745
+ }
48381
48746
  function extractAccountAccessErrorDetails(bodyText) {
48382
48747
  const decodedBody = decodeEscapedText(bodyText);
48383
48748
  const lowerBody = decodedBody.toLowerCase();
@@ -48455,11 +48820,13 @@ function extractAccountAccessErrorDetails(bodyText) {
48455
48820
  (line) => line && !line.startsWith("data:") && /(verify|validation|required|ineligible)/i.test(line)
48456
48821
  );
48457
48822
  }
48823
+ const structuredVerifyUrl = structuredVerificationUrl(bodyText);
48458
48824
  return {
48459
48825
  validationRequired,
48460
48826
  accountIneligible,
48461
48827
  message,
48462
- verifyUrl: selectBestVerificationUrl([...verificationUrls])
48828
+ verifyUrl: selectBestVerificationUrl([...verificationUrls]),
48829
+ ...structuredVerifyUrl && { structuredVerifyUrl }
48463
48830
  };
48464
48831
  }
48465
48832
  function buildAccountAccessProbeRequest(projectId) {
@@ -49493,7 +49860,7 @@ async function select3(items, options) {
49493
49860
  }
49494
49861
  renderedLines = linesWritten;
49495
49862
  };
49496
- return new Promise((resolve33) => {
49863
+ return new Promise((resolve34) => {
49497
49864
  const wasRaw = stdin.isRaw ?? false;
49498
49865
  const cleanup2 = () => {
49499
49866
  if (isCleanedUp) return;
@@ -49514,11 +49881,11 @@ async function select3(items, options) {
49514
49881
  };
49515
49882
  const onSignal = () => {
49516
49883
  cleanup2();
49517
- resolve33(null);
49884
+ resolve34(null);
49518
49885
  };
49519
49886
  const finishWithValue = (value) => {
49520
49887
  cleanup2();
49521
- resolve33(value);
49888
+ resolve34(value);
49522
49889
  };
49523
49890
  const findNextSelectable = (from, direction) => {
49524
49891
  if (items.length === 0) return from;
@@ -49564,7 +49931,7 @@ async function select3(items, options) {
49564
49931
  stdin.setRawMode(true);
49565
49932
  } catch {
49566
49933
  cleanup2();
49567
- resolve33(null);
49934
+ resolve34(null);
49568
49935
  return;
49569
49936
  }
49570
49937
  stdin.resume();
@@ -51967,20 +52334,20 @@ import crypto2 from "node:crypto";
51967
52334
  import { createHash as createHash17 } from "node:crypto";
51968
52335
 
51969
52336
  // src/plugin/cache/signature-cache.ts
52337
+ init_atomic_write();
51970
52338
  init_runtime_paths();
51971
- import {
51972
- existsSync as existsSync13,
51973
- mkdirSync as mkdirSync5,
51974
- readFileSync as readFileSync14,
51975
- renameSync as renameSync4,
51976
- unlinkSync as unlinkSync3,
51977
- writeFileSync as writeFileSync5
51978
- } from "node:fs";
51979
- import { tmpdir as tmpdir5 } from "node:os";
51980
- import { dirname as dirname33, join as join40 } from "node:path";
52339
+ import { existsSync as existsSync13, readFileSync as readFileSync14 } from "node:fs";
52340
+ import { readFile as readFile23 } from "node:fs/promises";
52341
+ import { resolve as resolve32 } from "node:path";
51981
52342
  function getSignatureCacheFilePath() {
51982
52343
  return stateHomeSignatureCacheFile();
51983
52344
  }
52345
+ var MAX_ENTRIES = 4096;
52346
+ function newestEntries(entries) {
52347
+ if (entries.length <= MAX_ENTRIES) return entries;
52348
+ return entries.sort(([, a], [, b]) => a.timestamp - b.timestamp).slice(-MAX_ENTRIES);
52349
+ }
52350
+ var pendingWrites = /* @__PURE__ */ new Map();
51984
52351
  var SignatureCache = class {
51985
52352
  // In-memory cache: key -> entry with signature and optional thinking text
51986
52353
  cache = /* @__PURE__ */ new Map();
@@ -51995,6 +52362,8 @@ var SignatureCache = class {
51995
52362
  now;
51996
52363
  // State
51997
52364
  dirty = false;
52365
+ revision = 0;
52366
+ pendingWrite;
51998
52367
  writeTimer = null;
51999
52368
  cleanupTimer = null;
52000
52369
  // Statistics
@@ -52031,11 +52400,10 @@ var SignatureCache = class {
52031
52400
  */
52032
52401
  store(key2, signature) {
52033
52402
  if (!this.enabled) return;
52034
- this.cache.set(key2, {
52403
+ this.storeEntry(key2, {
52035
52404
  value: signature,
52036
52405
  timestamp: this.now()
52037
52406
  });
52038
- this.dirty = true;
52039
52407
  }
52040
52408
  /**
52041
52409
  * Retrieve a signature from the cache.
@@ -52086,13 +52454,29 @@ var SignatureCache = class {
52086
52454
  */
52087
52455
  storeThinking(key2, thinkingText, signature, toolIds) {
52088
52456
  if (!this.enabled || !thinkingText || !signature) return;
52089
- this.cache.set(key2, {
52457
+ this.storeEntry(key2, {
52090
52458
  value: signature,
52091
52459
  timestamp: this.now(),
52092
52460
  thinkingText,
52093
52461
  textPreview: thinkingText.slice(0, 100),
52094
52462
  toolIds
52095
52463
  });
52464
+ }
52465
+ storeEntry(key2, entry) {
52466
+ this.cache.delete(key2);
52467
+ this.cache.set(key2, entry);
52468
+ if (this.cache.size > MAX_ENTRIES) {
52469
+ let oldest;
52470
+ let oldestTimestamp = Number.POSITIVE_INFINITY;
52471
+ for (const [candidate, value] of this.cache) {
52472
+ if (oldest === void 0 || value.timestamp < oldestTimestamp) {
52473
+ oldest = candidate;
52474
+ oldestTimestamp = value.timestamp;
52475
+ }
52476
+ }
52477
+ if (oldest !== void 0) this.cache.delete(oldest);
52478
+ }
52479
+ this.revision++;
52096
52480
  this.dirty = true;
52097
52481
  }
52098
52482
  /**
@@ -52161,7 +52545,17 @@ var SignatureCache = class {
52161
52545
  */
52162
52546
  async flush() {
52163
52547
  if (!this.enabled) return true;
52164
- return this.saveToDisk();
52548
+ const path5 = resolve32(this.cacheFilePath);
52549
+ const previous = pendingWrites.get(path5) ?? Promise.resolve(true);
52550
+ const writing = previous.then(() => this.saveToDisk());
52551
+ this.pendingWrite = writing;
52552
+ pendingWrites.set(path5, writing);
52553
+ try {
52554
+ return await writing;
52555
+ } finally {
52556
+ if (this.pendingWrite === writing) this.pendingWrite = void 0;
52557
+ if (pendingWrites.get(path5) === writing) pendingWrites.delete(path5);
52558
+ }
52165
52559
  }
52166
52560
  /**
52167
52561
  * Graceful shutdown: stop timers and flush to disk.
@@ -52176,7 +52570,7 @@ var SignatureCache = class {
52176
52570
  this.cleanupTimer = null;
52177
52571
  }
52178
52572
  if (this.dirty && this.enabled) {
52179
- this.saveToDisk();
52573
+ void this.flush();
52180
52574
  }
52181
52575
  }
52182
52576
  // ===========================================================================
@@ -52211,6 +52605,9 @@ var SignatureCache = class {
52211
52605
  _expired++;
52212
52606
  }
52213
52607
  }
52608
+ if (this.cache.size > MAX_ENTRIES) {
52609
+ this.cache = new Map(newestEntries([...this.cache]));
52610
+ }
52214
52611
  } catch {
52215
52612
  }
52216
52613
  }
@@ -52218,22 +52615,17 @@ var SignatureCache = class {
52218
52615
  * Save cache to disk with atomic write pattern.
52219
52616
  * Merges with existing disk entries that haven't expired.
52220
52617
  */
52221
- saveToDisk() {
52618
+ async saveToDisk() {
52222
52619
  try {
52223
- const dir = dirname33(this.cacheFilePath);
52224
- if (!existsSync13(dir)) {
52225
- mkdirSync5(dir, { recursive: true });
52226
- }
52227
- const now2 = this.now();
52228
52620
  let existingEntries = {};
52229
- if (existsSync13(this.cacheFilePath)) {
52230
- try {
52231
- const content = readFileSync14(this.cacheFilePath, "utf-8");
52232
- const data = JSON.parse(content);
52233
- existingEntries = data.entries || {};
52234
- } catch {
52235
- }
52621
+ try {
52622
+ const content = await readFile23(this.cacheFilePath, "utf-8");
52623
+ const data = JSON.parse(content);
52624
+ existingEntries = data.entries || {};
52625
+ } catch {
52236
52626
  }
52627
+ const now2 = this.now();
52628
+ const revision = this.revision;
52237
52629
  const validDiskEntries = {};
52238
52630
  for (const [key2, entry] of Object.entries(existingEntries)) {
52239
52631
  const age = now2 - entry.timestamp;
@@ -52252,7 +52644,9 @@ var SignatureCache = class {
52252
52644
  version: "1.0",
52253
52645
  memory_ttl_seconds: this.retentionMemoryTtlMs / 1e3,
52254
52646
  disk_ttl_seconds: this.retentionDiskTtlMs / 1e3,
52255
- entries: mergedEntries,
52647
+ entries: Object.fromEntries(
52648
+ newestEntries(Object.entries(mergedEntries))
52649
+ ),
52256
52650
  statistics: {
52257
52651
  memory_hits: this.stats.memoryHits,
52258
52652
  disk_hits: this.stats.diskHits,
@@ -52261,22 +52655,9 @@ var SignatureCache = class {
52261
52655
  last_write: now2
52262
52656
  }
52263
52657
  };
52264
- const tmpPath = join40(
52265
- tmpdir5(),
52266
- `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
52267
- );
52268
- writeFileSync5(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
52269
- try {
52270
- renameSync4(tmpPath, this.cacheFilePath);
52271
- } catch {
52272
- writeFileSync5(this.cacheFilePath, readFileSync14(tmpPath));
52273
- try {
52274
- unlinkSync3(tmpPath);
52275
- } catch {
52276
- }
52277
- }
52658
+ await writeJsonAtomic(this.cacheFilePath, cacheData);
52278
52659
  this.stats.writes++;
52279
- this.dirty = false;
52660
+ if (revision === this.revision) this.dirty = false;
52280
52661
  return true;
52281
52662
  } catch {
52282
52663
  return false;
@@ -52299,8 +52680,8 @@ var SignatureCache = class {
52299
52680
  }
52300
52681
  startWriteTimer() {
52301
52682
  this.writeTimer = setInterval(() => {
52302
- if (this.dirty) {
52303
- this.saveToDisk();
52683
+ if (this.dirty && !this.pendingWrite) {
52684
+ void this.flush();
52304
52685
  }
52305
52686
  }, this.writeIntervalMs);
52306
52687
  }
@@ -52479,11 +52860,18 @@ function createSignatureProcessState(options = {}) {
52479
52860
  updateRetention(shared3.path);
52480
52861
  return;
52481
52862
  }
52482
- if (disks.get(shared3.path) === shared3) disks.delete(shared3.path);
52863
+ const finalWrite = shared3.cache.flush();
52864
+ shared3.finalWrite = finalWrite;
52483
52865
  try {
52484
- await shared3.cache.flush();
52866
+ await finalWrite;
52485
52867
  } finally {
52486
- shared3.cache.shutdown();
52868
+ if (shared3.finalWrite === finalWrite) {
52869
+ shared3.finalWrite = void 0;
52870
+ if (shared3.owners.size === 0) {
52871
+ disks.delete(shared3.path);
52872
+ shared3.cache.shutdown();
52873
+ }
52874
+ }
52487
52875
  }
52488
52876
  };
52489
52877
  return {
@@ -52508,7 +52896,10 @@ function createSignatureProcessState(options = {}) {
52508
52896
  pathReaders.add(consumer);
52509
52897
  updateRetention(path5);
52510
52898
  }
52511
- const readableCache = () => shared3?.cache ?? (path5 ? disks.get(path5)?.cache : void 0);
52899
+ const readableCache = () => {
52900
+ const current = shared3 ?? (path5 ? disks.get(path5) : void 0);
52901
+ if (current?.owners.size) return current.cache;
52902
+ };
52512
52903
  const signatureStore = createSignatureStore();
52513
52904
  let disposed = false;
52514
52905
  return {
@@ -52613,13 +53004,13 @@ function clearSignatureCache(sessionId) {
52613
53004
  }
52614
53005
 
52615
53006
  // src/plugin/image-saver.ts
52616
- import { chmodSync as chmodSync4, existsSync as existsSync14, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
53007
+ import { chmodSync as chmodSync4, existsSync as existsSync14, mkdirSync as mkdirSync5, writeFileSync as writeFileSync5 } from "node:fs";
52617
53008
  import { homedir as homedir14 } from "node:os";
52618
- import { join as join41 } from "node:path";
53009
+ import { join as join40 } from "node:path";
52619
53010
  function getImageOutputDir(outputDir) {
52620
- const resolved = outputDir ?? join41(homedir14(), ".opencode", "generated-images");
53011
+ const resolved = outputDir ?? join40(homedir14(), ".opencode", "generated-images");
52621
53012
  if (!existsSync14(resolved)) {
52622
- mkdirSync6(resolved, { recursive: true, mode: 448 });
53013
+ mkdirSync5(resolved, { recursive: true, mode: 448 });
52623
53014
  }
52624
53015
  chmodSync4(resolved, 448);
52625
53016
  return resolved;
@@ -52640,8 +53031,8 @@ function generateImageFilename(mimeType) {
52640
53031
  function saveImageToDisk(base64Data, mimeType, outputDir) {
52641
53032
  try {
52642
53033
  const resolvedOutputDir = getImageOutputDir(outputDir);
52643
- const filePath = join41(resolvedOutputDir, generateImageFilename(mimeType));
52644
- writeFileSync6(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
53034
+ const filePath = join40(resolvedOutputDir, generateImageFilename(mimeType));
53035
+ writeFileSync5(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
52645
53036
  chmodSync4(filePath, 384);
52646
53037
  return filePath;
52647
53038
  } catch (error) {
@@ -53084,6 +53475,49 @@ data: ${JSON.stringify(syntheticUsage)}
53084
53475
  });
53085
53476
  }
53086
53477
 
53478
+ // src/plugin/core/streaming/displayed-thinking.ts
53479
+ var MAX_DISPLAYED_THINKING_SESSIONS = 256;
53480
+ var MAX_DISPLAYED_THINKING_PER_SESSION = 512;
53481
+ var BoundedHashSet = class extends Set {
53482
+ constructor(limit) {
53483
+ super();
53484
+ this.limit = limit;
53485
+ }
53486
+ limit;
53487
+ add(value) {
53488
+ if (!this.has(value) && this.size >= this.limit) {
53489
+ const oldest = this.values().next().value;
53490
+ if (oldest !== void 0) this.delete(oldest);
53491
+ }
53492
+ return super.add(value);
53493
+ }
53494
+ };
53495
+ function createDisplayedThinkingRegistry(limits = {}) {
53496
+ const maxSessions = limits.sessions ?? MAX_DISPLAYED_THINKING_SESSIONS;
53497
+ const perSession = limits.perSession ?? MAX_DISPLAYED_THINKING_PER_SESSION;
53498
+ const sessions = /* @__PURE__ */ new Map();
53499
+ return {
53500
+ forSession(sessionKey) {
53501
+ if (!sessionKey) return void 0;
53502
+ let hashes = sessions.get(sessionKey);
53503
+ if (hashes) {
53504
+ sessions.delete(sessionKey);
53505
+ } else {
53506
+ hashes = new BoundedHashSet(perSession);
53507
+ if (sessions.size >= maxSessions) {
53508
+ const oldest = sessions.keys().next().value;
53509
+ if (oldest !== void 0) sessions.delete(oldest);
53510
+ }
53511
+ }
53512
+ sessions.set(sessionKey, hashes);
53513
+ return hashes;
53514
+ },
53515
+ get sessionCount() {
53516
+ return sessions.size;
53517
+ }
53518
+ };
53519
+ }
53520
+
53087
53521
  // src/plugin/request.ts
53088
53522
  init_debug();
53089
53523
 
@@ -53091,12 +53525,12 @@ init_debug();
53091
53525
  init_dist();
53092
53526
  init_logging_utils();
53093
53527
  import { createHash as createHash18 } from "node:crypto";
53094
- import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "node:fs";
53095
- import { tmpdir as tmpdir6 } from "node:os";
53096
- import { join as join42 } from "node:path";
53528
+ import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
53529
+ import { tmpdir as tmpdir5 } from "node:os";
53530
+ import { join as join41 } from "node:path";
53097
53531
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
53098
53532
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
53099
- var DEFAULT_DUMP_DIR = join42(tmpdir6(), "opencode-antigravity-gemini-dumps");
53533
+ var DEFAULT_DUMP_DIR = join41(tmpdir5(), "opencode-antigravity-gemini-dumps");
53100
53534
  var DUMP_DIR_MODE = 448;
53101
53535
  var DUMP_FILE_MODE = 384;
53102
53536
  var nextDumpId = 0;
@@ -53228,7 +53662,7 @@ function bodyStructureSummary(bodyText) {
53228
53662
  };
53229
53663
  }
53230
53664
  function writeJson(path5, value) {
53231
- writeFileSync7(path5, `${JSON.stringify(value, null, 2)}
53665
+ writeFileSync6(path5, `${JSON.stringify(value, null, 2)}
53232
53666
  `, {
53233
53667
  encoding: "utf8",
53234
53668
  mode: DUMP_FILE_MODE
@@ -53250,8 +53684,8 @@ function writeGeminiDump(input2) {
53250
53684
  nextDumpId += 1;
53251
53685
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
53252
53686
  const dumpDir = getGeminiDumpDirectory();
53253
- const prefix = join42(dumpDir, id);
53254
- mkdirSync7(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
53687
+ const prefix = join41(dumpDir, id);
53688
+ mkdirSync6(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
53255
53689
  const context = {
53256
53690
  id,
53257
53691
  files: {
@@ -53279,11 +53713,11 @@ function writeGeminiDump(input2) {
53279
53713
  }
53280
53714
  }
53281
53715
  };
53282
- writeFileSync7(context.files.request, redactJsonBodyString(input2.body), {
53716
+ writeFileSync6(context.files.request, redactJsonBodyString(input2.body), {
53283
53717
  encoding: "utf8",
53284
53718
  mode: DUMP_FILE_MODE
53285
53719
  });
53286
- writeFileSync7(context.files.response, "", {
53720
+ writeFileSync6(context.files.response, "", {
53287
53721
  encoding: "utf8",
53288
53722
  mode: DUMP_FILE_MODE
53289
53723
  });
@@ -53335,27 +53769,27 @@ init_logger4();
53335
53769
  // src/plugin/recovery/storage.ts
53336
53770
  import {
53337
53771
  existsSync as existsSync15,
53338
- mkdirSync as mkdirSync8,
53772
+ mkdirSync as mkdirSync7,
53339
53773
  readdirSync as readdirSync2,
53340
53774
  readFileSync as readFileSync15,
53341
- unlinkSync as unlinkSync4,
53342
- writeFileSync as writeFileSync8
53775
+ unlinkSync as unlinkSync3,
53776
+ writeFileSync as writeFileSync7
53343
53777
  } from "node:fs";
53344
- import { join as join44 } from "node:path";
53778
+ import { join as join43 } from "node:path";
53345
53779
 
53346
53780
  // src/plugin/recovery/constants.ts
53347
53781
  import { homedir as homedir15 } from "node:os";
53348
- import { join as join43 } from "node:path";
53782
+ import { join as join42 } from "node:path";
53349
53783
  function getXdgData() {
53350
53784
  const platform = process.platform;
53351
53785
  if (platform === "win32") {
53352
- return process.env.APPDATA || join43(homedir15(), "AppData", "Roaming");
53786
+ return process.env.APPDATA || join42(homedir15(), "AppData", "Roaming");
53353
53787
  }
53354
- return process.env.XDG_DATA_HOME || join43(homedir15(), ".local", "share");
53788
+ return process.env.XDG_DATA_HOME || join42(homedir15(), ".local", "share");
53355
53789
  }
53356
- var OPENCODE_STORAGE = join43(getXdgData(), "opencode", "storage");
53357
- var MESSAGE_STORAGE = join43(OPENCODE_STORAGE, "message");
53358
- var PART_STORAGE = join43(OPENCODE_STORAGE, "part");
53790
+ var OPENCODE_STORAGE = join42(getXdgData(), "opencode", "storage");
53791
+ var MESSAGE_STORAGE = join42(OPENCODE_STORAGE, "message");
53792
+ var PART_STORAGE = join42(OPENCODE_STORAGE, "part");
53359
53793
  var THINKING_TYPES = /* @__PURE__ */ new Set([
53360
53794
  "thinking",
53361
53795
  "redacted_thinking",
@@ -53365,13 +53799,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
53365
53799
  // src/plugin/recovery/storage.ts
53366
53800
  function getMessageDir(sessionID) {
53367
53801
  if (!existsSync15(MESSAGE_STORAGE)) return "";
53368
- const directPath = join44(MESSAGE_STORAGE, sessionID);
53802
+ const directPath = join43(MESSAGE_STORAGE, sessionID);
53369
53803
  if (existsSync15(directPath)) {
53370
53804
  return directPath;
53371
53805
  }
53372
53806
  try {
53373
53807
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
53374
- const sessionPath = join44(MESSAGE_STORAGE, dir, sessionID);
53808
+ const sessionPath = join43(MESSAGE_STORAGE, dir, sessionID);
53375
53809
  if (existsSync15(sessionPath)) {
53376
53810
  return sessionPath;
53377
53811
  }
@@ -53388,7 +53822,7 @@ function readMessages(sessionID) {
53388
53822
  for (const file of readdirSync2(messageDir)) {
53389
53823
  if (!file.endsWith(".json")) continue;
53390
53824
  try {
53391
- const content = readFileSync15(join44(messageDir, file), "utf-8");
53825
+ const content = readFileSync15(join43(messageDir, file), "utf-8");
53392
53826
  messages.push(JSON.parse(content));
53393
53827
  } catch {
53394
53828
  }
@@ -53404,14 +53838,14 @@ function readMessages(sessionID) {
53404
53838
  });
53405
53839
  }
53406
53840
  function readParts(messageID) {
53407
- const partDir = join44(PART_STORAGE, messageID);
53841
+ const partDir = join43(PART_STORAGE, messageID);
53408
53842
  if (!existsSync15(partDir)) return [];
53409
53843
  const parts = [];
53410
53844
  try {
53411
53845
  for (const file of readdirSync2(partDir)) {
53412
53846
  if (!file.endsWith(".json")) continue;
53413
53847
  try {
53414
- const content = readFileSync15(join44(partDir, file), "utf-8");
53848
+ const content = readFileSync15(join43(partDir, file), "utf-8");
53415
53849
  parts.push(JSON.parse(content));
53416
53850
  } catch {
53417
53851
  }
@@ -53453,10 +53887,10 @@ function findMessagesWithOrphanThinking(sessionID) {
53453
53887
  return result;
53454
53888
  }
53455
53889
  function prependThinkingPart(sessionID, messageID) {
53456
- const partDir = join44(PART_STORAGE, messageID);
53890
+ const partDir = join43(PART_STORAGE, messageID);
53457
53891
  try {
53458
53892
  if (!existsSync15(partDir)) {
53459
- mkdirSync8(partDir, { recursive: true });
53893
+ mkdirSync7(partDir, { recursive: true });
53460
53894
  }
53461
53895
  const partId = "prt_0000000000_thinking";
53462
53896
  const part = {
@@ -53467,8 +53901,8 @@ function prependThinkingPart(sessionID, messageID) {
53467
53901
  thinking: "",
53468
53902
  synthetic: true
53469
53903
  };
53470
- writeFileSync8(
53471
- join44(partDir, `${partId}.json`),
53904
+ writeFileSync7(
53905
+ join43(partDir, `${partId}.json`),
53472
53906
  JSON.stringify(part, null, 2)
53473
53907
  );
53474
53908
  return true;
@@ -53477,18 +53911,18 @@ function prependThinkingPart(sessionID, messageID) {
53477
53911
  }
53478
53912
  }
53479
53913
  function stripThinkingParts(messageID) {
53480
- const partDir = join44(PART_STORAGE, messageID);
53914
+ const partDir = join43(PART_STORAGE, messageID);
53481
53915
  if (!existsSync15(partDir)) return false;
53482
53916
  let anyRemoved = false;
53483
53917
  try {
53484
53918
  for (const file of readdirSync2(partDir)) {
53485
53919
  if (!file.endsWith(".json")) continue;
53486
53920
  try {
53487
- const filePath = join44(partDir, file);
53921
+ const filePath = join43(partDir, file);
53488
53922
  const content = readFileSync15(filePath, "utf-8");
53489
53923
  const part = JSON.parse(content);
53490
53924
  if (THINKING_TYPES.has(part.type)) {
53491
- unlinkSync4(filePath);
53925
+ unlinkSync3(filePath);
53492
53926
  anyRemoved = true;
53493
53927
  }
53494
53928
  } catch {
@@ -54781,6 +55215,9 @@ function fixToolResponseGrouping(contents) {
54781
55215
  const newContents = [];
54782
55216
  const pendingGroups = [];
54783
55217
  const collectedResponses = /* @__PURE__ */ new Map();
55218
+ const arrivalById = /* @__PURE__ */ new Map();
55219
+ let arrivals = 0;
55220
+ const idsByName = /* @__PURE__ */ new Map();
54784
55221
  for (const content of contents) {
54785
55222
  const role = content.role;
54786
55223
  const parts = content.parts || [];
@@ -54790,6 +55227,15 @@ function fixToolResponseGrouping(contents) {
54790
55227
  const respId = resp.functionResponse?.id || "";
54791
55228
  if (respId && !collectedResponses.has(respId)) {
54792
55229
  collectedResponses.set(respId, resp);
55230
+ const arrival = arrivals++;
55231
+ arrivalById.set(respId, arrival);
55232
+ const name = resp.functionResponse?.name || "";
55233
+ let queue2 = idsByName.get(name);
55234
+ if (!queue2) {
55235
+ queue2 = { entries: [], head: 0 };
55236
+ idsByName.set(name, queue2);
55237
+ }
55238
+ queue2.entries.push({ id: respId, arrival });
54793
55239
  }
54794
55240
  }
54795
55241
  for (let i = pendingGroups.length - 1; i >= 0; i--) {
@@ -54827,7 +55273,20 @@ function fixToolResponseGrouping(contents) {
54827
55273
  newContents.push(content);
54828
55274
  }
54829
55275
  }
55276
+ const firstCollectedNamed = (name) => {
55277
+ const queue2 = idsByName.get(name);
55278
+ if (!queue2) return null;
55279
+ while (queue2.head < queue2.entries.length) {
55280
+ const entry = queue2.entries[queue2.head];
55281
+ if (collectedResponses.has(entry.id) && arrivalById.get(entry.id) === entry.arrival) {
55282
+ return entry.id;
55283
+ }
55284
+ queue2.head++;
55285
+ }
55286
+ return null;
55287
+ };
54830
55288
  pendingGroups.sort((a, b) => b.insertAfterIdx - a.insertAfterIdx);
55289
+ const insertedAfter = /* @__PURE__ */ new Map();
54831
55290
  for (const group of pendingGroups) {
54832
55291
  const groupResponses = [];
54833
55292
  for (let i = 0; i < group.ids.length; i++) {
@@ -54838,20 +55297,9 @@ function fixToolResponseGrouping(contents) {
54838
55297
  collectedResponses.delete(expectedId);
54839
55298
  } else if (collectedResponses.size > 0) {
54840
55299
  let matchedId = null;
54841
- for (const [orphanId, orphanResp] of collectedResponses) {
54842
- const orphanName = orphanResp.functionResponse?.name || "";
54843
- if (orphanName === expectedName) {
54844
- matchedId = orphanId;
54845
- break;
54846
- }
54847
- }
55300
+ matchedId = firstCollectedNamed(expectedName);
54848
55301
  if (!matchedId) {
54849
- for (const [orphanId, orphanResp] of collectedResponses) {
54850
- if (orphanResp.functionResponse?.name === "unknown_function") {
54851
- matchedId = orphanId;
54852
- break;
54853
- }
54854
- }
55302
+ matchedId = firstCollectedNamed("unknown_function");
54855
55303
  }
54856
55304
  if (!matchedId) {
54857
55305
  matchedId = collectedResponses.keys().next().value ?? null;
@@ -54891,13 +55339,20 @@ function fixToolResponseGrouping(contents) {
54891
55339
  }
54892
55340
  }
54893
55341
  if (groupResponses.length > 0) {
54894
- newContents.splice(group.insertAfterIdx + 1, 0, {
55342
+ insertedAfter.set(group.insertAfterIdx, {
54895
55343
  parts: groupResponses,
54896
55344
  role: "user"
54897
55345
  });
54898
55346
  }
54899
55347
  }
54900
- return newContents;
55348
+ if (insertedAfter.size === 0) return newContents;
55349
+ const withRecovered = [];
55350
+ for (let i = 0; i < newContents.length; i++) {
55351
+ withRecovered.push(newContents[i]);
55352
+ const recovered = insertedAfter.get(i);
55353
+ if (recovered) withRecovered.push(recovered);
55354
+ }
55355
+ return withRecovered;
54901
55356
  }
54902
55357
  function findOrphanedToolUseIds(messages) {
54903
55358
  const toolUseIds = /* @__PURE__ */ new Set();
@@ -55812,7 +56267,7 @@ init_dist();
55812
56267
  var log14 = createLogger4("request");
55813
56268
  var PLUGIN_SESSION_ID = `-${crypto2.randomUUID()}`;
55814
56269
  var DEFAULT_AGY_REQUEST_SESSION = createAgyRequestSessionContext();
55815
- var sessionDisplayedThinkingHashes = /* @__PURE__ */ new Set();
56270
+ var openCode1DisplayedThinking = createDisplayedThinkingRegistry();
55816
56271
  var MIN_SIGNATURE_LENGTH = 50;
55817
56272
  var AGY_CLAUDE_THINKING_BUDGET = 1024;
55818
56273
  var ANTIGRAVITY_ENVELOPE_FIELD_ORDER = [
@@ -55958,6 +56413,9 @@ function ensureThinkingFields(obj) {
55958
56413
  ensureThinkingFields(val);
55959
56414
  }
55960
56415
  }
56416
+ function systemInstructionOf(request2) {
56417
+ return request2 && typeof request2 === "object" ? request2.systemInstruction : void 0;
56418
+ }
55961
56419
  function safeStringify(obj) {
55962
56420
  ensureThinkingFields(obj);
55963
56421
  return JSON.stringify(obj, thinkingSafeReplacer);
@@ -56210,9 +56668,6 @@ function stripUnsupportedAntigravityFields(payload) {
56210
56668
  }
56211
56669
  }
56212
56670
  }
56213
- function isGeminiFunctionResponseTurn(content, wireModel) {
56214
- return wireModel.startsWith("gemini-") && content?.role === "model" && Array.isArray(content.parts) && content.parts.length > 0 && content.parts.every((part) => part?.functionResponse);
56215
- }
56216
56671
  function configureAntigravityToolCalling(payload) {
56217
56672
  delete payload.toolConfig;
56218
56673
  if (Array.isArray(payload.tools)) {
@@ -56634,7 +57089,7 @@ var openCode1WireLocation = {
56634
57089
  },
56635
57090
  logger: log14,
56636
57091
  sessionFingerprint: () => getSessionFingerprint(),
56637
- displayedThinkingHashes: sessionDisplayedThinkingHashes,
57092
+ displayedThinking: openCode1DisplayedThinking,
56638
57093
  cacheStats: { last: null }
56639
57094
  };
56640
57095
  function getLastCacheStats() {
@@ -56659,6 +57114,7 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56659
57114
  let sessionId;
56660
57115
  let needsSignedThinkingWarmup = false;
56661
57116
  let thinkingRecoveryMessage;
57117
+ let wireSystemInstruction;
56662
57118
  if (!isGenerativeLanguageRequest(input2)) {
56663
57119
  return {
56664
57120
  request: input2,
@@ -56787,13 +57243,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56787
57243
  normalizeNativeFunctionResponseRoles(req, effectiveModel);
56788
57244
  }
56789
57245
  for (const req of requestObjects) {
56790
- if (Array.isArray(req.contents)) {
56791
- const contents = req.contents;
56792
- const lastContent = contents[contents.length - 1];
56793
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
56794
- contents.push({ role: "user", parts: [{ text: "[Continue]" }] });
56795
- }
56796
- }
57246
+ if (Array.isArray(req.contents))
57247
+ appendAgyContinuation(req.contents, effectiveModel);
56797
57248
  if (Array.isArray(req.messages)) {
56798
57249
  const messages = req.messages;
56799
57250
  const lastMessage = messages[messages.length - 1];
@@ -56843,6 +57294,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
56843
57294
  }
56844
57295
  }
56845
57296
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
57297
+ wireSystemInstruction = {
57298
+ body,
57299
+ instruction: systemInstructionOf(wrappedBody.request)
57300
+ };
56846
57301
  } else {
56847
57302
  const requestPayload = { ...parsedBody };
56848
57303
  if (isImageGenerationModel(effectiveModel) && isOpenCodeTitleGenerationRequest(requestPayload)) {
@@ -57229,15 +57684,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57229
57684
  wire.signatures.signatureStore.delete(signatureSessionKey);
57230
57685
  }
57231
57686
  }
57232
- if (Array.isArray(requestPayload.contents)) {
57233
- const lastContent = requestPayload.contents[requestPayload.contents.length - 1];
57234
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel) || lastContent?.role === "assistant") {
57235
- requestPayload.contents.push({
57236
- role: "user",
57237
- parts: [{ text: "[Continue]" }]
57238
- });
57239
- }
57240
- }
57687
+ if (Array.isArray(requestPayload.contents))
57688
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
57241
57689
  if (Array.isArray(requestPayload.messages)) {
57242
57690
  const lastMessage = requestPayload.messages[requestPayload.messages.length - 1];
57243
57691
  if (lastMessage?.role === "model" || lastMessage?.role === "assistant") {
@@ -57265,15 +57713,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57265
57713
  stripUnsupportedAntigravityFields(requestPayload);
57266
57714
  configureAntigravityToolCalling(requestPayload);
57267
57715
  normalizeNativeFunctionResponseRoles(requestPayload, effectiveModel);
57268
- if (Array.isArray(requestPayload.contents)) {
57269
- const lastContent = requestPayload.contents.at(-1);
57270
- if (lastContent?.role === "model" && !isGeminiFunctionResponseTurn(lastContent, effectiveModel)) {
57271
- requestPayload.contents.push({
57272
- role: "user",
57273
- parts: [{ text: "[Continue]" }]
57274
- });
57275
- }
57276
- }
57716
+ if (Array.isArray(requestPayload.contents))
57717
+ appendAgyContinuation(requestPayload.contents, effectiveModel);
57277
57718
  }
57278
57719
  const effectiveProjectId = projectId?.trim() || ANTIGRAVITY_DEFAULT_PROJECT_ID;
57279
57720
  resolvedProjectId = effectiveProjectId;
@@ -57298,6 +57739,10 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57298
57739
  requestType: "agent"
57299
57740
  };
57300
57741
  body = safeStringify(orderAntigravityEnvelope(wrappedBody));
57742
+ wireSystemInstruction = {
57743
+ body,
57744
+ instruction: requestPayload.systemInstruction
57745
+ };
57301
57746
  }
57302
57747
  } catch {
57303
57748
  throw new Error("Failed to build Antigravity request body");
@@ -57341,7 +57786,8 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
57341
57786
  toolDebugSummary: toolDebugSummaries.slice(0, 20).join(" | "),
57342
57787
  needsSignedThinkingWarmup,
57343
57788
  headerStyle: "antigravity",
57344
- thinkingRecoveryMessage
57789
+ thinkingRecoveryMessage,
57790
+ ...wireSystemInstruction ? { wireSystemInstruction } : {}
57345
57791
  };
57346
57792
  }
57347
57793
  function prepareAntigravityRequest(...args) {
@@ -57459,7 +57905,7 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
57459
57905
  signatureSessionKey: sessionId,
57460
57906
  debugText,
57461
57907
  cacheSignatures,
57462
- displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinkingHashes : void 0
57908
+ displayedThinkingHashes: effectiveModel && isGemini3Model(effectiveModel) ? wire.displayedThinking.forSession(sessionId) : void 0
57463
57909
  // injectSyntheticThinking removed - keep_thinking now unified with debug via debugText
57464
57910
  }
57465
57911
  );
@@ -57820,10 +58266,10 @@ async function retainResponseLifetime(response, cancellation) {
57820
58266
  cancellation.release();
57821
58267
  throw error;
57822
58268
  }
57823
- let resolve33 = () => {
58269
+ let resolve34 = () => {
57824
58270
  };
57825
58271
  const settled = new Promise((done) => {
57826
- resolve33 = done;
58272
+ resolve34 = done;
57827
58273
  });
57828
58274
  let stopping = false;
57829
58275
  let finished = false;
@@ -57833,7 +58279,7 @@ async function retainResponseLifetime(response, cancellation) {
57833
58279
  finished = true;
57834
58280
  cancellation.signal.removeEventListener("abort", abort);
57835
58281
  cancellation.release();
57836
- resolve33();
58282
+ resolve34();
57837
58283
  };
57838
58284
  const abort = () => {
57839
58285
  if (finished || stopping) return;
@@ -57902,8 +58348,8 @@ function createAfterHandoff(work, signals, onFailure) {
57902
58348
  let running = false;
57903
58349
  let resolveCompletion = () => {
57904
58350
  };
57905
- const completion = new Promise((resolve33) => {
57906
- resolveCompletion = resolve33;
58351
+ const completion = new Promise((resolve34) => {
58352
+ resolveCompletion = resolve34;
57907
58353
  });
57908
58354
  const finish = () => {
57909
58355
  if (finished) return;
@@ -57950,14 +58396,14 @@ function createAfterHandoff(work, signals, onFailure) {
57950
58396
  };
57951
58397
  }
57952
58398
  function publishResponse(dispatch) {
57953
- return new Promise((resolve33, reject) => {
58399
+ return new Promise((resolve34, reject) => {
57954
58400
  let acknowledge;
57955
58401
  void Promise.resolve().then(
57956
58402
  () => dispatch((callback) => {
57957
58403
  acknowledge = callback;
57958
58404
  })
57959
58405
  ).then((response) => {
57960
- resolve33(response);
58406
+ resolve34(response);
57961
58407
  acknowledge?.();
57962
58408
  }, reject);
57963
58409
  });
@@ -58048,16 +58494,21 @@ function createAuthLoader({
58048
58494
  };
58049
58495
  let storeOpening = null;
58050
58496
  const openStore = () => {
58051
- storeOpening ??= deps.openAccountStore().then((opening) => {
58052
- if (opening.status === "ready") {
58053
- lifecycle.register({
58054
- async dispose() {
58055
- await opening.repository.dispose();
58056
- }
58057
- });
58058
- }
58059
- return opening;
58060
- });
58497
+ if (!storeOpening) {
58498
+ const attempt = deps.openAccountStore().then((opening) => {
58499
+ if (opening.status === "ready") {
58500
+ lifecycle.register({
58501
+ async dispose() {
58502
+ await opening.repository.dispose();
58503
+ }
58504
+ });
58505
+ } else if (opening.status === "refused" && opening.admission.status === "busy" && opening.admission.retryable && storeOpening === attempt) {
58506
+ storeOpening = null;
58507
+ }
58508
+ return opening;
58509
+ });
58510
+ storeOpening = attempt;
58511
+ }
58061
58512
  return storeOpening;
58062
58513
  };
58063
58514
  const initializeFreshStore = async () => {
@@ -58555,16 +59006,10 @@ var BackgroundQuotaRefresh = class {
58555
59006
  if (this.timer.unref) this.timer.unref();
58556
59007
  }
58557
59008
  async runTick() {
58558
- if (this.mayRun && !await this.mayRun()) {
59009
+ if (!await this.canRun()) {
58559
59010
  if (!this.disposed) this.scheduleNext(this.jitteredInterval());
58560
59011
  return;
58561
59012
  }
58562
- if (this.disposed) return;
58563
- const freshnessThresholdMs = Math.max(
58564
- this.intervalMs - MIN_INTERVAL_MS,
58565
- Math.floor(this.intervalMs / 2)
58566
- );
58567
- const ageMs = this.now() - this.snapshots.lastCheckedAt();
58568
59013
  const lockPath = this.snapshots.pollLockPath;
58569
59014
  let lock = null;
58570
59015
  try {
@@ -58582,9 +59027,7 @@ var BackgroundQuotaRefresh = class {
58582
59027
  return;
58583
59028
  }
58584
59029
  try {
58585
- if (this.disposed || this.mayRun && !await this.mayRun()) return;
58586
- if (ageMs >= freshnessThresholdMs) await this.refresh();
58587
- else await this.refreshTierSlot();
59030
+ if (await this.canRun()) await this.refresh();
58588
59031
  } finally {
58589
59032
  await lock.release().catch(() => {
58590
59033
  });
@@ -58593,22 +59036,36 @@ var BackgroundQuotaRefresh = class {
58593
59036
  this.scheduleNext(this.jitteredInterval());
58594
59037
  }
58595
59038
  }
59039
+ async canRun() {
59040
+ return !this.disposed && (!this.mayRun || await this.mayRun()) && !this.disposed;
59041
+ }
58596
59042
  async refresh() {
58597
59043
  const refreshedQuota = await this.refreshQuota();
58598
- if (!this.disposed && (!this.mayRun || await this.mayRun()))
58599
- await this.refreshTierSlot();
58600
- if (refreshedQuota) await this.pushSnapshot();
59044
+ if (await this.canRun()) await this.refreshTierSlot();
59045
+ if (refreshedQuota && await this.canRun()) await this.pushSnapshot();
58601
59046
  }
58602
59047
  async refreshQuota() {
58603
- if (this.disposed || this.mayRun && !await this.mayRun()) return false;
58604
59048
  const manager = this.getAccountManager();
58605
59049
  if (!manager) return false;
58606
- const accounts = manager.getAccountsForQuotaCheck();
59050
+ const observed = await (manager.readAccountsForQuotaPoll?.() ?? this.localObservations(manager));
59051
+ if (!await this.canRun()) return false;
59052
+ const now2 = this.now();
59053
+ const freshnessThresholdMs = Math.max(
59054
+ this.intervalMs - MIN_INTERVAL_MS,
59055
+ Math.floor(this.intervalMs / 2)
59056
+ );
59057
+ const accounts = observed.filter(
59058
+ ({ enabled, cachedQuotaUpdatedAt: at }) => enabled !== false && (at === void 0 || !Number.isFinite(at) || at <= 0 || at > now2 || now2 - at >= freshnessThresholdMs)
59059
+ );
58607
59060
  if (accounts.length === 0) return false;
58608
59061
  let results;
58609
59062
  try {
59063
+ const indexes = new Map(
59064
+ accounts.map((account, index) => [account, index])
59065
+ );
58610
59066
  results = await this.quotaManager.refreshAccounts(accounts, {
58611
- indexFor: (account) => accounts.indexOf(account),
59067
+ indexFor: (account) => indexes.get(account),
59068
+ publishSidebar: false,
58612
59069
  // Do not force: the quota manager's per-account dedup and backoff
58613
59070
  // apply — an account that already refreshed recently is skipped.
58614
59071
  force: false
@@ -58616,7 +59073,7 @@ var BackgroundQuotaRefresh = class {
58616
59073
  } catch {
58617
59074
  return false;
58618
59075
  }
58619
- if (this.disposed) return false;
59076
+ if (!await this.canRun()) return false;
58620
59077
  const liveAccounts = manager.getAccounts();
58621
59078
  const liveIndexByToken = /* @__PURE__ */ new Map();
58622
59079
  for (const entry of liveAccounts) {
@@ -58625,7 +59082,8 @@ var BackgroundQuotaRefresh = class {
58625
59082
  let anyUpdated = false;
58626
59083
  for (let i = 0; i < results.length; i++) {
58627
59084
  const result = results[i];
58628
- if (result?.status !== "ok" || !result.quota?.groups) continue;
59085
+ if (result?.status !== "ok" || !result.quota?.groups || result.checkedAt === void 0)
59086
+ continue;
58629
59087
  const candidateTokens = [
58630
59088
  result.updatedAccount?.refreshToken,
58631
59089
  accounts[i]?.refreshToken
@@ -58634,7 +59092,13 @@ var BackgroundQuotaRefresh = class {
58634
59092
  if (liveIndex === void 0) continue;
58635
59093
  const liveToken = liveAccounts[liveIndex]?.parts.refreshToken;
58636
59094
  if (!liveToken) continue;
58637
- manager.updateQuotaCache(liveIndex, result.quota.groups, liveToken);
59095
+ if (manager.updateQuotaCache(
59096
+ liveIndex,
59097
+ result.quota.groups,
59098
+ liveToken,
59099
+ result.checkedAt
59100
+ ) === false)
59101
+ continue;
58638
59102
  const uaTier = toCapturedTier(result.updatedAccount ?? {});
58639
59103
  if (uaTier !== void 0) {
58640
59104
  manager.applyUpdatedAccount(
@@ -58650,9 +59114,24 @@ var BackgroundQuotaRefresh = class {
58650
59114
  }
58651
59115
  anyUpdated = true;
58652
59116
  }
58653
- if (anyUpdated) manager.requestSaveToDisk();
59117
+ if (anyUpdated && await this.canRun()) {
59118
+ if (manager.saveToDisk) await manager.saveToDisk();
59119
+ else manager.requestSaveToDisk();
59120
+ }
58654
59121
  return true;
58655
59122
  }
59123
+ localObservations(manager) {
59124
+ const accounts = new Map(
59125
+ manager.getAccounts().map((row) => [row.parts.refreshToken, row])
59126
+ );
59127
+ return manager.getAccountsForQuotaCheck().map((target) => {
59128
+ const row = accounts.get(target.refreshToken);
59129
+ return {
59130
+ ...target,
59131
+ cachedQuotaUpdatedAt: row?.cachedQuota && row.cachedQuotaUpdatedAt
59132
+ };
59133
+ });
59134
+ }
58656
59135
  async refreshTierSlot() {
58657
59136
  if (this.disposed || !this.loadAccountTier) return;
58658
59137
  const manager = this.getAccountManager();
@@ -58677,7 +59156,7 @@ var BackgroundQuotaRefresh = class {
58677
59156
  if (!accountForTier) return;
58678
59157
  try {
58679
59158
  const tier = await this.loadAccountTier(accountForTier);
58680
- if (tier === null || this.disposed) return;
59159
+ if (tier === null || !await this.canRun()) return;
58681
59160
  const liveEntry = manager.getAccounts().find((entry) => entry.parts.refreshToken === refreshToken);
58682
59161
  if (!liveEntry) return;
58683
59162
  manager.applyUpdatedAccount(
@@ -58713,6 +59192,7 @@ var BackgroundQuotaRefresh = class {
58713
59192
  enabled: entry.enabled,
58714
59193
  coolingDownUntil: entry.coolingDownUntil,
58715
59194
  cachedQuota: entry.cachedQuota,
59195
+ cachedQuotaUpdatedAt: entry.cachedQuotaUpdatedAt,
58716
59196
  cachedQuotaAccountId: entry.cachedQuotaAccountId,
58717
59197
  // An account reorder changes which cached reading occupies an index.
58718
59198
  // Use a refresh-token-derived account ID to detect that mismatch
@@ -58976,12 +59456,12 @@ var BackgroundVaultQuotaRefresh = class {
58976
59456
  outcome.reason = "no-rows";
58977
59457
  return;
58978
59458
  }
58979
- const due = pool.selector.rows.some((row) => {
59459
+ const dueRoutes = pool.selector.rows.filter((row) => {
58980
59460
  const quota = quotaReadingForVaultRoute(row.route, state2);
58981
59461
  const at = quota?.cachedQuotaUpdatedAt;
58982
59462
  return quota?.cachedQuota == null || typeof at !== "number" || !Number.isFinite(at) || at < 0 || now2 - at >= threshold;
58983
- });
58984
- if (!due) {
59463
+ }).map((row) => row.route);
59464
+ if (dueRoutes.length === 0) {
58985
59465
  outcome.reason = "fresh";
58986
59466
  return;
58987
59467
  }
@@ -58990,6 +59470,7 @@ var BackgroundVaultQuotaRefresh = class {
58990
59470
  const report = await checkAndPublishVaultQuota(
58991
59471
  {
58992
59472
  pool,
59473
+ routes: dueRoutes,
58993
59474
  signal: controller.signal,
58994
59475
  now: this.now,
58995
59476
  onStage: (stage) => {
@@ -59635,15 +60116,15 @@ init_debug();
59635
60116
  // src/plugin/dependencies.ts
59636
60117
  init_dist();
59637
60118
  import { homedir as homedir16 } from "node:os";
59638
- import { join as join45 } from "node:path";
60119
+ import { join as join44 } from "node:path";
59639
60120
  function defaultFilesystemRoots() {
59640
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join45(homedir16(), ".config");
59641
- const xdgState2 = process.env.XDG_STATE_HOME ?? join45(homedir16(), ".local", "state");
60121
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join44(homedir16(), ".config");
60122
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join44(homedir16(), ".local", "state");
59642
60123
  return {
59643
60124
  projectRoot: process.cwd(),
59644
- userConfigRoot: join45(xdgConfig2, "opencode"),
59645
- sidebarStateRoot: join45(xdgState2, "cortexkit", "antigravity-auth"),
59646
- rpcRoot: join45(xdgState2, "cortexkit", "antigravity-auth", "rpc")
60125
+ userConfigRoot: join44(xdgConfig2, "opencode"),
60126
+ sidebarStateRoot: join44(xdgState2, "cortexkit", "antigravity-auth"),
60127
+ rpcRoot: join44(xdgState2, "cortexkit", "antigravity-auth", "rpc")
59647
60128
  };
59648
60129
  }
59649
60130
  function resolvePluginDependencies(overrides = {}) {
@@ -59672,10 +60153,10 @@ function resolvePluginDependencies(overrides = {}) {
59672
60153
  }
59673
60154
  async function defaultSleep(ms, signal) {
59674
60155
  if (ms <= 0) return;
59675
- await new Promise((resolve33, reject) => {
60156
+ await new Promise((resolve34, reject) => {
59676
60157
  const timer = setTimeout(() => {
59677
60158
  signal?.removeEventListener("abort", onAbort);
59678
- resolve33();
60159
+ resolve34();
59679
60160
  }, ms);
59680
60161
  timer.unref?.();
59681
60162
  const onAbort = () => {
@@ -59924,8 +60405,6 @@ function candidateView(candidates) {
59924
60405
  accounts.push({ account_id: accountId, credential_id: credentialId });
59925
60406
  }
59926
60407
  }
59927
- if (accounts.length === 0)
59928
- return void 0;
59929
60408
  const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
59930
60409
  `, "utf8")).sort(Buffer.compare);
59931
60410
  const hash2 = createHash22("sha256");
@@ -60002,8 +60481,8 @@ async function askRouting(input2) {
60002
60481
  return void 0;
60003
60482
  const requested = input2.deadlineMs ?? 1500;
60004
60483
  const deadlineMs = Number.isNaN(requested) ? 1500 : Math.min(2e3, Math.max(1, requested));
60005
- const expired = new Promise((resolve33) => {
60006
- timer = setTimeout(() => resolve33(void 0), deadlineMs);
60484
+ const expired = new Promise((resolve34) => {
60485
+ timer = setTimeout(() => resolve34(void 0), deadlineMs);
60007
60486
  timer.unref();
60008
60487
  });
60009
60488
  const cap = input2.holdWaitMaxS;
@@ -60017,7 +60496,7 @@ async function askRouting(input2) {
60017
60496
  request2.warm_credential = warmCredentialId;
60018
60497
  }
60019
60498
  const candidates = candidateView(input2.candidates);
60020
- if (candidates)
60499
+ if (candidates.accounts.length > 0 || request2.mode === "continue")
60021
60500
  request2.candidates = candidates;
60022
60501
  const pending = accountFor.call(handle, request2, { deadlineMs });
60023
60502
  if (!isObject2(pending) || typeof pending.then !== "function")
@@ -60393,7 +60872,7 @@ function createRetryState() {
60393
60872
  var MAX_WARMUP_SESSIONS = 1e3;
60394
60873
  var MAX_WARMUP_RETRIES = 2;
60395
60874
  function createWarmupState() {
60396
- const warmupAttemptedSessionIds = /* @__PURE__ */ new Set();
60875
+ const warmupAttemptCounts = /* @__PURE__ */ new Map();
60397
60876
  const warmupSucceededSessionIds = /* @__PURE__ */ new Set();
60398
60877
  let disposed = false;
60399
60878
  function trackAttempt(sessionId) {
@@ -60401,22 +60880,22 @@ function createWarmupState() {
60401
60880
  if (warmupSucceededSessionIds.has(sessionId)) {
60402
60881
  return false;
60403
60882
  }
60404
- if (warmupAttemptedSessionIds.size >= MAX_WARMUP_SESSIONS) {
60405
- const first = warmupAttemptedSessionIds.values().next().value;
60406
- if (first) {
60407
- warmupAttemptedSessionIds.delete(first);
60408
- warmupSucceededSessionIds.delete(first);
60409
- }
60410
- }
60411
60883
  const attempts2 = getAttemptCount(sessionId);
60412
60884
  if (attempts2 >= MAX_WARMUP_RETRIES) {
60413
60885
  return false;
60414
60886
  }
60415
- warmupAttemptedSessionIds.add(sessionId);
60887
+ if (attempts2 === 0 && warmupAttemptCounts.size >= MAX_WARMUP_SESSIONS) {
60888
+ const first = warmupAttemptCounts.keys().next().value;
60889
+ if (first !== void 0) {
60890
+ warmupAttemptCounts.delete(first);
60891
+ warmupSucceededSessionIds.delete(first);
60892
+ }
60893
+ }
60894
+ warmupAttemptCounts.set(sessionId, attempts2 + 1);
60416
60895
  return true;
60417
60896
  }
60418
60897
  function getAttemptCount(sessionId) {
60419
- return warmupAttemptedSessionIds.has(sessionId) ? 1 : 0;
60898
+ return warmupAttemptCounts.get(sessionId) ?? 0;
60420
60899
  }
60421
60900
  function markSuccess(sessionId) {
60422
60901
  if (disposed) return;
@@ -60426,12 +60905,14 @@ function createWarmupState() {
60426
60905
  if (first) warmupSucceededSessionIds.delete(first);
60427
60906
  }
60428
60907
  }
60429
- function clearWarmupAttempt(sessionId) {
60908
+ function refundAttempt(sessionId) {
60430
60909
  if (disposed) return;
60431
- warmupAttemptedSessionIds.delete(sessionId);
60910
+ const attempts2 = getAttemptCount(sessionId);
60911
+ if (attempts2 <= 1) warmupAttemptCounts.delete(sessionId);
60912
+ else warmupAttemptCounts.set(sessionId, attempts2 - 1);
60432
60913
  }
60433
60914
  function clear() {
60434
- warmupAttemptedSessionIds.clear();
60915
+ warmupAttemptCounts.clear();
60435
60916
  warmupSucceededSessionIds.clear();
60436
60917
  }
60437
60918
  function dispose() {
@@ -60446,7 +60927,7 @@ function createWarmupState() {
60446
60927
  trackAttempt,
60447
60928
  getAttemptCount,
60448
60929
  markSuccess,
60449
- clearWarmupAttempt,
60930
+ refundAttempt,
60450
60931
  clear,
60451
60932
  dispose
60452
60933
  };
@@ -60937,6 +61418,7 @@ function isTitleVaultRequest(kind, headers) {
60937
61418
  var FIRST_RETRY_DELAY_MS = 1e3;
60938
61419
  var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
60939
61420
  var ROUTING_ASK_DEADLINE_MS = 2e3;
61421
+ var FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS = 5;
60940
61422
  var REFUSAL_BODY_TIMEOUT_MS = 2e3;
60941
61423
  var REFUSAL_BODY_MAX_BYTES = 64 * 1024;
60942
61424
  async function readRefusalBody(response, deadline) {
@@ -60965,8 +61447,8 @@ async function readRefusalBody(response, deadline) {
60965
61447
  return false;
60966
61448
  }
60967
61449
  })(),
60968
- new Promise((resolve33) => {
60969
- timer = setTimeout(() => resolve33(false), REFUSAL_BODY_TIMEOUT_MS);
61450
+ new Promise((resolve34) => {
61451
+ timer = setTimeout(() => resolve34(false), REFUSAL_BODY_TIMEOUT_MS);
60970
61452
  })
60971
61453
  ])
60972
61454
  );
@@ -61082,7 +61564,7 @@ function formatWaitTime(ms) {
61082
61564
  return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;
61083
61565
  }
61084
61566
  function sleep4(ms, signal) {
61085
- return new Promise((resolve33, reject) => {
61567
+ return new Promise((resolve34, reject) => {
61086
61568
  if (signal?.aborted) {
61087
61569
  reject(
61088
61570
  signal.reason instanceof Error ? signal.reason : new Error("Aborted")
@@ -61092,7 +61574,7 @@ function sleep4(ms, signal) {
61092
61574
  const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
61093
61575
  const timeout = setTimeout(() => {
61094
61576
  cleanup2();
61095
- resolve33();
61577
+ resolve34();
61096
61578
  }, timerMs);
61097
61579
  const onAbort = () => {
61098
61580
  cleanup2();
@@ -61165,15 +61647,16 @@ function createLocalQuotaRefresh(accountManager, quotaManager, log19) {
61165
61647
  ...signal ? { signal } : {}
61166
61648
  });
61167
61649
  if (signal?.aborted) return;
61168
- if (result.status === "ok" && result.quota?.groups) {
61650
+ if (result.status === "ok" && result.quota?.groups && result.checkedAt !== void 0) {
61169
61651
  const currentIndex = accountManager.getAccounts().indexOf(account);
61170
61652
  if (currentIndex === -1) return;
61171
- accountManager.updateQuotaCache(
61653
+ if (accountManager.updateQuotaCache(
61172
61654
  currentIndex,
61173
61655
  result.quota.groups,
61174
- expectedRefreshToken
61175
- );
61176
- accountManager.requestSaveToDisk();
61656
+ expectedRefreshToken,
61657
+ result.checkedAt
61658
+ ))
61659
+ accountManager.requestSaveToDisk();
61177
61660
  }
61178
61661
  } catch (err) {
61179
61662
  log19.debug(
@@ -61299,6 +61782,18 @@ function createRequestExecutor(deps) {
61299
61782
  let retired = false;
61300
61783
  let drainPromise;
61301
61784
  let disposePromise;
61785
+ let warnedConditionReceipt = false;
61786
+ const runVaultCondition = (operation) => {
61787
+ void Promise.resolve().then(operation).catch((error) => {
61788
+ if (warnedConditionReceipt || !(error instanceof Error) || !("kind" in error) || error.kind !== "no-receipt")
61789
+ return;
61790
+ warnedConditionReceipt = true;
61791
+ try {
61792
+ log19.warn("vault-condition-no-receipt");
61793
+ } catch {
61794
+ }
61795
+ });
61796
+ };
61302
61797
  const reportVault401 = (admission, status) => {
61303
61798
  if (!admission || status !== 401) return;
61304
61799
  void Promise.resolve().then(() => admission.report401(status)).catch((error) => {
@@ -61410,6 +61905,7 @@ function createRequestExecutor(deps) {
61410
61905
  } : void 0;
61411
61906
  const isChildRequest = requestSessionIdentity.parentSessionId !== null;
61412
61907
  let physicalSendCount = 0;
61908
+ let emptyResponseAttempts = 0;
61413
61909
  if (accountManager.getAccountCount() === 0) {
61414
61910
  const urlString2 = typeof input2 === "string" ? input2 : toUrlString(input2);
61415
61911
  const modelFromUrl = extractModelFromUrl(urlString2) ?? "unknown";
@@ -61522,6 +62018,7 @@ function createRequestExecutor(deps) {
61522
62018
  }
61523
62019
  };
61524
62020
  let accountSwitchCount = 0;
62021
+ let capacityExhaustedSelections = 0;
61525
62022
  let unconfirmedRetries = 0;
61526
62023
  const maxAccountSwitches = config.max_account_switches ?? 2;
61527
62024
  let previousAccountIndex = -1;
@@ -61533,6 +62030,7 @@ function createRequestExecutor(deps) {
61533
62030
  let routingPlacementConsidered = false;
61534
62031
  let routedCandidate;
61535
62032
  let continueRouting;
62033
+ let continueOnlyLogin = false;
61536
62034
  const refusedRoutes = /* @__PURE__ */ new Map();
61537
62035
  let routingTitle = false;
61538
62036
  let routingWaitMs = 0;
@@ -61600,10 +62098,12 @@ function createRequestExecutor(deps) {
61600
62098
  const choice = routedCandidate;
61601
62099
  routedCandidate = void 0;
61602
62100
  const exhausted = continueRouting;
62101
+ const onlyLoginContinuation = continueOnlyLogin;
61603
62102
  continueRouting = void 0;
62103
+ continueOnlyLogin = false;
61604
62104
  if (exhausted) refusedRoutes.set(routingIdentityKey(exhausted), exhausted);
61605
62105
  const accountCount = accountManager.getAccountCount();
61606
- if (accountCount === 0) {
62106
+ if (accountCount === 0 && !onlyLoginContinuation) {
61607
62107
  if (choice) return failedRoutedPick();
61608
62108
  return createNoAccountResponse(
61609
62109
  "No Antigravity accounts available. Run `opencode auth login`.",
@@ -61791,7 +62291,7 @@ function createRequestExecutor(deps) {
61791
62291
  const canHold = !!holdCandidate && candidates.some(
61792
62292
  (candidate) => routingIdentityKey(candidate) === holdCandidate
61793
62293
  );
61794
- const answer = await deadline.wait(() => {
62294
+ const ask = () => deadline.wait(() => {
61795
62295
  const input3 = {
61796
62296
  sessionId: accountSessionIdentity.id,
61797
62297
  provider: "antigravity",
@@ -61813,9 +62313,21 @@ function createRequestExecutor(deps) {
61813
62313
  } : input3
61814
62314
  );
61815
62315
  });
62316
+ let answer = await ask();
62317
+ const firstRefusal = !exhausted && answer && "refused" in answer ? answer.refused : void 0;
62318
+ if (firstRefusal?.code === "account_selection_refused" && firstRefusal.retryAfterSecs !== void 0 && firstRefusal.retryAfterSecs <= FIRST_PLACEMENT_REFUSAL_MAX_RETRY_SECS) {
62319
+ await routingSleep(
62320
+ firstRefusal.retryAfterSecs * 1e3,
62321
+ "account_free"
62322
+ );
62323
+ checkAborted();
62324
+ answer = await ask();
62325
+ }
61816
62326
  checkAborted();
61817
62327
  if (answer && "refused" in answer)
61818
62328
  return routingRefusalResponse(answer.refused);
62329
+ if (!answer && onlyLoginContinuation && candidates.length === 0)
62330
+ return failedRoutedPick();
61819
62331
  if (exhausted && answer?.hold) {
61820
62332
  if (!canHold || routingIdentityKey(answer.candidate) !== holdCandidate)
61821
62333
  return failedRoutedPick();
@@ -62288,12 +62800,14 @@ function createRequestExecutor(deps) {
62288
62800
  streaming: true,
62289
62801
  projectId
62290
62802
  });
62803
+ let warmupDispatched = false;
62291
62804
  try {
62292
62805
  pushDebug("thinking-warmup: start");
62293
62806
  const warmupSend = await credentialForAuxiliarySend(
62294
62807
  warmupInit,
62295
62808
  projectId
62296
62809
  );
62810
+ warmupDispatched = true;
62297
62811
  const warmupResponse = await sendPhysical(
62298
62812
  warmupUrl,
62299
62813
  warmupSend.init,
@@ -62318,7 +62832,7 @@ function createRequestExecutor(deps) {
62318
62832
  warmupState.markSuccess(prepared.sessionId);
62319
62833
  pushDebug("thinking-warmup: done");
62320
62834
  } catch (error) {
62321
- warmupState.clearWarmupAttempt(prepared.sessionId);
62835
+ if (!warmupDispatched) warmupState.refundAttempt(prepared.sessionId);
62322
62836
  if (error instanceof PreResponseTimeoutError) throw error;
62323
62837
  checkAborted();
62324
62838
  if (isLocalGrantError(error)) throw error;
@@ -62651,9 +63165,9 @@ function createRequestExecutor(deps) {
62651
63165
  const routed429 = response.status === 429 ? routedIdentity : void 0;
62652
63166
  if (response.status === 429 && rateLimitReason === "UNKNOWN") {
62653
63167
  await logResponseBody2(debugContext, response, 429);
62654
- const outgoing = JSON.parse(String(prepared.init.body));
63168
+ const carried = prepared.wireSystemInstruction;
62655
63169
  const recognised = systemInstructionHasHarnessIdentity(
62656
- outgoing.request?.systemInstruction
63170
+ carried && carried.body === prepared.init.body ? carried.instruction : JSON.parse(String(prepared.init.body)).request?.systemInstruction
62657
63171
  );
62658
63172
  if (recognised) {
62659
63173
  void response.body?.cancel().catch(() => {
@@ -62777,10 +63291,19 @@ function createRequestExecutor(deps) {
62777
63291
  i -= 1;
62778
63292
  continue;
62779
63293
  }
63294
+ retainHttpFailure(response);
63295
+ capacityExhaustedSelections++;
63296
+ if (capacityExhaustedSelections > 1) {
63297
+ pushDebug(
63298
+ `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted again after one account switch, giving up`
63299
+ );
63300
+ return terminalMainAttemptFailure(
63301
+ "Antigravity has no capacity for this model right now"
63302
+ );
63303
+ }
62780
63304
  pushDebug(
62781
63305
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
62782
63306
  );
62783
- retainHttpFailure(response);
62784
63307
  shouldSwitchAccount = true;
62785
63308
  break;
62786
63309
  }
@@ -62926,6 +63449,10 @@ function createRequestExecutor(deps) {
62926
63449
  i -= 1;
62927
63450
  continue;
62928
63451
  }
63452
+ if (routed429 && exhaustion) {
63453
+ const { accountId, credentialId } = routed429;
63454
+ continueRouting = { accountId, credentialId, ...exhaustion };
63455
+ }
62929
63456
  const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
62930
63457
  if (accountCount > 1) {
62931
63458
  const quotaMsg = reasonInfo.quotaResetTime ? ` (quota resets ${reasonInfo.quotaResetTime})` : ``;
@@ -62934,7 +63461,7 @@ function createRequestExecutor(deps) {
62934
63461
  "warning"
62935
63462
  );
62936
63463
  await sleep4(switchAccountDelayMs, abortSignal);
62937
- } else {
63464
+ } else if (!continueRouting || isHardEligible(account)) {
62938
63465
  const expBackoffMs = Math.min(
62939
63466
  FIRST_RETRY_DELAY_MS * 2 ** (backoff.attempt - 1),
62940
63467
  6e4
@@ -62951,10 +63478,6 @@ function createRequestExecutor(deps) {
62951
63478
  );
62952
63479
  }
62953
63480
  retainHttpFailure(response);
62954
- if (routed429 && exhaustion) {
62955
- const { accountId, credentialId } = routed429;
62956
- continueRouting = { accountId, credentialId, ...exhaustion };
62957
- }
62958
63481
  shouldSwitchAccount = true;
62959
63482
  break;
62960
63483
  }
@@ -62998,6 +63521,19 @@ function createRequestExecutor(deps) {
62998
63521
  () => response.clone().text().catch(() => "")
62999
63522
  );
63000
63523
  const extracted = errorBodyText === void 0 ? void 0 : classifyAccessError(errorBodyText);
63524
+ const served2 = sendAdmission;
63525
+ const reportCondition = (reason) => {
63526
+ if (credentials.domain !== "vault" || !served2?.reportCondition)
63527
+ return;
63528
+ const actionUrl = extracted?.structuredVerifyUrl;
63529
+ waitPolicy.vaultConditions.push(
63530
+ () => served2.reportCondition?.({
63531
+ reason,
63532
+ providerStatus: 403,
63533
+ ...actionUrl && { actionUrl }
63534
+ })
63535
+ );
63536
+ };
63001
63537
  if (routedIdentity && (extracted?.accountIneligible || extracted?.validationRequired)) {
63002
63538
  const { accountId, credentialId } = routedIdentity;
63003
63539
  continueRouting = {
@@ -63027,6 +63563,7 @@ function createRequestExecutor(deps) {
63027
63563
  trackers.health.recordFailure(account.index);
63028
63564
  retainHttpFailure(response);
63029
63565
  shouldSwitchAccount = true;
63566
+ reportCondition("provider_ineligible");
63030
63567
  break;
63031
63568
  }
63032
63569
  if (extracted?.validationRequired) {
@@ -63062,6 +63599,7 @@ function createRequestExecutor(deps) {
63062
63599
  trackers.health.recordFailure(account.index);
63063
63600
  retainHttpFailure(response);
63064
63601
  shouldSwitchAccount = true;
63602
+ reportCondition("provider_verification_required");
63065
63603
  break;
63066
63604
  }
63067
63605
  }
@@ -63141,8 +63679,7 @@ function createRequestExecutor(deps) {
63141
63679
  })
63142
63680
  );
63143
63681
  if (isEmptyResponseBody(bodyText)) {
63144
- const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
63145
- const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
63682
+ const currentAttempts = ++emptyResponseAttempts;
63146
63683
  pushDebug(
63147
63684
  `empty-response: attempt ${currentAttempts}/${maxAttempts}`
63148
63685
  );
@@ -63155,14 +63692,11 @@ function createRequestExecutor(deps) {
63155
63692
  await sleep4(retryDelayMs, abortSignal);
63156
63693
  continue;
63157
63694
  }
63158
- retryState.clearEmptyResponseAttempts();
63159
63695
  return createNativeGoogleErrorResponse({
63160
63696
  status: 502,
63161
63697
  reason: "empty_response"
63162
63698
  });
63163
63699
  }
63164
- const _emptyAttemptKeyClean = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
63165
- retryState.clearEmptyResponseAttempts();
63166
63700
  }
63167
63701
  const routingObservation = credentials.domain === "vault" && sendAdmission && sessionKey && response.ok && hasVaultRoutingAccessor() ? observeVaultUpstream(response, abortSignal) : void 0;
63168
63702
  const transformedResponse = await deadline.wait(
@@ -63199,7 +63733,7 @@ function createRequestExecutor(deps) {
63199
63733
  }
63200
63734
  if (apiRequestCount > 1) {
63201
63735
  pushDebug(
63202
- `[Quota] Total API requests for this user message: ${apiRequestCount} (${apiRequestCount - 1} retries)`
63736
+ `[Quota] Main-request responses on this account selection: ${apiRequestCount}`
63203
63737
  );
63204
63738
  }
63205
63739
  const dailyCounts = accountManager.getDailyRequestCounts(
@@ -63239,6 +63773,9 @@ function createRequestExecutor(deps) {
63239
63773
  const refresh = credentials.refreshQuotaAfterSuccess;
63240
63774
  waitPolicy.quota = (signal) => refresh(account, config.quota_refresh_interval_minutes, signal);
63241
63775
  }
63776
+ const served = sendAdmission;
63777
+ if (credentials.domain === "vault" && response.ok && transformedResponse.ok && served?.clearCondition)
63778
+ waitPolicy.vaultConditions.push(() => served.clearCondition?.());
63242
63779
  return routingObservation && credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor() && response.ok ? observeVaultServed(
63243
63780
  {
63244
63781
  sessionId: sessionKey,
@@ -63256,6 +63793,7 @@ function createRequestExecutor(deps) {
63256
63793
  trackers.token.refund(account.index);
63257
63794
  tokenConsumed = false;
63258
63795
  }
63796
+ deadline.resume();
63259
63797
  if (credentials.domain === "local" && localGrant?.captured.source === "store" && isLocalGrantError(error)) {
63260
63798
  if (error instanceof LocalGrantSupersededError && !localRecaptureUsed) {
63261
63799
  localRecaptureUsed = true;
@@ -63341,6 +63879,10 @@ function createRequestExecutor(deps) {
63341
63879
  }
63342
63880
  if (shouldSwitchAccount) {
63343
63881
  if (switchedForUnconfirmed) continue;
63882
+ if (accountCount === 1 && continueRouting && (continueRouting.limitWindow === "signed_out" || !isHardEligible(account))) {
63883
+ continueOnlyLogin = true;
63884
+ continue;
63885
+ }
63344
63886
  accountSwitchCount++;
63345
63887
  if (accountSwitchCount > maxAccountSwitches) {
63346
63888
  pushDebug(
@@ -63409,7 +63951,11 @@ function createRequestExecutor(deps) {
63409
63951
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
63410
63952
  () => log19.debug("post-response-advisory-work-failed")
63411
63953
  );
63412
- const waitPolicy = {};
63954
+ const waitPolicy = { vaultConditions: [] };
63955
+ const publishVaultConditions = () => {
63956
+ for (const operation of waitPolicy.vaultConditions.splice(0))
63957
+ runVaultCondition(operation);
63958
+ };
63413
63959
  const selectedCredentials = /* @__PURE__ */ new Set();
63414
63960
  const selectedProjectIds = /* @__PURE__ */ new Set();
63415
63961
  const redactFailure = (error) => {
@@ -63482,7 +64028,21 @@ function createRequestExecutor(deps) {
63482
64028
  cancellation.release();
63483
64029
  throw redactFailure(error);
63484
64030
  }
63485
- ).catch((error) => {
64031
+ ).then((response) => {
64032
+ if (waitPolicy.vaultConditions.length > 0) {
64033
+ if (requestOptions?.onResponseHandoff) {
64034
+ try {
64035
+ requestOptions.onResponseHandoff(publishVaultConditions);
64036
+ return response;
64037
+ } catch {
64038
+ }
64039
+ }
64040
+ setImmediate(publishVaultConditions);
64041
+ }
64042
+ return response;
64043
+ }).catch((error) => {
64044
+ if (waitPolicy.vaultConditions.length > 0)
64045
+ setImmediate(publishVaultConditions);
63486
64046
  handoff.cancel();
63487
64047
  deadline.dispose();
63488
64048
  cancellation.release();
@@ -64183,8 +64743,8 @@ function createPluginLifecycle(options) {
64183
64743
  };
64184
64744
  let failDisposal = () => {
64185
64745
  };
64186
- disposal = new Promise((resolve33, reject) => {
64187
- finishDisposal = resolve33;
64746
+ disposal = new Promise((resolve34, reject) => {
64747
+ finishDisposal = resolve34;
64188
64748
  failDisposal = reject;
64189
64749
  });
64190
64750
  void (async () => {
@@ -64372,7 +64932,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
64372
64932
  // Diagnostics. Before the move they load from and write to the
64373
64933
  // project or user antigravity.json through the operator writer.
64374
64934
  operator: () => createOperatorSettingsController({
64375
- projectConfigPath: join46(directory, ".opencode", "antigravity.json"),
64935
+ projectConfigPath: join45(directory, ".opencode", "antigravity.json"),
64376
64936
  // getUserConfigPath() already returns the full file path including
64377
64937
  // 'antigravity.json' — do NOT join again or the path double-nests
64378
64938
  // into <dir>/antigravity.json/antigravity.json.
@@ -64434,7 +64994,7 @@ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2
64434
64994
  await drainSidebarWrites();
64435
64995
  }
64436
64996
  });
64437
- const accountFile = resolve32(accountFileForVault());
64997
+ const accountFile = resolve33(accountFileForVault());
64438
64998
  const vaultFolder = await prepareVaultFolder({ accountFile });
64439
64999
  const unavailableMessage = vaultFolder.refusal?.message ?? VAULT_ACCOUNT_REMEDY;
64440
65000
  let vaultQuotaPoller;