@cortexkit/opencode-antigravity-auth 3.0.22 → 3.0.24

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 (60) hide show
  1. package/dist/cli.js +321 -204
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +68 -43
  4. package/dist/index.js +547 -351
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +75 -50
  7. package/dist/server.js +690 -386
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/auth-method-labels.d.ts +1 -0
  11. package/dist/src/auth-method-labels.d.ts.map +1 -1
  12. package/dist/src/auth-method-labels.js +1 -0
  13. package/dist/src/auth-method-labels.js.map +1 -1
  14. package/dist/src/ga/server/auth.d.ts.map +1 -1
  15. package/dist/src/ga/server/auth.js +63 -21
  16. package/dist/src/ga/server/auth.js.map +1 -1
  17. package/dist/src/ga/server/pool-login.d.ts +4 -0
  18. package/dist/src/ga/server/pool-login.d.ts.map +1 -1
  19. package/dist/src/ga/server/pool-login.js +22 -1
  20. package/dist/src/ga/server/pool-login.js.map +1 -1
  21. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  22. package/dist/src/plugin/ga-location-services.js +42 -4
  23. package/dist/src/plugin/ga-location-services.js.map +1 -1
  24. package/dist/src/plugin/shared/request-services.d.ts +3 -0
  25. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  26. package/dist/src/plugin/shared/request-services.js +17 -3
  27. package/dist/src/plugin/shared/request-services.js.map +1 -1
  28. package/dist/src/plugin/shared/vault-routing.d.ts +6 -3
  29. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  30. package/dist/src/plugin/shared/vault-routing.js +12 -12
  31. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  32. package/dist/src/runtime-layout.d.ts.map +1 -1
  33. package/dist/src/runtime-layout.js +14 -3
  34. package/dist/src/runtime-layout.js.map +1 -1
  35. package/dist/src/setup.d.ts.map +1 -1
  36. package/dist/src/setup.js +38 -4
  37. package/dist/src/setup.js.map +1 -1
  38. package/dist/src/vault-folder.d.ts.map +1 -1
  39. package/dist/src/vault-folder.js +51 -14
  40. package/dist/src/vault-folder.js.map +1 -1
  41. package/dist/src/version-fence.d.ts +5 -0
  42. package/dist/src/version-fence.d.ts.map +1 -1
  43. package/dist/src/version-fence.js +64 -7
  44. package/dist/src/version-fence.js.map +1 -1
  45. package/dist/types/src/auth-method-labels.d.ts +1 -0
  46. package/dist/types/src/auth-method-labels.d.ts.map +1 -1
  47. package/dist/types/src/ga/server/auth.d.ts.map +1 -1
  48. package/dist/types/src/ga/server/pool-login.d.ts +4 -0
  49. package/dist/types/src/ga/server/pool-login.d.ts.map +1 -1
  50. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  51. package/dist/types/src/plugin/shared/request-services.d.ts +3 -0
  52. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  53. package/dist/types/src/plugin/shared/vault-routing.d.ts +6 -3
  54. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  55. package/dist/types/src/runtime-layout.d.ts.map +1 -1
  56. package/dist/types/src/setup.d.ts.map +1 -1
  57. package/dist/types/src/vault-folder.d.ts.map +1 -1
  58. package/dist/types/src/version-fence.d.ts +5 -0
  59. package/dist/types/src/version-fence.d.ts.map +1 -1
  60. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1628,10 +1628,10 @@ async function privateDirectory(path5) {
1628
1628
  if (errno(error) !== "EEXIST")
1629
1629
  throw error;
1630
1630
  }
1631
- const stat15 = await lstat2(path5);
1632
- if (!stat15.isDirectory() || stat15.isSymbolicLink())
1631
+ const stat16 = await lstat2(path5);
1632
+ if (!stat16.isDirectory() || stat16.isSymbolicLink())
1633
1633
  throw new AccountMigrationError("successor directory is not a regular directory");
1634
- privateMode(stat15.mode, 448);
1634
+ privateMode(stat16.mode, 448);
1635
1635
  if (windowsPrivateFiles)
1636
1636
  await verifySafeDirectory(path5);
1637
1637
  if (!sameFilesystemPath(await realpath(path5), path5))
@@ -6870,8 +6870,11 @@ var init_account_selector = __esm({
6870
6870
  rateLimitResetTimes: { ...a.rateLimitResetTimes }
6871
6871
  }));
6872
6872
  }
6873
- getEffectiveSoftQuotaThreshold(thresholdPercent) {
6874
- return this.getEnabledAccounts().length > 1 ? thresholdPercent : 100;
6873
+ getEligibleAccounts(excludeIndexes) {
6874
+ return this.accounts.filter((a) => a.enabled !== false && a.accountIneligible !== true && a.verificationRequired !== true && !excludeIndexes?.has(a.index));
6875
+ }
6876
+ getEffectiveSoftQuotaThreshold(thresholdPercent, excludeIndexes) {
6877
+ return this.getEligibleAccounts(excludeIndexes).length > 1 ? thresholdPercent : 100;
6875
6878
  }
6876
6879
  getRequestSessionState(identity3) {
6877
6880
  const now = this.now();
@@ -6974,7 +6977,7 @@ var init_account_selector = __esm({
6974
6977
  const currentIndex = this.getActiveIndex(family, identity3);
6975
6978
  if (currentIndex >= 0 && currentIndex < this.accounts.length) {
6976
6979
  const account = this.accounts[currentIndex] ?? null;
6977
- if (account && account.enabled !== false) {
6980
+ if (account && account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true) {
6978
6981
  return account;
6979
6982
  }
6980
6983
  }
@@ -7017,7 +7020,7 @@ var init_account_selector = __esm({
7017
7020
  }
7018
7021
  getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity3, excludeIndexes) {
7019
7022
  const quotaKey = getQuotaKey(family, model);
7020
- const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent);
7023
+ const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent, excludeIndexes);
7021
7024
  if (identity3) {
7022
7025
  const pinned = this.getCurrentAccountForFamily(family, identity3);
7023
7026
  if (pinned) {
@@ -7040,7 +7043,7 @@ var init_account_selector = __esm({
7040
7043
  if (strategy === "hybrid") {
7041
7044
  const healthTracker = this.healthTracker;
7042
7045
  const tokenTracker = this.tokenTracker;
7043
- const eligibleAccounts = this.preferAccountOutsideParent(this.accounts.filter((acc) => acc.enabled !== false && !excludeIndexes?.has(acc.index)), family, identity3);
7046
+ const eligibleAccounts = this.preferAccountOutsideParent(this.accounts.filter((acc) => acc.enabled !== false && acc.accountIneligible !== true && acc.verificationRequired !== true && !excludeIndexes?.has(acc.index)), family, identity3);
7044
7047
  const accountsWithMetrics = eligibleAccounts.map((acc) => {
7045
7048
  clearExpiredRateLimits(acc, this.now);
7046
7049
  return {
@@ -7097,10 +7100,10 @@ var init_account_selector = __esm({
7097
7100
  return next;
7098
7101
  }
7099
7102
  getNextForFamily(family, model, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity3, excludeIndexes) {
7100
- const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent);
7103
+ const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent, excludeIndexes);
7101
7104
  const allAvailable = this.accounts.filter((account2) => {
7102
7105
  clearExpiredRateLimits(account2, this.now);
7103
- return account2.enabled !== false && !excludeIndexes?.has(account2.index) && !isRateLimitedForFamily(account2, family, this.now, model) && !isOverSoftQuotaThreshold(account2, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model) && !this.isAccountCoolingDown(account2);
7106
+ return account2.enabled !== false && account2.accountIneligible !== true && account2.verificationRequired !== true && !excludeIndexes?.has(account2.index) && !isRateLimitedForFamily(account2, family, this.now, model) && !isOverSoftQuotaThreshold(account2, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model) && !this.isAccountCoolingDown(account2);
7104
7107
  });
7105
7108
  const available = this.preferAccountOutsideParent(allAvailable, family, identity3);
7106
7109
  if (available.length === 0) {
@@ -7286,7 +7289,7 @@ var init_account_selector = __esm({
7286
7289
  getFreshAccountsForQuota(quotaKey, family, model) {
7287
7290
  return this.accounts.filter((acc) => {
7288
7291
  clearExpiredRateLimits(acc, this.now);
7289
- return acc.enabled !== false && this.isFreshForQuota(acc, quotaKey) && !isRateLimitedForFamily(acc, family, this.now, model) && !this.isAccountCoolingDown(acc);
7292
+ return acc.enabled !== false && acc.accountIneligible !== true && acc.verificationRequired !== true && this.isFreshForQuota(acc, quotaKey) && !isRateLimitedForFamily(acc, family, this.now, model) && !this.isAccountCoolingDown(acc);
7290
7293
  });
7291
7294
  }
7292
7295
  isRateLimited(account, family, model) {
@@ -7422,12 +7425,40 @@ var init_account_selector = __esm({
7422
7425
  }
7423
7426
  return true;
7424
7427
  }
7425
- getMinWaitTimeForFamily(family, model) {
7428
+ /**
7429
+ * Calculates the minimum wait time in milliseconds across eligible accounts
7430
+ * for a given model family (and optional model).
7431
+ *
7432
+ * Note: Returning `0` can mean either:
7433
+ * 1. No eligible candidates exist in the pool, OR
7434
+ * 2. At least one eligible candidate is immediately usable without waiting.
7435
+ * Callers must distinguish "no eligible candidates" from "zero wait time"
7436
+ * by inspecting candidate pool availability / eligibility directly.
7437
+ *
7438
+ * @param family Model family (e.g., 'claude', 'gemini')
7439
+ * @param model Optional model name for per-model rate limits
7440
+ * @param eligibleIndexes Optional set of account indexes permitted for this request
7441
+ * @param includeCooldown Whether to factor in `coolingDownUntil` alongside quota rate limits
7442
+ * @returns Minimum wait duration in milliseconds, or 0 if immediately usable or no candidates
7443
+ */
7444
+ getMinWaitTimeForFamily(family, model, eligibleIndexes, includeCooldown = false) {
7426
7445
  const now = this.now();
7427
- const waits = this.accounts.filter((a) => a.enabled !== false).map((a) => {
7446
+ const waits = this.accounts.filter((a) => {
7447
+ if (a.enabled === false)
7448
+ return false;
7449
+ if (a.accountIneligible === true || a.verificationRequired === true) {
7450
+ return false;
7451
+ }
7452
+ if (eligibleIndexes !== void 0 && eligibleIndexes !== null) {
7453
+ if (!eligibleIndexes.has(a.index))
7454
+ return false;
7455
+ }
7456
+ return true;
7457
+ }).map((a) => {
7428
7458
  clearExpiredRateLimits(a, this.now);
7429
7459
  const modelReset = model ? a.rateLimitResetTimes[getQuotaKey(family, model)] : void 0;
7430
- return Math.max(0, (a.rateLimitResetTimes[family] ?? now) - now, (modelReset ?? now) - now);
7460
+ const cooldownWait = includeCooldown && a.coolingDownUntil !== void 0 && a.coolingDownUntil > now ? a.coolingDownUntil - now : 0;
7461
+ return Math.max(0, (a.rateLimitResetTimes[family] ?? now) - now, (modelReset ?? now) - now, cooldownWait);
7431
7462
  });
7432
7463
  return waits.length > 0 ? Math.min(...waits) : 0;
7433
7464
  }
@@ -7622,36 +7653,42 @@ var init_account_selector = __esm({
7622
7653
  }
7623
7654
  return oldest;
7624
7655
  }
7625
- areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
7656
+ /**
7657
+ * Check whether all eligible accounts (more than 1) are currently over the soft-quota threshold.
7658
+ * Returns false if thresholdPercent >= 100 or if <= 1 eligible account remains.
7659
+ */
7660
+ areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes) {
7626
7661
  if (thresholdPercent >= 100)
7627
7662
  return false;
7628
- const enabled = this.accounts.filter((a) => a.enabled !== false);
7629
- if (enabled.length <= 1)
7663
+ const eligible = this.accounts.filter((a) => a.enabled !== false && a.accountIneligible !== true && a.verificationRequired !== true && (eligibleIndexes == null || eligibleIndexes.has(a.index)));
7664
+ if (eligible.length <= 1)
7630
7665
  return false;
7631
- return enabled.every((a) => isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, this.now, model));
7666
+ return eligible.every((a) => isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, this.now, model));
7632
7667
  }
7633
7668
  /**
7634
- * Get minimum wait time until any account's soft quota resets.
7635
- * Returns 0 if any account is available (not over threshold).
7636
- * Returns the minimum resetTime across all over-threshold accounts.
7637
- * Returns null if no resetTime data is available.
7669
+ * Get minimum wait time until any eligible account's soft quota resets.
7670
+ * Operates over the eligible subset (enabled, non-ineligible, non-verification-required,
7671
+ * and present in `eligibleIndexes` when provided).
7672
+ * Returns null if no eligible accounts remain or no resetTime data is available.
7673
+ * Returns 0 if only 1 eligible account exists or any eligible account is below threshold.
7674
+ * Returns the minimum resetTime across all over-threshold eligible accounts.
7638
7675
  */
7639
- getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
7676
+ getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes) {
7640
7677
  if (thresholdPercent >= 100)
7641
7678
  return 0;
7642
- const enabled = this.accounts.filter((a) => a.enabled !== false);
7643
- if (enabled.length === 0)
7679
+ const eligible = this.accounts.filter((a) => a.enabled !== false && a.accountIneligible !== true && a.verificationRequired !== true && (eligibleIndexes == null || eligibleIndexes.has(a.index)));
7680
+ if (eligible.length === 0)
7644
7681
  return null;
7645
- if (enabled.length === 1)
7682
+ if (eligible.length === 1)
7646
7683
  return 0;
7647
- const available = enabled.filter((a) => !isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, this.now, model));
7684
+ const available = eligible.filter((a) => !isOverSoftQuotaThreshold(a, family, thresholdPercent, cacheTtlMs, this.now, model));
7648
7685
  if (available.length > 0)
7649
7686
  return 0;
7650
7687
  if (!model && family !== "claude")
7651
7688
  return null;
7652
7689
  const now = this.now();
7653
7690
  const waitTimes = [];
7654
- for (const acc of enabled) {
7691
+ for (const acc of eligible) {
7655
7692
  const quotaGroup = resolveQuotaGroup(family, model, acc.cachedQuota);
7656
7693
  const groupData = acc.cachedQuota?.[quotaGroup];
7657
7694
  if (groupData?.resetTime) {
@@ -8083,7 +8120,7 @@ function writeConsoleLog(level, ...args) {
8083
8120
  }
8084
8121
  function createLogger(module) {
8085
8122
  const service = `antigravity.${module}`;
8086
- const log16 = (level, message, extra) => {
8123
+ const log17 = (level, message, extra) => {
8087
8124
  if (_sink) {
8088
8125
  try {
8089
8126
  _sink({ service, level, message, extra });
@@ -8097,10 +8134,10 @@ function createLogger(module) {
8097
8134
  }
8098
8135
  };
8099
8136
  return {
8100
- debug: (message, extra) => log16("debug", message, extra),
8101
- info: (message, extra) => log16("info", message, extra),
8102
- warn: (message, extra) => log16("warn", message, extra),
8103
- error: (message, extra) => log16("error", message, extra)
8137
+ debug: (message, extra) => log17("debug", message, extra),
8138
+ info: (message, extra) => log17("info", message, extra),
8139
+ warn: (message, extra) => log17("warn", message, extra),
8140
+ error: (message, extra) => log17("error", message, extra)
8104
8141
  };
8105
8142
  }
8106
8143
  var ENV_CONSOLE_LOG, _sink;
@@ -9656,8 +9693,24 @@ var init_account_manager = __esm({
9656
9693
  expires: account.expires
9657
9694
  };
9658
9695
  }
9659
- getMinWaitTimeForFamily(family, model) {
9660
- return this.selection.getMinWaitTimeForFamily(family, model);
9696
+ /**
9697
+ * Calculates the minimum wait time in milliseconds across eligible accounts
9698
+ * for a given model family (and optional model).
9699
+ *
9700
+ * Note: Returning `0` can mean either:
9701
+ * 1. No eligible candidates exist in the pool, OR
9702
+ * 2. At least one eligible candidate is immediately usable without waiting.
9703
+ * Callers must distinguish "no eligible candidates" from "zero wait time"
9704
+ * by inspecting candidate pool availability / eligibility directly.
9705
+ *
9706
+ * @param family Model family (e.g., 'claude', 'gemini')
9707
+ * @param model Optional model name for per-model rate limits
9708
+ * @param eligibleIndexes Optional set of account indexes permitted for this request
9709
+ * @param includeCooldown Whether to factor in `coolingDownUntil` alongside quota rate limits
9710
+ * @returns Minimum wait duration in milliseconds, or 0 if immediately usable or no candidates
9711
+ */
9712
+ getMinWaitTimeForFamily(family, model, eligibleIndexes, includeCooldown = false) {
9713
+ return this.selection.getMinWaitTimeForFamily(family, model, eligibleIndexes, includeCooldown);
9661
9714
  }
9662
9715
  getAccounts() {
9663
9716
  return this.selection.getAccounts();
@@ -10000,17 +10053,23 @@ var init_account_manager = __esm({
10000
10053
  getOldestQuotaCacheAge() {
10001
10054
  return this.selection.getOldestQuotaCacheAge();
10002
10055
  }
10003
- areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
10004
- return this.selection.areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model);
10056
+ /**
10057
+ * Check whether all eligible accounts (more than 1) are currently over the soft-quota threshold.
10058
+ * Returns false if thresholdPercent >= 100 or if <= 1 eligible account remains.
10059
+ */
10060
+ areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes) {
10061
+ return this.selection.areAllAccountsOverSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes);
10005
10062
  }
10006
10063
  /**
10007
- * Get minimum wait time until any account's soft quota resets.
10008
- * Returns 0 if any account is available (not over threshold).
10009
- * Returns the minimum resetTime across all over-threshold accounts.
10010
- * Returns null if no resetTime data is available.
10064
+ * Get minimum wait time until any eligible account's soft quota resets.
10065
+ * Operates over the eligible subset (enabled, non-ineligible, non-verification-required,
10066
+ * and present in `eligibleIndexes` when provided).
10067
+ * Returns null if no eligible accounts remain or no resetTime data is available.
10068
+ * Returns 0 if only 1 eligible account exists or any eligible account is below threshold.
10069
+ * Returns the minimum resetTime across all over-threshold eligible accounts.
10011
10070
  */
10012
- getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model) {
10013
- return this.selection.getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model);
10071
+ getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes) {
10072
+ return this.selection.getMinWaitTimeForSoftQuota(family, thresholdPercent, cacheTtlMs, model, eligibleIndexes);
10014
10073
  }
10015
10074
  };
10016
10075
  }
@@ -25267,13 +25326,13 @@ async function safeRead(path5, privateFile = false, afterReadCheck) {
25267
25326
  let file;
25268
25327
  try {
25269
25328
  file = await open7(path5, constants2.O_RDONLY | constants2.O_NOFOLLOW);
25270
- const stat15 = await file.stat();
25271
- if (!stat15.isFile() || privateFile && (stat15.mode & 511) !== 384) {
25329
+ const stat16 = await file.stat();
25330
+ if (!stat16.isFile() || privateFile && (stat16.mode & 511) !== 384) {
25272
25331
  throw new PiSlotError("unsafe-path");
25273
25332
  }
25274
25333
  await afterReadCheck?.(path5);
25275
25334
  const current = await lstat5(path5);
25276
- if (!current.isFile() || current.dev !== stat15.dev || current.ino !== stat15.ino) {
25335
+ if (!current.isFile() || current.dev !== stat16.dev || current.ino !== stat16.ino) {
25277
25336
  throw new PiSlotError("unsafe-path");
25278
25337
  }
25279
25338
  const bytes = await file.readFile();
@@ -28694,7 +28753,7 @@ function getAntigravityVersionResolution() {
28694
28753
  return lastResolution ?? { version: getAntigravityVersion(), source: "fallback" };
28695
28754
  }
28696
28755
  async function initAntigravityVersion() {
28697
- const log16 = createLogger("version");
28756
+ const log17 = createLogger("version");
28698
28757
  const fallback = getAntigravityVersion();
28699
28758
  let version;
28700
28759
  let source;
@@ -28708,15 +28767,15 @@ async function initAntigravityVersion() {
28708
28767
  } else {
28709
28768
  source = "fallback";
28710
28769
  setAntigravityVersion(fallback);
28711
- log16.info("version-fetch-failed", { fallback });
28770
+ log17.info("version-fetch-failed", { fallback });
28712
28771
  lastResolution = { version: fallback, source };
28713
28772
  return lastResolution;
28714
28773
  }
28715
28774
  }
28716
28775
  if (version !== fallback) {
28717
- log16.info("version-updated", { version, source, previous: fallback });
28776
+ log17.info("version-updated", { version, source, previous: fallback });
28718
28777
  } else {
28719
- log16.debug("version-unchanged", { version, source });
28778
+ log17.debug("version-unchanged", { version, source });
28720
28779
  }
28721
28780
  setAntigravityVersion(version);
28722
28781
  lastResolution = { version, source };
@@ -30917,8 +30976,8 @@ var init_process_heartbeat = __esm({
30917
30976
  });
30918
30977
 
30919
30978
  // src/version-fence.ts
30920
- import { readdir as readdir2, readFile as readFile11 } from "node:fs/promises";
30921
- import { homedir as homedir3 } from "node:os";
30979
+ import { readdir as readdir2, readFile as readFile11, stat as stat9, unlink as unlink9 } from "node:fs/promises";
30980
+ import { homedir as homedir3, uptime } from "node:os";
30922
30981
  import { join as join13 } from "node:path";
30923
30982
  function defaultStateHome() {
30924
30983
  return process.env.XDG_STATE_HOME || join13(homedir3(), ".local", "state");
@@ -31001,13 +31060,18 @@ async function readProcessRecord(path5, pid) {
31001
31060
  return { kind: "gone" };
31002
31061
  return { kind: "unreadable" };
31003
31062
  }
31063
+ let startedAt;
31004
31064
  try {
31005
31065
  const value = JSON.parse(text2);
31066
+ if (isRecord10(value) && typeof value.startedAt === "number" && Number.isFinite(value.startedAt))
31067
+ startedAt = value.startedAt;
31006
31068
  if (value !== null && typeof value === "object" && value.pid === pid && typeof value.version === "string") {
31007
31069
  const layouts = value.layouts;
31008
31070
  const stores = value.stores;
31009
31071
  return {
31010
31072
  kind: "ok",
31073
+ text: text2,
31074
+ startedAt,
31011
31075
  version: value.version,
31012
31076
  ...isRecord10(layouts) ? { layouts } : {},
31013
31077
  ...isRecord10(stores) ? { stores } : {}
@@ -31015,14 +31079,45 @@ async function readProcessRecord(path5, pid) {
31015
31079
  }
31016
31080
  } catch {
31017
31081
  }
31018
- return { kind: "unreadable" };
31082
+ return { kind: "unreadable", text: text2, startedAt };
31019
31083
  }
31020
31084
  function isRecord10(value) {
31021
31085
  return value !== null && typeof value === "object" && !Array.isArray(value);
31022
31086
  }
31087
+ function bootTime(options) {
31088
+ try {
31089
+ return (options.now ?? Date.now)() - (options.uptimeSeconds ?? uptime)() * 1e3;
31090
+ } catch {
31091
+ return Number.NaN;
31092
+ }
31093
+ }
31094
+ async function staleRecord(path5, record3, boot, heartbeat) {
31095
+ if (record3.text === void 0 || !Number.isFinite(boot)) return false;
31096
+ let start = heartbeat ? record3.startedAt : void 0;
31097
+ if (start === void 0) {
31098
+ try {
31099
+ start = (await stat9(path5)).mtimeMs;
31100
+ } catch {
31101
+ return false;
31102
+ }
31103
+ }
31104
+ if (!Number.isFinite(start) || !(start < boot - BOOT_TIME_MARGIN_MS))
31105
+ return false;
31106
+ if (heartbeat) {
31107
+ try {
31108
+ if (await readFile11(path5, "utf8") === record3.text) {
31109
+ await unlink9(path5);
31110
+ log5.debug("Removed stale pre-boot heartbeat", { path: path5 });
31111
+ }
31112
+ } catch {
31113
+ }
31114
+ }
31115
+ return true;
31116
+ }
31023
31117
  async function versionFenceOpen(options) {
31024
31118
  const isAlive = options.isAlive ?? pidAlive;
31025
31119
  const self = options.selfPid ?? process.pid;
31120
+ const boot = bootTime(options);
31026
31121
  const blockers = /* @__PURE__ */ new Map();
31027
31122
  const block = (entry) => {
31028
31123
  const key = entry.pid === "unknown" ? `dir:${entry.detail}` : entry.pid;
@@ -31045,7 +31140,8 @@ async function versionFenceOpen(options) {
31045
31140
  const path5 = join13(heartbeatDir, name);
31046
31141
  const heartbeat = await readProcessRecord(path5, pid);
31047
31142
  if (heartbeat.kind === "gone") continue;
31048
- if (!alive(pid)) continue;
31143
+ const live = alive(pid);
31144
+ if (await staleRecord(path5, heartbeat, boot, true) || !live) continue;
31049
31145
  if (heartbeat.kind === "unreadable") {
31050
31146
  block({ pid, version: "unknown", detail: path5 });
31051
31147
  continue;
@@ -31079,6 +31175,7 @@ async function versionFenceOpen(options) {
31079
31175
  const path5 = join13(dir, name);
31080
31176
  const port = await readProcessRecord(path5, pid);
31081
31177
  if (port.kind === "gone") continue;
31178
+ if (await staleRecord(path5, port, boot, false)) continue;
31082
31179
  const version = port.kind === "ok" ? port.version : "unknown";
31083
31180
  const order = compareVersions(version, options.currentVersion);
31084
31181
  if (order === void 0 || order < 0)
@@ -31091,9 +31188,109 @@ async function versionFenceOpen(options) {
31091
31188
  blockers: [...blockers.values()].sort((a, b) => rank(a) - rank(b))
31092
31189
  };
31093
31190
  }
31191
+ var log5, BOOT_TIME_MARGIN_MS;
31094
31192
  var init_version_fence = __esm({
31095
31193
  "src/version-fence.ts"() {
31096
31194
  "use strict";
31195
+ init_logger4();
31196
+ log5 = createLogger4("version-fence");
31197
+ BOOT_TIME_MARGIN_MS = 3e5;
31198
+ }
31199
+ });
31200
+
31201
+ // src/vault-folder.ts
31202
+ var vault_folder_exports = {};
31203
+ __export(vault_folder_exports, {
31204
+ __resetVaultFoldersForTest: () => __resetVaultFoldersForTest,
31205
+ currentVaultFolder: () => currentVaultFolder,
31206
+ prepareVaultFolder: () => prepareVaultFolder
31207
+ });
31208
+ import { isAbsolute as isAbsolute3 } from "node:path";
31209
+ function vaultOverride(accountFile) {
31210
+ const kept = refusals.get(overrideRefusalKey);
31211
+ if (kept) return { accountFile, vaultDir: kept.stateDir, refusal: kept };
31212
+ const vaultDir = process.env[OVERRIDE];
31213
+ if (!vaultDir) return void 0;
31214
+ if (isAbsolute3(vaultDir)) return { accountFile, vaultDir };
31215
+ const refusal3 = new RuntimeLayoutRefusal(
31216
+ vaultDir,
31217
+ "relative-vault-dir",
31218
+ `antigravity-auth cannot start: ${OVERRIDE} must be an absolute path. Correct it and restart OpenCode.`
31219
+ );
31220
+ refusals.set(overrideRefusalKey, refusal3);
31221
+ return { accountFile, vaultDir, refusal: refusal3 };
31222
+ }
31223
+ function locationKey() {
31224
+ const location = runtimeLayoutLocation();
31225
+ return `${location.stateHomeDir}\0${location.key}`;
31226
+ }
31227
+ function __resetVaultFoldersForTest() {
31228
+ refusals.clear();
31229
+ }
31230
+ async function prepareVaultFolder(options) {
31231
+ const { accountFile } = options;
31232
+ const override = vaultOverride(accountFile);
31233
+ if (override?.refusal) return override;
31234
+ const key = locationKey();
31235
+ const kept = refusals.get(key);
31236
+ if (kept)
31237
+ return override ? { ...override, refusal: kept } : refused(accountFile, kept);
31238
+ const log17 = options.log ?? createLogger4("runtime-layout");
31239
+ const version = options.version ?? await pluginPackageVersion().catch(() => "unknown");
31240
+ try {
31241
+ if (override) {
31242
+ await ensurePrivateDirectory2(override.vaultDir);
31243
+ } else
31244
+ await prepareRuntimeLayout({
31245
+ version,
31246
+ accountFile,
31247
+ log: log17,
31248
+ ...options.layoutLockWaitMs === void 0 ? {} : { layoutLockWaitMs: options.layoutLockWaitMs }
31249
+ });
31250
+ if (options.accountStore !== false)
31251
+ await prepareAccountStore({ version, log: log17 });
31252
+ } catch (error) {
31253
+ const refusal3 = error instanceof RuntimeLayoutRefusal ? error : new RuntimeLayoutRefusal(
31254
+ override?.vaultDir ?? runtimeLayoutLocation().stateHomeDir,
31255
+ error instanceof Error ? error.name : typeof error
31256
+ );
31257
+ if (!refusals.has(key)) {
31258
+ refusals.set(key, refusal3);
31259
+ log17.warn(refusal3.message, {
31260
+ stateDir: refusal3.stateDir,
31261
+ errorClass: refusal3.errorClass
31262
+ });
31263
+ }
31264
+ return override ? { ...override, refusal: refusals.get(key) ?? refusal3 } : refused(accountFile, refusals.get(key) ?? refusal3);
31265
+ }
31266
+ return override ?? { accountFile, vaultDir: getVaultDir(accountFile) };
31267
+ }
31268
+ function currentVaultFolder(accountFile) {
31269
+ const override = vaultOverride(accountFile);
31270
+ if (override?.refusal) return override;
31271
+ const kept = refusals.get(locationKey());
31272
+ return kept ? override ? { ...override, refusal: kept } : refused(accountFile, kept) : override ?? { accountFile, vaultDir: getVaultDir(accountFile) };
31273
+ }
31274
+ function refused(accountFile, refusal3) {
31275
+ return { accountFile, vaultDir: getVaultDir(accountFile), refusal: refusal3 };
31276
+ }
31277
+ var refusalsKey, globalState2, refusals, OVERRIDE, overrideRefusalKey;
31278
+ var init_vault_folder = __esm({
31279
+ "src/vault-folder.ts"() {
31280
+ "use strict";
31281
+ init_private_files2();
31282
+ init_logger4();
31283
+ init_process_heartbeat();
31284
+ init_runtime_layout();
31285
+ init_runtime_paths();
31286
+ refusalsKey = /* @__PURE__ */ Symbol.for(
31287
+ "@cortexkit/antigravity-auth/vault-folder-refusals"
31288
+ );
31289
+ globalState2 = globalThis;
31290
+ refusals = globalState2[refusalsKey] ?? /* @__PURE__ */ new Map();
31291
+ globalState2[refusalsKey] = refusals;
31292
+ OVERRIDE = "OPENCODE_ANTIGRAVITY_AUTH_VAULT_DIR";
31293
+ overrideRefusalKey = "invalid-vault-dir-override";
31097
31294
  }
31098
31295
  });
31099
31296
 
@@ -31124,8 +31321,8 @@ import {
31124
31321
  readFile as readFile12,
31125
31322
  rename as rename10,
31126
31323
  rmdir as rmdir2,
31127
- stat as stat9,
31128
- unlink as unlink9
31324
+ stat as stat10,
31325
+ unlink as unlink10
31129
31326
  } from "node:fs/promises";
31130
31327
  import { basename as basename4, dirname as dirname15, join as join14, resolve as resolve15 } from "node:path";
31131
31328
  function refusalMessage(stateDir, errorClass2) {
@@ -31180,10 +31377,10 @@ function errorFile(error) {
31180
31377
  ...typeof stage === "string" && stage ? { stage } : {}
31181
31378
  };
31182
31379
  }
31183
- function logCleanupFailure(location, log16, step, error) {
31380
+ function logCleanupFailure(location, log17, step, error) {
31184
31381
  logOnce(
31185
31382
  `${location.key}\0cleanup`,
31186
- () => log16.warn(
31383
+ () => log17.warn(
31187
31384
  "antigravity-auth could not finish removing its old vault files from OpenCode's config folder; it tries again at the next start",
31188
31385
  {
31189
31386
  configDir: location.configDir,
@@ -31212,13 +31409,13 @@ function prepareRuntimeLayout(options) {
31212
31409
  return run;
31213
31410
  }
31214
31411
  async function decide(location, options) {
31215
- const log16 = options.log ?? createLogger4("runtime-layout");
31412
+ const log17 = options.log ?? createLogger4("runtime-layout");
31216
31413
  const stateDir = location.stateHomeDir;
31217
31414
  const markerPath = join14(stateDir, RUNTIME_LAYOUT_MARKER_FILE);
31218
31415
  const files = layoutFiles(location, options.accountFile);
31219
31416
  const fence = options.fence ?? defaultFence(options.version);
31220
31417
  const stateHome = async () => {
31221
- await settleVault(location, options, "state-home", log16);
31418
+ await settleVault(location, options, "state-home", log17);
31222
31419
  return "state-home";
31223
31420
  };
31224
31421
  let marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -31229,7 +31426,7 @@ async function decide(location, options) {
31229
31426
  join14(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)
31230
31427
  ).catch(() => true);
31231
31428
  if (!manifestLeft) {
31232
- await settleVault(location, options, "state-home", log16);
31429
+ await settleVault(location, options, "state-home", log17);
31233
31430
  return stateHome();
31234
31431
  }
31235
31432
  }
@@ -31241,7 +31438,7 @@ async function decide(location, options) {
31241
31438
  RUNTIME_LAYOUT_LOCK_NAME,
31242
31439
  markerPath,
31243
31440
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
31244
- log16
31441
+ log17
31245
31442
  );
31246
31443
  } catch (error) {
31247
31444
  marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -31261,7 +31458,7 @@ async function decide(location, options) {
31261
31458
  const legacy = async () => {
31262
31459
  try {
31263
31460
  await lock.assertOwned();
31264
- await settleVault(location, options, "legacy", log16);
31461
+ await settleVault(location, options, "legacy", log17);
31265
31462
  } catch (error) {
31266
31463
  throw new RuntimeLayoutRefusal(stateDir, errorClass(error));
31267
31464
  }
@@ -31275,20 +31472,20 @@ async function decide(location, options) {
31275
31472
  if (!marker.oldFilesRemoved && !aliased)
31276
31473
  await finishOldFiles(location, files, markerPath, marker, lock, {
31277
31474
  fence,
31278
- log: log16,
31475
+ log: log17,
31279
31476
  steps: options.steps,
31280
31477
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile()
31281
31478
  });
31282
31479
  else if (marker.oldFilesRemoved) {
31283
31480
  await refuseReappearedFiles(location, files);
31284
- await removeLeftoverManifest(location, lock, options.steps, log16);
31481
+ await removeLeftoverManifest(location, lock, options.steps, log17);
31285
31482
  }
31286
31483
  return await stateHome();
31287
31484
  }
31288
31485
  if (aliased) {
31289
31486
  logOnce(
31290
31487
  `${location.key}\0aliased`,
31291
- () => log16.warn(
31488
+ () => log17.warn(
31292
31489
  "antigravity-auth keeps its vault files in OpenCode's config folder: its state folder is that same folder",
31293
31490
  { configDir: location.configDir, stateDir }
31294
31491
  )
@@ -31297,14 +31494,14 @@ async function decide(location, options) {
31297
31494
  }
31298
31495
  const gate = await fence();
31299
31496
  if (!gate.open) {
31300
- logDeferral(location, gate.blockers, log16);
31497
+ logDeferral(location, gate.blockers, log17);
31301
31498
  return await legacy();
31302
31499
  }
31303
31500
  let markerStarted = false;
31304
31501
  try {
31305
31502
  const outcome = await moveFiles(location, files, markerPath, lock, {
31306
31503
  fence,
31307
- log: log16,
31504
+ log: log17,
31308
31505
  steps: options.steps,
31309
31506
  destinationPrivate: options.destinationPrivate ?? defaultDestinationPrivate,
31310
31507
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile(),
@@ -31313,13 +31510,13 @@ async function decide(location, options) {
31313
31510
  }
31314
31511
  });
31315
31512
  if (outcome.kind === "deferred") {
31316
- logDeferral(location, outcome.blockers, log16);
31513
+ logDeferral(location, outcome.blockers, log17);
31317
31514
  return await legacy();
31318
31515
  }
31319
31516
  if (outcome.kind === "refused") {
31320
31517
  logOnce(
31321
31518
  `${location.key}\0refused`,
31322
- () => log16.warn(
31519
+ () => log17.warn(
31323
31520
  outcome.reason === "destination-not-private" ? "antigravity-auth keeps its vault files in OpenCode's config folder: the vault folder in its state folder already exists and is not private to your user. It was left unchanged; remove it if it holds nothing you need, then restart OpenCode." : "antigravity-auth keeps its vault files in OpenCode's config folder: it will not move them",
31324
31521
  { reason: outcome.reason, paths: outcome.paths, stateDir }
31325
31522
  )
@@ -31327,7 +31524,7 @@ async function decide(location, options) {
31327
31524
  return await legacy();
31328
31525
  }
31329
31526
  if (outcome.moved)
31330
- log16.info(
31527
+ log17.info(
31331
31528
  "antigravity-auth moved its vault files out of OpenCode's config folder",
31332
31529
  { from: files.vault.old, to: files.vault.next }
31333
31530
  );
@@ -31338,7 +31535,7 @@ async function decide(location, options) {
31338
31535
  return await stateHome();
31339
31536
  logOnce(
31340
31537
  `${location.key}\0failed`,
31341
- () => log16.warn(
31538
+ () => log17.warn(
31342
31539
  "antigravity-auth's vault files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",
31343
31540
  {
31344
31541
  configDir: location.configDir,
@@ -31367,8 +31564,12 @@ async function settleVault(location, options, layout, _log) {
31367
31564
  }
31368
31565
  async function localAccountStoreAuthorized() {
31369
31566
  const location = runtimeLayoutLocation();
31567
+ const folder = process.env.OPENCODE_ANTIGRAVITY_AUTH_VAULT_DIR ? (await Promise.resolve().then(() => (init_vault_folder(), vault_folder_exports))).currentVaultFolder(
31568
+ accountFileForVault(location.configDir)
31569
+ ) : void 0;
31570
+ if (folder?.refusal) return false;
31370
31571
  const claustrum = await loadCommonAuthClaustrum();
31371
- const vaultDir = decidedRuntimeLayout(location) === "state-home" ? stateHomeVaultDir(location) : legacyVaultDir(accountFileForVault(location.configDir));
31572
+ const vaultDir = folder ? folder.vaultDir : decidedRuntimeLayout(location) === "state-home" ? stateHomeVaultDir(location) : legacyVaultDir(accountFileForVault(location.configDir));
31372
31573
  return await enrollmentAuthority2(
31373
31574
  claustrum.hostEnrollmentPaths({
31374
31575
  stateDir: vaultDir,
@@ -31383,7 +31584,7 @@ async function prepareAccountStore(options) {
31383
31584
  if (!await localAccountStoreAuthorized()) return void 0;
31384
31585
  const decided = decidedAccountStoreAnchor(location);
31385
31586
  if (decided) return decided;
31386
- const log16 = options.log ?? createLogger4("runtime-layout");
31587
+ const log17 = options.log ?? createLogger4("runtime-layout");
31387
31588
  const runKey = `${location.stateHomeDir}\0${location.key}`;
31388
31589
  let run = processState.storeRuns.get(runKey);
31389
31590
  if (!run) {
@@ -31394,12 +31595,12 @@ async function prepareAccountStore(options) {
31394
31595
  RUNTIME_LAYOUT_LOCK_NAME,
31395
31596
  join14(location.stateHomeDir, RUNTIME_LAYOUT_MARKER_FILE),
31396
31597
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
31397
- log16
31598
+ log17
31398
31599
  );
31399
31600
  try {
31400
31601
  await lock.assertOwned();
31401
31602
  if (!await localAccountStoreAuthorized()) return void 0;
31402
- return await settleAccountStore(location, options, log16);
31603
+ return await settleAccountStore(location, options, log17);
31403
31604
  } finally {
31404
31605
  await lock.release();
31405
31606
  }
@@ -31410,20 +31611,20 @@ async function prepareAccountStore(options) {
31410
31611
  }
31411
31612
  return run;
31412
31613
  }
31413
- async function settleAccountStore(location, options, log16) {
31614
+ async function settleAccountStore(location, options, log17) {
31414
31615
  const decided = decidedAccountStoreAnchor(location);
31415
31616
  if (decided) return decided;
31416
- const anchor = await decideAccountStore(location, options, log16);
31617
+ const anchor = await decideAccountStore(location, options, log17);
31417
31618
  setAccountStoreAnchor(location, anchor);
31418
31619
  return anchor;
31419
31620
  }
31420
- async function decideAccountStore(location, options, log16) {
31421
- const keepConfig = () => recordAnchor(location, options, "config", log16);
31621
+ async function decideAccountStore(location, options, log17) {
31622
+ const keepConfig = () => recordAnchor(location, options, "config", log17);
31422
31623
  if (processHasOlderGeneration()) {
31423
31624
  logOnce(
31424
31625
  "older-generation-account-store",
31425
31626
  () => showLog(
31426
- log16,
31627
+ log17,
31427
31628
  "antigravity-auth keeps the account store in OpenCode's config folder until OpenCode restarts, because an older version of the plugin ran in this process.",
31428
31629
  { accountStore: "config" }
31429
31630
  )
@@ -31437,7 +31638,7 @@ async function decideAccountStore(location, options, log16) {
31437
31638
  if (!sameSpelling(forward.legacyPath, stateAnchor)) {
31438
31639
  logOnce(
31439
31640
  `${location.key}\0store-forward-elsewhere`,
31440
- () => log16.warn(
31641
+ () => log17.warn(
31441
31642
  "the account store moved to another folder than this process resolved; check XDG_STATE_HOME",
31442
31643
  { movedTo: forward.legacyPath, expected: stateAnchor }
31443
31644
  )
@@ -31448,9 +31649,9 @@ async function decideAccountStore(location, options, log16) {
31448
31649
  options,
31449
31650
  configAnchor,
31450
31651
  stateAnchor,
31451
- log16
31652
+ log17
31452
31653
  );
31453
- return recordAnchor(location, options, "state-home", log16);
31654
+ return recordAnchor(location, options, "state-home", log17);
31454
31655
  }
31455
31656
  if (decidedRuntimeLayout(location) === "legacy") return keepConfig();
31456
31657
  const configStore = await presentAccountStore(configAnchor);
@@ -31462,9 +31663,9 @@ async function decideAccountStore(location, options, log16) {
31462
31663
  `antigravity-auth cannot start: two account stores exist, one at ${configAnchor} and one at ${stateAnchor}, and neither is marked as moved. Keep the one you want and move the other one aside, then restart OpenCode.`
31463
31664
  );
31464
31665
  }
31465
- if (stateStore) return recordAnchor(location, options, "state-home", log16);
31666
+ if (stateStore) return recordAnchor(location, options, "state-home", log17);
31466
31667
  if (configStore) {
31467
- if (!await storeMovePathResolves(stateAnchor, location, log16))
31668
+ if (!await storeMovePathResolves(stateAnchor, location, log17))
31468
31669
  return keepConfig();
31469
31670
  return moveStore(
31470
31671
  location,
@@ -31472,21 +31673,21 @@ async function decideAccountStore(location, options, log16) {
31472
31673
  configAnchor,
31473
31674
  stateAnchor,
31474
31675
  false,
31475
- log16,
31676
+ log17,
31476
31677
  false
31477
31678
  );
31478
31679
  }
31479
- if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log16))
31680
+ if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log17))
31480
31681
  return keepConfig();
31481
- if (!await storeMovePathResolves(stateAnchor, location, log16))
31682
+ if (!await storeMovePathResolves(stateAnchor, location, log17))
31482
31683
  return keepConfig();
31483
- return initializeStore(location, options, stateAnchor, log16);
31684
+ return initializeStore(location, options, stateAnchor, log17);
31484
31685
  }
31485
- function showLog(log16, message, meta) {
31486
- if (log16.log) log16.log(message, meta);
31487
- else log16.info(message, meta);
31686
+ function showLog(log17, message, meta) {
31687
+ if (log17.log) log17.log(message, meta);
31688
+ else log17.info(message, meta);
31488
31689
  }
31489
- async function recordAnchor(location, options, anchor, log16) {
31690
+ async function recordAnchor(location, options, anchor, log17) {
31490
31691
  try {
31491
31692
  await recordProcessAnchor({
31492
31693
  key: location.key,
@@ -31498,32 +31699,32 @@ async function recordAnchor(location, options, anchor, log16) {
31498
31699
  }
31499
31700
  if (anchor === "state-home")
31500
31701
  showLog(
31501
- log16,
31702
+ log17,
31502
31703
  "antigravity-auth keeps its account store in its state folder",
31503
31704
  { accountStore: anchor }
31504
31705
  );
31505
31706
  return anchor;
31506
31707
  }
31507
- async function storeMovePathResolves(stateAnchor, location, log16) {
31708
+ async function storeMovePathResolves(stateAnchor, location, log17) {
31508
31709
  if (folderResolvesToItself(
31509
31710
  join14(location.stateHomeDir, "antigravity-accounts.json")
31510
31711
  ))
31511
31712
  return true;
31512
31713
  logOnce(
31513
31714
  `${location.key}\0store-linked-path`,
31514
- () => log16.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
31715
+ () => log17.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
31515
31716
  accountStore: stateAnchor,
31516
31717
  stateFolder: location.stateHomeDir
31517
31718
  })
31518
31719
  );
31519
31720
  return false;
31520
31721
  }
31521
- async function storeFenceOpen(location, options, log16) {
31722
+ async function storeFenceOpen(location, options, log17) {
31522
31723
  const gate = await (options.storeFence ?? defaultStoreFence(options.version))();
31523
31724
  if (gate.open) return true;
31524
31725
  logOnce(
31525
31726
  `${location.key}\0store-version-fence`,
31526
- () => log16.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
31727
+ () => log17.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
31527
31728
  configDir: location.configDir,
31528
31729
  blockers: gate.blockers
31529
31730
  })
@@ -31550,7 +31751,7 @@ async function storeArtefacts(anchor) {
31550
31751
  (name) => name === store || name.startsWith(`${pool}.store.`) || name.startsWith(pool) && name.endsWith(".tmp")
31551
31752
  ).length;
31552
31753
  }
31553
- async function abandonUnpublishedStore(location, stateAnchor, log16) {
31754
+ async function abandonUnpublishedStore(location, stateAnchor, log17) {
31554
31755
  const store = await loadCommonAuthStoreModules();
31555
31756
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
31556
31757
  if (binding.status === "bound") return false;
@@ -31559,9 +31760,9 @@ async function abandonUnpublishedStore(location, stateAnchor, log16) {
31559
31760
  await rename10(folder, archived).catch((error) => {
31560
31761
  if (error.code !== "ENOENT") throw error;
31561
31762
  });
31562
- await unlink9(accountStorePointerPath(stateAnchor)).catch(() => {
31763
+ await unlink10(accountStorePointerPath(stateAnchor)).catch(() => {
31563
31764
  });
31564
- log16.info(
31765
+ log17.info(
31565
31766
  "antigravity-auth set an unfinished account store aside before starting its move again",
31566
31767
  { configDir: location.configDir, archived }
31567
31768
  );
@@ -31583,9 +31784,9 @@ async function runStoreMove(input2) {
31583
31784
  return { status: "pending", reason: outcome.reason };
31584
31785
  return { status: "cancelled" };
31585
31786
  }
31586
- async function moveStore(location, options, source, target, back, log16, forwarded) {
31587
- const keepConfig = () => recordAnchor(location, options, "config", log16);
31588
- if (!await storeFenceOpen(location, options, log16)) return keepConfig();
31787
+ async function moveStore(location, options, source, target, back, log17, forwarded) {
31788
+ const keepConfig = () => recordAnchor(location, options, "config", log17);
31789
+ if (!await storeFenceOpen(location, options, log17)) return keepConfig();
31589
31790
  try {
31590
31791
  const result = await (options.relocate ?? runStoreMove)({
31591
31792
  source,
@@ -31595,7 +31796,7 @@ async function moveStore(location, options, source, target, back, log16, forward
31595
31796
  if (result.status !== "completed") {
31596
31797
  logOnce(
31597
31798
  `${location.key}\0store-move-unfinished`,
31598
- () => log16.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
31799
+ () => log17.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
31599
31800
  configDir: location.configDir,
31600
31801
  reason: result.status === "pending" ? result.reason : result.status
31601
31802
  })
@@ -31603,14 +31804,14 @@ async function moveStore(location, options, source, target, back, log16, forward
31603
31804
  return forwarded ? "state-home" : keepConfig();
31604
31805
  }
31605
31806
  showLog(
31606
- log16,
31807
+ log17,
31607
31808
  "antigravity-auth moved the account store out of OpenCode's config folder",
31608
31809
  { from: source, to: target, generation: result.id }
31609
31810
  );
31610
31811
  } catch (error) {
31611
31812
  logOnce(
31612
31813
  `${location.key}\0store-move-failed`,
31613
- () => log16.warn(
31814
+ () => log17.warn(
31614
31815
  "antigravity-auth's account store stays in OpenCode's config folder: moving it failed; the move is tried again at the next start",
31615
31816
  {
31616
31817
  configDir: location.configDir,
@@ -31621,9 +31822,9 @@ async function moveStore(location, options, source, target, back, log16, forward
31621
31822
  );
31622
31823
  return forwarded ? "state-home" : keepConfig();
31623
31824
  }
31624
- return recordAnchor(location, options, "state-home", log16);
31825
+ return recordAnchor(location, options, "state-home", log17);
31625
31826
  }
31626
- async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log16) {
31827
+ async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log17) {
31627
31828
  const store = await loadCommonAuthStoreModules();
31628
31829
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
31629
31830
  if (binding.status === "bound") return;
@@ -31634,13 +31835,13 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
31634
31835
  configAnchor,
31635
31836
  stateAnchor,
31636
31837
  false,
31637
- log16,
31838
+ log17,
31638
31839
  true
31639
31840
  );
31640
31841
  } catch (error) {
31641
31842
  logOnce(
31642
31843
  `${location.key}\0store-resume-failed`,
31643
- () => log16.warn(
31844
+ () => log17.warn(
31644
31845
  "antigravity-auth's account store is still moving; it could not be finished at this start",
31645
31846
  {
31646
31847
  configDir: location.configDir,
@@ -31651,9 +31852,9 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
31651
31852
  );
31652
31853
  }
31653
31854
  }
31654
- async function initializeStore(location, options, stateAnchor, log16) {
31655
- const keepConfig = () => recordAnchor(location, options, "config", log16);
31656
- if (!await storeFenceOpen(location, options, log16)) return keepConfig();
31855
+ async function initializeStore(location, options, stateAnchor, log17) {
31856
+ const keepConfig = () => recordAnchor(location, options, "config", log17);
31857
+ if (!await storeFenceOpen(location, options, log17)) return keepConfig();
31657
31858
  try {
31658
31859
  const store = await loadCommonAuthStoreModules();
31659
31860
  const created = await initializeFreshAccountStore(store, {
@@ -31666,7 +31867,7 @@ async function initializeStore(location, options, stateAnchor, log16) {
31666
31867
  } catch (error) {
31667
31868
  logOnce(
31668
31869
  `${location.key}\0store-init-failed`,
31669
- () => log16.warn(
31870
+ () => log17.warn(
31670
31871
  "antigravity-auth's account store stays in OpenCode's config folder: creating it in its state folder failed; it is tried again at the next start",
31671
31872
  {
31672
31873
  configDir: location.configDir,
@@ -31678,13 +31879,13 @@ async function initializeStore(location, options, stateAnchor, log16) {
31678
31879
  return keepConfig();
31679
31880
  }
31680
31881
  showLog(
31681
- log16,
31882
+ log17,
31682
31883
  "antigravity-auth created its account store in its state folder",
31683
31884
  {
31684
31885
  accountStore: stateAnchor
31685
31886
  }
31686
31887
  );
31687
- return recordAnchor(location, options, "state-home", log16);
31888
+ return recordAnchor(location, options, "state-home", log17);
31688
31889
  }
31689
31890
  async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacyAccountFile(runtimeLayoutLocation().configDir)) {
31690
31891
  const forward = {
@@ -31699,10 +31900,10 @@ async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacy
31699
31900
  durability: "file-only-on-windows"
31700
31901
  });
31701
31902
  }
31702
- function logDeferral(location, blockers, log16) {
31903
+ function logDeferral(location, blockers, log17) {
31703
31904
  logOnce(
31704
31905
  `${location.key}\0deferred`,
31705
- () => log16.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
31906
+ () => log17.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
31706
31907
  configDir: location.configDir,
31707
31908
  blockers
31708
31909
  })
@@ -31751,7 +31952,7 @@ async function moveFiles(location, files, markerPath, layoutLock, input2) {
31751
31952
  for (const path5 of listed) {
31752
31953
  if (wanted.has(path5)) continue;
31753
31954
  await layoutLock.assertOwned();
31754
- await unlink9(path5).catch((error) => {
31955
+ await unlink10(path5).catch((error) => {
31755
31956
  if (error.code !== "ENOENT") throw error;
31756
31957
  });
31757
31958
  }
@@ -31860,13 +32061,13 @@ async function finishOldFiles(location, files, markerPath, marker, layoutLock, i
31860
32061
  if (done) await removeOldVaultFolder(files, layoutLock, input2.steps);
31861
32062
  }
31862
32063
  }
31863
- async function removeLeftoverManifest(location, layoutLock, steps, log16) {
32064
+ async function removeLeftoverManifest(location, layoutLock, steps, log17) {
31864
32065
  try {
31865
32066
  await removeManifestOwned(location.stateHomeDir, layoutLock, steps);
31866
32067
  } catch (error) {
31867
32068
  logOnce(
31868
32069
  `${location.key}\0manifest`,
31869
- () => log16.warn(
32070
+ () => log17.warn(
31870
32071
  `antigravity-auth could not remove ${RUNTIME_LAYOUT_MANIFEST_FILE} from its state folder; it tries again at the next start`,
31871
32072
  { stateDir: location.stateHomeDir, errorClass: errorClass(error) }
31872
32073
  )
@@ -31886,16 +32087,16 @@ async function removeOldVaultFolder(files, layoutLock, steps) {
31886
32087
  } catch {
31887
32088
  }
31888
32089
  }
31889
- async function removeOldSignatureCache(location, path5, layoutLock, steps, log16) {
32090
+ async function removeOldSignatureCache(location, path5, layoutLock, steps, log17) {
31890
32091
  try {
31891
32092
  if (!await exists2(path5)) return;
31892
32093
  await beforeRemove(path5, layoutLock, steps);
31893
- await unlink9(path5);
32094
+ await unlink10(path5);
31894
32095
  } catch (error) {
31895
32096
  if (error?.code === "ENOENT") return;
31896
32097
  logOnce(
31897
32098
  `${location.key}\0signature-cache`,
31898
- () => log16.warn(
32099
+ () => log17.warn(
31899
32100
  "antigravity-auth could not remove its old signature cache from OpenCode's config folder; it is no longer used and can be deleted",
31900
32101
  { path: path5, errorClass: errorClass(error) }
31901
32102
  )
@@ -31906,7 +32107,7 @@ async function beforeRemove(path5, layoutLock, steps) {
31906
32107
  await steps?.beforeRemove?.(path5);
31907
32108
  await layoutLock.assertOwned();
31908
32109
  }
31909
- async function takeDataLocks(files, log16) {
32110
+ async function takeDataLocks(files, log17) {
31910
32111
  const locks = [];
31911
32112
  try {
31912
32113
  if (await exists2(files.vault.old))
@@ -31916,7 +32117,7 @@ async function takeDataLocks(files, log16) {
31916
32117
  lock.name,
31917
32118
  join14(files.vault.old, lock.file),
31918
32119
  lock.waitMs,
31919
- log16
32120
+ log17
31920
32121
  )
31921
32122
  );
31922
32123
  return locks;
@@ -31980,6 +32181,7 @@ async function isVaultShapedKeptState(files) {
31980
32181
  return vaultShape && proposedName === OPENCODE_VAULT_ENROLLMENT_NAME;
31981
32182
  }
31982
32183
  async function removeMovedVaultStateLeftover(vaultDir, accountFile) {
32184
+ if (process.env.OPENCODE_ANTIGRAVITY_AUTH_VAULT_DIR) return;
31983
32185
  const location = runtimeLayoutLocation();
31984
32186
  const files = layoutFiles(location, accountFile);
31985
32187
  if (resolve15(vaultDir) !== resolve15(files.vault.next)) return;
@@ -31992,7 +32194,7 @@ async function removeMovedVaultStateLeftover(vaultDir, accountFile) {
31992
32194
  if (!marker?.oldDir || marker.oldDir !== location.key) return;
31993
32195
  const leftover = vaultStateFile(files).old;
31994
32196
  if (!await isVaultShapedKeptState(files)) return;
31995
- await unlink9(leftover).catch((error) => {
32197
+ await unlink10(leftover).catch((error) => {
31996
32198
  if (error.code !== "ENOENT") throw error;
31997
32199
  });
31998
32200
  await rmdir2(files.vault.old).catch(() => {
@@ -32038,7 +32240,7 @@ async function physicalAliases(location, files) {
32038
32240
  async function samePhysical(a, b) {
32039
32241
  const id = async (path5) => {
32040
32242
  try {
32041
- const info = await stat9(path5, { bigint: true });
32243
+ const info = await stat10(path5, { bigint: true });
32042
32244
  return info.ino === 0n ? void 0 : `${info.dev}:${info.ino}`;
32043
32245
  } catch (error) {
32044
32246
  const code2 = error.code;
@@ -32128,7 +32330,7 @@ async function unlinkIfIdentical(file, stateDir, guard) {
32128
32330
  if (!same) throw credentialConflict(stateDir, file);
32129
32331
  await guard();
32130
32332
  try {
32131
- await unlink9(file.old);
32333
+ await unlink10(file.old);
32132
32334
  return true;
32133
32335
  } catch (error) {
32134
32336
  if (error.code === "ENOENT") return true;
@@ -32241,7 +32443,7 @@ async function writeManifest(stateDir, paths) {
32241
32443
  );
32242
32444
  }
32243
32445
  async function removeManifest(stateDir) {
32244
- await unlink9(join14(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)).catch(
32446
+ await unlink10(join14(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)).catch(
32245
32447
  (error) => {
32246
32448
  if (error.code !== "ENOENT") throw error;
32247
32449
  }
@@ -32265,7 +32467,7 @@ async function ensureOwnerOnlyDir(path5) {
32265
32467
  await mkdir13(path5, { recursive: true, mode: 448 });
32266
32468
  await chmod5(path5, 448);
32267
32469
  }
32268
- async function takeLock(name, path5, waitMs, log16) {
32470
+ async function takeLock(name, path5, waitMs, log17) {
32269
32471
  const fs5 = await loadCommonAuthFs();
32270
32472
  const started = performance.now();
32271
32473
  let announced = false;
@@ -32290,7 +32492,7 @@ async function takeLock(name, path5, waitMs, log16) {
32290
32492
  );
32291
32493
  if (!announced && waited >= LOCK_WAIT_NOTICE_MS) {
32292
32494
  announced = true;
32293
- log16.info(
32495
+ log17.info(
32294
32496
  `antigravity-auth is waiting up to ${Math.round(waitMs / 1e3)} s for the ${name} lock at ${path5}.${lockHolderText(name)}`,
32295
32497
  { lock: name, path: path5 }
32296
32498
  );
@@ -32303,7 +32505,7 @@ function lockHolderText(name) {
32303
32505
  }
32304
32506
  async function exists2(path5) {
32305
32507
  try {
32306
- await stat9(path5);
32508
+ await stat10(path5);
32307
32509
  return true;
32308
32510
  } catch (error) {
32309
32511
  const code2 = error.code;
@@ -32311,7 +32513,7 @@ async function exists2(path5) {
32311
32513
  throw error;
32312
32514
  }
32313
32515
  }
32314
- var RUNTIME_LAYOUT_LOCK_NAME, RUNTIME_LAYOUT_MANIFEST_FILE, VAULT_ENROLLMENT_STATE_FILE, VAULT_ENROLLMENT_TOKEN_FILE, VAULT_FILE_NAMES, LOCK_TTL_MS, DATA_LOCKS, LAYOUT_LOCK_WAIT_MS, LOCK_RETRY_MS, LOCK_WAIT_NOTICE_MS, MARKER_READ_ATTEMPTS, MARKER_READ_RETRY_MS, SHARING_RETRY_DELAYS_MS, SHARING_RETRY_BUDGET_MS, RUNTIME_LAYOUT_DEFERRED_MESSAGE, ACCOUNT_STORE_DEFERRED_MESSAGE, ACCOUNT_STORE_LINKED_PATH_MESSAGE, RuntimeLayoutRefusal, stateKey2, globalState2, processState, LayoutMoveError, OldVaultFileKeptError, SHA256_HEX2;
32516
+ var RUNTIME_LAYOUT_LOCK_NAME, RUNTIME_LAYOUT_MANIFEST_FILE, VAULT_ENROLLMENT_STATE_FILE, VAULT_ENROLLMENT_TOKEN_FILE, VAULT_FILE_NAMES, LOCK_TTL_MS, DATA_LOCKS, LAYOUT_LOCK_WAIT_MS, LOCK_RETRY_MS, LOCK_WAIT_NOTICE_MS, MARKER_READ_ATTEMPTS, MARKER_READ_RETRY_MS, SHARING_RETRY_DELAYS_MS, SHARING_RETRY_BUDGET_MS, RUNTIME_LAYOUT_DEFERRED_MESSAGE, ACCOUNT_STORE_DEFERRED_MESSAGE, ACCOUNT_STORE_LINKED_PATH_MESSAGE, RuntimeLayoutRefusal, stateKey2, globalState3, processState, LayoutMoveError, OldVaultFileKeptError, SHA256_HEX2;
32315
32517
  var init_runtime_layout = __esm({
32316
32518
  "src/runtime-layout.ts"() {
32317
32519
  "use strict";
@@ -32368,8 +32570,8 @@ var init_runtime_layout = __esm({
32368
32570
  errorClass;
32369
32571
  };
32370
32572
  stateKey2 = /* @__PURE__ */ Symbol.for("@cortexkit/antigravity-auth/runtime-layout-runs");
32371
- globalState2 = globalThis;
32372
- processState = globalState2[stateKey2] ?? {
32573
+ globalState3 = globalThis;
32574
+ processState = globalState3[stateKey2] ?? {
32373
32575
  runs: /* @__PURE__ */ new Map(),
32374
32576
  storeRuns: /* @__PURE__ */ new Map(),
32375
32577
  logged: /* @__PURE__ */ new Set()
@@ -32377,7 +32579,7 @@ var init_runtime_layout = __esm({
32377
32579
  processState.runs ??= /* @__PURE__ */ new Map();
32378
32580
  processState.storeRuns ??= /* @__PURE__ */ new Map();
32379
32581
  processState.logged ??= /* @__PURE__ */ new Set();
32380
- globalState2[stateKey2] = processState;
32582
+ globalState3[stateKey2] = processState;
32381
32583
  LayoutMoveError = class extends Error {
32382
32584
  constructor(code2, message) {
32383
32585
  super(message);
@@ -32438,7 +32640,7 @@ async function ensureGitignore(configDir) {
32438
32640
  `,
32439
32641
  "utf-8"
32440
32642
  );
32441
- log5.info("Created .gitignore in config directory");
32643
+ log6.info("Created .gitignore in config directory");
32442
32644
  } else {
32443
32645
  const suffix = content.endsWith("\n") ? "" : "\n";
32444
32646
  await fs.appendFile(
@@ -32447,12 +32649,12 @@ async function ensureGitignore(configDir) {
32447
32649
  `,
32448
32650
  "utf-8"
32449
32651
  );
32450
- log5.info("Updated .gitignore with missing entries", {
32652
+ log6.info("Updated .gitignore with missing entries", {
32451
32653
  added: missingEntries
32452
32654
  });
32453
32655
  }
32454
32656
  } catch (error) {
32455
- log5.warn("Failed to update .gitignore with account storage entries", {
32657
+ log6.warn("Failed to update .gitignore with account storage entries", {
32456
32658
  error: String(error)
32457
32659
  });
32458
32660
  }
@@ -32487,21 +32689,21 @@ function migrateLegacyWindowsConfig() {
32487
32689
  mkdirSync(newConfigDir, { recursive: true });
32488
32690
  try {
32489
32691
  renameSync3(legacyPath, newPath);
32490
- log5.info("Migrated Windows config via rename", {
32692
+ log6.info("Migrated Windows config via rename", {
32491
32693
  from: legacyPath,
32492
32694
  to: newPath
32493
32695
  });
32494
32696
  } catch {
32495
32697
  copyFileSync(legacyPath, newPath);
32496
32698
  unlinkSync(legacyPath);
32497
- log5.info("Migrated Windows config via copy+delete", {
32699
+ log6.info("Migrated Windows config via copy+delete", {
32498
32700
  from: legacyPath,
32499
32701
  to: newPath
32500
32702
  });
32501
32703
  }
32502
32704
  return true;
32503
32705
  } catch (error) {
32504
- log5.warn("Failed to migrate legacy Windows config, will use legacy path", {
32706
+ log6.warn("Failed to migrate legacy Windows config, will use legacy path", {
32505
32707
  legacyPath,
32506
32708
  newPath,
32507
32709
  error: String(error)
@@ -32534,7 +32736,7 @@ function getStoragePathWithMigration() {
32534
32736
  );
32535
32737
  const anchored = resolveWindowsAccountAnchor(newPath, legacyPath);
32536
32738
  if (resolve16(anchored).toLowerCase() !== resolve16(newPath).toLowerCase() && !existsSync3(accountStorePointerPath(resolve16(anchored)))) {
32537
- log5.info("Using legacy Windows config path (migration failed)", {
32739
+ log6.info("Using legacy Windows config path (migration failed)", {
32538
32740
  legacyPath,
32539
32741
  newPath
32540
32742
  });
@@ -32702,18 +32904,18 @@ async function clearAccounts() {
32702
32904
  } catch (error) {
32703
32905
  const code2 = error.code;
32704
32906
  if (code2 !== "ENOENT") {
32705
- log5.error("Failed to clear account storage", { error: String(error) });
32907
+ log6.error("Failed to clear account storage", { error: String(error) });
32706
32908
  }
32707
32909
  }
32708
32910
  }
32709
- var log5, mutateAccountStorage2, GITIGNORE_ENTRIES, LegacyAccountPoolRetiredError, MIGRATE_COMMAND, UNMIGRATED_ACCOUNT_MESSAGE, ROLLBACK_COMMAND;
32911
+ var log6, mutateAccountStorage2, GITIGNORE_ENTRIES, LegacyAccountPoolRetiredError, MIGRATE_COMMAND, UNMIGRATED_ACCOUNT_MESSAGE, ROLLBACK_COMMAND;
32710
32912
  var init_storage = __esm({
32711
32913
  "src/plugin/storage.ts"() {
32712
32914
  "use strict";
32713
32915
  init_dist();
32714
32916
  init_runtime_paths();
32715
32917
  init_logger4();
32716
- log5 = createLogger4("storage");
32918
+ log6 = createLogger4("storage");
32717
32919
  mutateAccountStorage2 = async (path5, mutate) => {
32718
32920
  await assertLegacyPoolInUse(path5);
32719
32921
  return mutateAccountStorage(path5, mutate);
@@ -33657,15 +33859,15 @@ function initLogger3(client) {
33657
33859
  }
33658
33860
  function createLogger4(module) {
33659
33861
  let channel3;
33660
- const log16 = (level, message, extra) => {
33862
+ const log17 = (level, message, extra) => {
33661
33863
  channel3 ??= getLegacyLogger().createLogger(module);
33662
33864
  channel3[level](message, extra);
33663
33865
  };
33664
33866
  return {
33665
- debug: (message, extra) => log16("debug", message, extra),
33666
- info: (message, extra) => log16("info", message, extra),
33667
- warn: (message, extra) => log16("warn", message, extra),
33668
- error: (message, extra) => log16("error", message, extra)
33867
+ debug: (message, extra) => log17("debug", message, extra),
33868
+ info: (message, extra) => log17("info", message, extra),
33869
+ warn: (message, extra) => log17("warn", message, extra),
33870
+ error: (message, extra) => log17("error", message, extra)
33669
33871
  };
33670
33872
  }
33671
33873
  var ENV_CONSOLE_LOG2, LOG_LEVEL_FROM_OPERATOR, legacyClient, legacyLogger;
@@ -34501,7 +34703,7 @@ init_storage();
34501
34703
  // src/plugin/token.ts
34502
34704
  init_dist();
34503
34705
  init_logger4();
34504
- var log6 = createLogger4("token");
34706
+ var log7 = createLogger4("token");
34505
34707
  function parseOAuthErrorPayload(text2) {
34506
34708
  if (!text2) {
34507
34709
  return {};
@@ -34584,13 +34786,13 @@ async function exchangeRefreshToken(refreshToken, now) {
34584
34786
  const details = [code2, description ?? errorText3].filter(Boolean).join(": ");
34585
34787
  const baseMessage = `Antigravity token refresh failed (${response.status} ${response.statusText})`;
34586
34788
  const message = details ? `${baseMessage} - ${details}` : baseMessage;
34587
- log6.warn("Token refresh failed", {
34789
+ log7.warn("Token refresh failed", {
34588
34790
  status: response.status,
34589
34791
  code: code2,
34590
34792
  details
34591
34793
  });
34592
34794
  if (code2 === "invalid_grant") {
34593
- log6.warn(
34795
+ log7.warn(
34594
34796
  "Google revoked the stored refresh token - reauthentication required"
34595
34797
  );
34596
34798
  invalidateProjectContextCache(refreshToken);
@@ -34646,7 +34848,7 @@ async function refreshAccessToken(auth, _client, _providerId) {
34646
34848
  if (error instanceof AntigravityTokenRefreshError) {
34647
34849
  throw error;
34648
34850
  }
34649
- log6.error("Unexpected token refresh error", { error: String(error) });
34851
+ log7.error("Unexpected token refresh error", { error: String(error) });
34650
34852
  return void 0;
34651
34853
  }
34652
34854
  }
@@ -34773,7 +34975,7 @@ init_dist();
34773
34975
  // src/plugin/quota.ts
34774
34976
  init_logger4();
34775
34977
  init_dist();
34776
- var log7 = createLogger4("quota");
34978
+ var log8 = createLogger4("quota");
34777
34979
  function createOpenCodeQuotaManager(client, providerId = ANTIGRAVITY_PROVIDER_ID, options = {}) {
34778
34980
  const fetchPoolFileQuota = makeFetchAccountQuota(
34779
34981
  client,
@@ -34964,7 +35166,7 @@ async function pushSidebarQuotaSnapshot(getAccounts, backoffUntil = 0, getActive
34964
35166
  );
34965
35167
  } catch (error) {
34966
35168
  ;
34967
- (options.logger ?? log7).debug("sidebar-quota-write-failed", {
35169
+ (options.logger ?? log8).debug("sidebar-quota-write-failed", {
34968
35170
  error: String(error)
34969
35171
  });
34970
35172
  }
@@ -35330,7 +35532,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
35330
35532
  let rotatedRefresh;
35331
35533
  if (purpose === "advisory") {
35332
35534
  if (accessTokenExpired(auth)) {
35333
- log7.debug("advisory-quota-skipped-refresh-needed");
35535
+ log8.debug("advisory-quota-skipped-refresh-needed");
35334
35536
  return {
35335
35537
  index,
35336
35538
  email: account.email,
@@ -35342,7 +35544,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
35342
35544
  const managedProjectId = parts.managedProjectId ?? account.managedProjectId;
35343
35545
  const projectId = managedProjectId ?? parts.projectId ?? account.projectId;
35344
35546
  if (!projectId) {
35345
- log7.debug("advisory-quota-skipped-project-needed");
35547
+ log8.debug("advisory-quota-skipped-project-needed");
35346
35548
  return {
35347
35549
  index,
35348
35550
  email: account.email,
@@ -35364,7 +35566,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
35364
35566
  { timeoutMs: extra.timeoutMs }
35365
35567
  );
35366
35568
  },
35367
- logger: log7
35569
+ logger: log8
35368
35570
  }),
35369
35571
  signal
35370
35572
  );
@@ -35421,7 +35623,7 @@ function makeFetchAccountQuota(client, providerId, fetchVia) {
35421
35623
  managedProjectId,
35422
35624
  projectId: projectContext.effectiveProjectId,
35423
35625
  fetchVia,
35424
- logger: log7
35626
+ logger: log8
35425
35627
  });
35426
35628
  quotaResult = payloads.quota;
35427
35629
  if (quotaResult.error) throw new Error(quotaResult.error);
@@ -36050,6 +36252,7 @@ import { join as join24, resolve as resolve20 } from "node:path";
36050
36252
  // src/auth-method-labels.ts
36051
36253
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
36052
36254
  var OPENCODE2_VAULT_AUTH_LABEL = "Use approved Antigravity vault";
36255
+ var OPENCODE2_POOL_RECONNECT_LABEL = "Use existing local Antigravity pool";
36053
36256
 
36054
36257
  // src/common-auth-embedded/auth-menu/ansi.js
36055
36258
  var ANSI2 = {
@@ -36290,8 +36493,8 @@ async function select2(terminal, items, options) {
36290
36493
  // src/common-auth-embedded/claustrum/enrollment.js
36291
36494
  import { createHash as createHash13, randomBytes as randomBytes5, randomUUID as randomUUID17 } from "node:crypto";
36292
36495
  import { constants as fsConstants2 } from "node:fs";
36293
- import { chmod as chmod6, mkdir as mkdir15, open as open10, readFile as readFile14, realpath as realpath4, rename as rename12, stat as stat11, unlink as unlink10 } from "node:fs/promises";
36294
- import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join20, resolve as resolve19 } from "node:path";
36496
+ import { chmod as chmod6, mkdir as mkdir15, open as open10, readFile as readFile14, realpath as realpath4, rename as rename12, stat as stat12, unlink as unlink11 } from "node:fs/promises";
36497
+ import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute4, join as join20, resolve as resolve19 } from "node:path";
36295
36498
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
36296
36499
 
36297
36500
  // src/common-auth-embedded/fs/file-read-cache.js
@@ -36364,7 +36567,7 @@ init_private_files2();
36364
36567
  // src/common-auth-embedded/fs/refresh-file-lock.js
36365
36568
  init_private_files2();
36366
36569
  import { randomUUID as randomUUID16 } from "node:crypto";
36367
- import { lstat as lstat8, mkdir as mkdir14, open as open9, readFile as readFile13, rename as rename11, rm as rm6, stat as stat10 } from "node:fs/promises";
36570
+ import { lstat as lstat8, mkdir as mkdir14, open as open9, readFile as readFile13, rename as rename11, rm as rm6, stat as stat11 } from "node:fs/promises";
36368
36571
  import { dirname as dirname19, join as join19 } from "node:path";
36369
36572
 
36370
36573
  // src/common-auth-embedded/fs/with-lock.js
@@ -36618,7 +36821,7 @@ async function acquireRefreshFileLockWithClock2(options) {
36618
36821
  };
36619
36822
  }
36620
36823
  try {
36621
- const current = await stat10(lockPath);
36824
+ const current = await stat11(lockPath);
36622
36825
  const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
36623
36826
  if (legacyExpiry > now())
36624
36827
  return { status: "live" };
@@ -36685,7 +36888,7 @@ async function acquireRefreshFileLockWithClock2(options) {
36685
36888
  if (!sameMarkerDirectory2(created, current))
36686
36889
  return false;
36687
36890
  try {
36688
- await stat10(evictOwnerPath);
36891
+ await stat11(evictOwnerPath);
36689
36892
  return true;
36690
36893
  } catch (error) {
36691
36894
  if (error.code !== "ENOENT")
@@ -36737,7 +36940,7 @@ async function acquireRefreshFileLockWithClock2(options) {
36737
36940
  async function recoverStaleEvictionMarker() {
36738
36941
  let evictStat;
36739
36942
  try {
36740
- evictStat = await stat10(evictPath);
36943
+ evictStat = await stat11(evictPath);
36741
36944
  } catch (error) {
36742
36945
  if (error.code === "ENOENT")
36743
36946
  return "missing";
@@ -36755,7 +36958,7 @@ async function acquireRefreshFileLockWithClock2(options) {
36755
36958
  if (evictStat.mtimeMs + EVICT_TTL > now()) {
36756
36959
  let hasOwner = true;
36757
36960
  try {
36758
- await stat10(evictOwnerPath);
36961
+ await stat11(evictOwnerPath);
36759
36962
  } catch (error) {
36760
36963
  if (error.code === "ENOENT")
36761
36964
  hasOwner = false;
@@ -37157,9 +37360,9 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
37157
37360
  }
37158
37361
  function hostEnrollmentPaths2(input2) {
37159
37362
  const override = input2.override?.trim();
37160
- if (override && !isAbsolute3(override) && !input2.cwd)
37363
+ if (override && !isAbsolute4(override) && !input2.cwd)
37161
37364
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
37162
- const tokenPath = override ? isAbsolute3(override) ? override : resolve19(input2.cwd, override) : join20(input2.stateDir, `${input2.host}-enrollment.json`);
37365
+ const tokenPath = override ? isAbsolute4(override) ? override : resolve19(input2.cwd, override) : join20(input2.stateDir, `${input2.host}-enrollment.json`);
37163
37366
  return getClaustrumEnrollmentPaths2(tokenPath);
37164
37367
  }
37165
37368
  function isRecord11(value) {
@@ -37344,7 +37547,7 @@ async function refuseWritableAncestor2(parent, options = {}) {
37344
37547
  }
37345
37548
  let privateGroup;
37346
37549
  for (; ; ) {
37347
- const metadata = await stat11(component).catch(() => void 0);
37550
+ const metadata = await stat12(component).catch(() => void 0);
37348
37551
  if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
37349
37552
  if (privateGroup === void 0) {
37350
37553
  privateGroup = gid !== void 0 && await isPrivateGroup2(uid, gid, options);
@@ -37373,7 +37576,7 @@ async function ensureClaustrumPrivateDirectory2(directory, options = {}, what =
37373
37576
  return;
37374
37577
  }
37375
37578
  await mkdir15(directory, { recursive: true, mode: 448 });
37376
- const metadata = await stat11(directory);
37579
+ const metadata = await stat12(directory);
37377
37580
  const uid = process.geteuid?.();
37378
37581
  if (uid !== void 0 && metadata.uid !== uid) {
37379
37582
  throw new ClaustrumConsumerError2("unsafe-file", `Claustrum ${what} must be owned by the current user`);
@@ -37409,7 +37612,7 @@ async function writeStateAtomic2(path5, state, ancestorOptions = {}) {
37409
37612
  await descriptor?.close().catch(() => {
37410
37613
  });
37411
37614
  if (created)
37412
- await unlink10(temporary).catch(() => {
37615
+ await unlink11(temporary).catch(() => {
37413
37616
  });
37414
37617
  }
37415
37618
  }
@@ -37636,7 +37839,7 @@ var ClaustrumEnrollmentManager2 = class {
37636
37839
  }
37637
37840
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
37638
37841
  await lock.assertOwned();
37639
- await unlink10(this.#paths.statePath).catch((cause) => {
37842
+ await unlink11(this.#paths.statePath).catch((cause) => {
37640
37843
  if (cause.code !== "ENOENT")
37641
37844
  throw cause;
37642
37845
  });
@@ -37726,7 +37929,7 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
37726
37929
  if (state.phase === "pending")
37727
37930
  return "refused-pending";
37728
37931
  await lock.assertOwned();
37729
- await unlink10(paths.statePath);
37932
+ await unlink11(paths.statePath);
37730
37933
  return "reset";
37731
37934
  } finally {
37732
37935
  await lock.release();
@@ -37962,7 +38165,7 @@ function setupPaths(io = {}) {
37962
38165
  }
37963
38166
 
37964
38167
  // src/common-auth-embedded/setup/detect.js
37965
- function stat12(path5, kind) {
38168
+ function stat13(path5, kind) {
37966
38169
  try {
37967
38170
  return statSync5(path5)[kind]();
37968
38171
  } catch {
@@ -37971,12 +38174,12 @@ function stat12(path5, kind) {
37971
38174
  }
37972
38175
  var defaultSetupFileSystem = {
37973
38176
  exists: existsSync6,
37974
- isFile: (path5) => stat12(path5, "isFile"),
37975
- isDirectory: (path5) => stat12(path5, "isDirectory"),
38177
+ isFile: (path5) => stat13(path5, "isFile"),
38178
+ isDirectory: (path5) => stat13(path5, "isDirectory"),
37976
38179
  isExecutable(path5) {
37977
38180
  try {
37978
38181
  accessSync(path5, constants3.X_OK);
37979
- return stat12(path5, "isFile");
38182
+ return stat13(path5, "isFile");
37980
38183
  } catch {
37981
38184
  return false;
37982
38185
  }
@@ -38682,7 +38885,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
38682
38885
 
38683
38886
  // src/common-auth-embedded/setup/config-write.js
38684
38887
  import { randomUUID as randomUUID18 } from "node:crypto";
38685
- import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat13, unlink as unlink11 } from "node:fs/promises";
38888
+ import { mkdir as mkdir16, open as open11, rename as rename13, stat as stat14, unlink as unlink12 } from "node:fs/promises";
38686
38889
  import { basename as basename6, dirname as dirname21, join as join22 } from "node:path";
38687
38890
  import { setTimeout as delay2 } from "node:timers/promises";
38688
38891
  async function writeHostConfigAtomic(file, content, options = {}) {
@@ -38692,7 +38895,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
38692
38895
  let mode;
38693
38896
  if (!windows2) {
38694
38897
  try {
38695
- mode = (await stat13(file)).mode & 4095;
38898
+ mode = (await stat14(file)).mode & 4095;
38696
38899
  } catch (error) {
38697
38900
  if (error.code !== "ENOENT")
38698
38901
  throw error;
@@ -38728,7 +38931,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
38728
38931
  }
38729
38932
  } finally {
38730
38933
  if (created)
38731
- await unlink11(stage).catch(() => {
38934
+ await unlink12(stage).catch(() => {
38732
38935
  });
38733
38936
  }
38734
38937
  }
@@ -39170,63 +39373,7 @@ function createV1VaultActivationMethod(input2) {
39170
39373
  // src/setup.ts
39171
39374
  init_vault_custody();
39172
39375
  init_runtime_paths();
39173
-
39174
- // src/vault-folder.ts
39175
- init_logger4();
39176
- init_process_heartbeat();
39177
- init_runtime_layout();
39178
- init_runtime_paths();
39179
- var refusalsKey = /* @__PURE__ */ Symbol.for(
39180
- "@cortexkit/antigravity-auth/vault-folder-refusals"
39181
- );
39182
- var globalState3 = globalThis;
39183
- var refusals = globalState3[refusalsKey] ?? /* @__PURE__ */ new Map();
39184
- globalState3[refusalsKey] = refusals;
39185
- function locationKey() {
39186
- const location = runtimeLayoutLocation();
39187
- return `${location.stateHomeDir}\0${location.key}`;
39188
- }
39189
- async function prepareVaultFolder(options) {
39190
- const { accountFile } = options;
39191
- const key = locationKey();
39192
- const kept = refusals.get(key);
39193
- if (kept) return refused(accountFile, kept);
39194
- const log16 = options.log ?? createLogger4("runtime-layout");
39195
- const version = options.version ?? await pluginPackageVersion().catch(() => "unknown");
39196
- try {
39197
- await prepareRuntimeLayout({
39198
- version,
39199
- accountFile,
39200
- log: log16,
39201
- ...options.layoutLockWaitMs === void 0 ? {} : { layoutLockWaitMs: options.layoutLockWaitMs }
39202
- });
39203
- if (options.accountStore !== false)
39204
- await prepareAccountStore({ version, log: log16 });
39205
- } catch (error) {
39206
- const refusal3 = error instanceof RuntimeLayoutRefusal ? error : new RuntimeLayoutRefusal(
39207
- runtimeLayoutLocation().stateHomeDir,
39208
- error instanceof Error ? error.name : typeof error
39209
- );
39210
- if (!refusals.has(key)) {
39211
- refusals.set(key, refusal3);
39212
- log16.warn(refusal3.message, {
39213
- stateDir: refusal3.stateDir,
39214
- errorClass: refusal3.errorClass
39215
- });
39216
- }
39217
- return refused(accountFile, refusals.get(key) ?? refusal3);
39218
- }
39219
- return { accountFile, vaultDir: getVaultDir(accountFile) };
39220
- }
39221
- function currentVaultFolder(accountFile) {
39222
- const kept = refusals.get(locationKey());
39223
- return kept ? refused(accountFile, kept) : { accountFile, vaultDir: getVaultDir(accountFile) };
39224
- }
39225
- function refused(accountFile, refusal3) {
39226
- return { accountFile, vaultDir: getVaultDir(accountFile), refusal: refusal3 };
39227
- }
39228
-
39229
- // src/setup.ts
39376
+ init_vault_folder();
39230
39377
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
39231
39378
  async function storePresent(anchor) {
39232
39379
  return await pathPresent(accountStorePointerPath(anchor)) || await pathPresent(anchor);
@@ -39380,6 +39527,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39380
39527
  }
39381
39528
  };
39382
39529
  let openCodeLogin;
39530
+ let hasLocalPool = false;
39383
39531
  const manifest = JSON.parse(
39384
39532
  await readFile16(new URL("../package.json", import.meta.url), "utf8")
39385
39533
  );
@@ -39435,7 +39583,23 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39435
39583
  },
39436
39584
  signInLocal: async (host, context) => {
39437
39585
  await assertLocal(host, context);
39438
- if (host === "opencode" && context.opencodeGeneration === "2") return;
39586
+ if (host === "opencode" && context.opencodeGeneration === "2") {
39587
+ if (!forceLogin) {
39588
+ try {
39589
+ const source2 = await deps.accountStore.read(
39590
+ deps.accountStore.legacyPath()
39591
+ );
39592
+ const candidateAccounts = source2.kind === "store" ? source2.accounts : source2.kind === "legacy" ? (await deps.loadAccounts())?.accounts ?? [] : [];
39593
+ if (candidateAccounts.some(
39594
+ (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39595
+ )) {
39596
+ hasLocalPool = true;
39597
+ }
39598
+ } catch {
39599
+ }
39600
+ }
39601
+ return;
39602
+ }
39439
39603
  const slot = (await nativeAuth(host, context))[provider(host)];
39440
39604
  const source = host === "opencode" ? await deps.accountStore.read(deps.accountStore.legacyPath()) : void 0;
39441
39605
  if (source?.kind === "unavailable") throw new Error(source.reason);
@@ -39447,6 +39611,11 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39447
39611
  `Using existing local Antigravity login for ${host}.
39448
39612
  `
39449
39613
  );
39614
+ if (host === "opencode" && accounts.some(
39615
+ (account) => account.enabled !== false && account.accountIneligible !== true && account.verificationRequired !== true && typeof account.refreshToken === "string" && account.refreshToken.length > 0
39616
+ )) {
39617
+ hasLocalPool = true;
39618
+ }
39450
39619
  if (host === "opencode" && claustrum.classifyHostSlot(slot, provider(host)) !== "login") {
39451
39620
  const account = accounts[0];
39452
39621
  await writeNativeSlot(
@@ -39477,7 +39646,10 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
39477
39646
  host,
39478
39647
  context
39479
39648
  );
39480
- if (host === "opencode") openCodeLogin = result;
39649
+ if (host === "opencode") {
39650
+ openCodeLogin = result;
39651
+ hasLocalPool = true;
39652
+ }
39481
39653
  },
39482
39654
  beforeRegister: async (host, mode, context) => {
39483
39655
  const needsOpenCode2 = host === "opencode" && context.opencodeGeneration !== "1";
@@ -39501,7 +39673,10 @@ Setup has not completed the OpenCode 2 native Google connection.
39501
39673
  },
39502
39674
  context
39503
39675
  );
39504
- if (needsOpenCode2) nativeNextStep(OPENCODE2_POOL_AUTH_LABEL);
39676
+ if (needsOpenCode2)
39677
+ nativeNextStep(
39678
+ hasLocalPool ? OPENCODE2_POOL_RECONNECT_LABEL : OPENCODE2_POOL_AUTH_LABEL
39679
+ );
39505
39680
  return;
39506
39681
  }
39507
39682
  if (await authority(host) !== "vault")
@@ -39595,6 +39770,7 @@ async function runPluginSetup(argv, deps, migrateOpenCode, io = {}) {
39595
39770
  }
39596
39771
 
39597
39772
  // src/cli.ts
39773
+ init_vault_folder();
39598
39774
  var HELP = `Usage: antigravity-auth <command> [options]
39599
39775
 
39600
39776
  Commands:
@@ -40405,8 +40581,8 @@ function getLocalDevPath(directory) {
40405
40581
  }
40406
40582
  function findPackageJsonUp(startPath) {
40407
40583
  try {
40408
- const stat15 = fs4.statSync(startPath);
40409
- let dir = stat15.isDirectory() ? startPath : path4.dirname(startPath);
40584
+ const stat16 = fs4.statSync(startPath);
40585
+ let dir = stat16.isDirectory() ? startPath : path4.dirname(startPath);
40410
40586
  for (let i = 0; i < 10; i++) {
40411
40587
  const pkgPath = path4.join(dir, "package.json");
40412
40588
  if (fs4.existsSync(pkgPath)) {
@@ -40716,12 +40892,12 @@ function isTuiConnected(sessionId) {
40716
40892
  // src/rpc/rpc-dir.ts
40717
40893
  import { createHash as createHash14 } from "node:crypto";
40718
40894
  import { homedir as homedir10, tmpdir as tmpdir4 } from "node:os";
40719
- import { isAbsolute as isAbsolute4, join as join28, resolve as resolve22 } from "node:path";
40895
+ import { isAbsolute as isAbsolute5, join as join28, resolve as resolve22 } from "node:path";
40720
40896
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
40721
40897
  function getRpcDir(projectDirectory) {
40722
40898
  const override = process.env[RPC_DIR_ENV]?.trim();
40723
40899
  if (override) {
40724
- return isAbsolute4(override) ? override : resolve22(projectDirectory, override);
40900
+ return isAbsolute5(override) ? override : resolve22(projectDirectory, override);
40725
40901
  }
40726
40902
  const projectHash = createHash14("sha256").update(resolve22(projectDirectory)).digest("hex").slice(0, 16);
40727
40903
  const stateHome = process.env.XDG_STATE_HOME ?? join28(homedir10(), ".local", "state");
@@ -40736,7 +40912,7 @@ function isSessionId(value) {
40736
40912
  // src/common-auth-embedded/rpc/port-file.js
40737
40913
  init_private_files2();
40738
40914
  import { createHash as createHash15, randomUUID as randomUUID19 } from "node:crypto";
40739
- import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir4, rename as rename14, rmdir as rmdir3, stat as stat14, unlink as unlink12 } from "node:fs/promises";
40915
+ import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir4, rename as rename14, rmdir as rmdir3, stat as stat15, unlink as unlink13 } from "node:fs/promises";
40740
40916
  import { join as join29, resolve as resolve23 } from "node:path";
40741
40917
  function isProbeablePid(pid) {
40742
40918
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
@@ -40761,9 +40937,9 @@ function isUsablePortFileEntry(value, name) {
40761
40937
  const { pid, port, token } = value;
40762
40938
  return isProbeablePid(pid) && filenamePid(name) === pid && typeof port === "number" && Number.isInteger(port) && port >= 1 && port <= 65535 && typeof token === "string" && token.length > 0;
40763
40939
  }
40764
- async function removeCorruptPortFile(portFile, log16) {
40765
- log16?.debug("rpc corrupt port file", { pid: process.pid, portFile });
40766
- await unlink12(portFile).catch(() => {
40940
+ async function removeCorruptPortFile(portFile, log17) {
40941
+ log17?.debug("rpc corrupt port file", { pid: process.pid, portFile });
40942
+ await unlink13(portFile).catch(() => {
40767
40943
  });
40768
40944
  }
40769
40945
  async function writePortFile(dir, entry, options = {}) {
@@ -40801,7 +40977,7 @@ async function writePortFile(dir, entry, options = {}) {
40801
40977
  await handle?.close().catch(() => {
40802
40978
  });
40803
40979
  if (created)
40804
- await unlink12(tmp).catch(() => {
40980
+ await unlink13(tmp).catch(() => {
40805
40981
  });
40806
40982
  }
40807
40983
  return target;
@@ -40815,7 +40991,7 @@ async function writePortFile(dir, entry, options = {}) {
40815
40991
  throw error;
40816
40992
  }
40817
40993
  }
40818
- async function sweepRpcState(root, activeDir, isManagedDir, log16) {
40994
+ async function sweepRpcState(root, activeDir, isManagedDir, log17) {
40819
40995
  let projectDirs;
40820
40996
  try {
40821
40997
  projectDirs = await readdir4(root, { withFileTypes: true });
@@ -40856,16 +41032,16 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
40856
41032
  try {
40857
41033
  parsed = JSON.parse(raw);
40858
41034
  } catch {
40859
- await removeCorruptPortFile(portFile, log16);
41035
+ await removeCorruptPortFile(portFile, log17);
40860
41036
  continue;
40861
41037
  }
40862
41038
  if (!isUsablePortFileEntry(parsed, name)) {
40863
- await removeCorruptPortFile(portFile, log16);
41039
+ await removeCorruptPortFile(portFile, log17);
40864
41040
  continue;
40865
41041
  }
40866
41042
  const entry = parsed;
40867
41043
  if (!pidAlive2(entry.pid))
40868
- await unlink12(portFile).catch(() => {
41044
+ await unlink13(portFile).catch(() => {
40869
41045
  });
40870
41046
  }
40871
41047
  if (resolve23(dir) !== active2)
@@ -40880,7 +41056,7 @@ init_private_files2();
40880
41056
  // src/common-auth-embedded/rpc/rpc-server.js
40881
41057
  init_private_files2();
40882
41058
  import { randomBytes as randomBytes6, timingSafeEqual } from "node:crypto";
40883
- import { unlink as unlink13 } from "node:fs/promises";
41059
+ import { unlink as unlink14 } from "node:fs/promises";
40884
41060
  import { createServer as createServer2 } from "node:http";
40885
41061
  import { join as join30 } from "node:path";
40886
41062
  var RpcRequestError = class extends Error {
@@ -40955,7 +41131,7 @@ function tokenOk(header, token) {
40955
41131
  async function startRpcServer(options) {
40956
41132
  if (typeof options.drain === "function" === (typeof options.drainAsync === "function"))
40957
41133
  throw new TypeError("exactly one of drain or drainAsync must be provided");
40958
- const log16 = options.log ?? { warn() {
41134
+ const log17 = options.log ?? { warn() {
40959
41135
  }, debug() {
40960
41136
  } };
40961
41137
  const token = randomBytes6(32).toString("hex");
@@ -41056,7 +41232,7 @@ async function startRpcServer(options) {
41056
41232
  return json(400, { error: "session required" });
41057
41233
  if (sessionId === void 0 && !warnedMissingNotificationSession) {
41058
41234
  warnedMissingNotificationSession = true;
41059
- log16.warn("rpc notification drain missing session id", {
41235
+ log17.warn("rpc notification drain missing session id", {
41060
41236
  pid: process.pid
41061
41237
  });
41062
41238
  }
@@ -41065,7 +41241,7 @@ async function startRpcServer(options) {
41065
41241
  try {
41066
41242
  messages = await options.drainAsync(lastReceivedId, sessionId);
41067
41243
  } catch (error) {
41068
- log16.warn("rpc notification drain failed", {
41244
+ log17.warn("rpc notification drain failed", {
41069
41245
  pid: process.pid,
41070
41246
  error: error instanceof Error ? error.message : String(error)
41071
41247
  });
@@ -41084,20 +41260,20 @@ async function startRpcServer(options) {
41084
41260
  return json(404, { error: "unknown method" });
41085
41261
  } catch (error) {
41086
41262
  if (error instanceof RpcRequestError) {
41087
- log16.debug("rpc request refused", {
41263
+ log17.debug("rpc request refused", {
41088
41264
  pid: process.pid,
41089
41265
  status: error.status
41090
41266
  });
41091
41267
  return json(error.status, { error: error.message });
41092
41268
  }
41093
41269
  if (error instanceof ApplyDeadlineError) {
41094
- log16.warn("rpc apply deadline exceeded", {
41270
+ log17.warn("rpc apply deadline exceeded", {
41095
41271
  pid: process.pid,
41096
41272
  deadlineMs: options.applyDeadlineMs
41097
41273
  });
41098
41274
  return json(504, { error: "handler deadline exceeded" });
41099
41275
  }
41100
- log16.warn("rpc request failed", {
41276
+ log17.warn("rpc request failed", {
41101
41277
  pid: process.pid,
41102
41278
  error: error instanceof Error ? error.message : String(error)
41103
41279
  });
@@ -41117,9 +41293,9 @@ async function startRpcServer(options) {
41117
41293
  server.unref();
41118
41294
  if (options.sweepRoot) {
41119
41295
  try {
41120
- await sweepRpcState(options.sweepRoot, options.dir, options.isManagedDir, log16);
41296
+ await sweepRpcState(options.sweepRoot, options.dir, options.isManagedDir, log17);
41121
41297
  } catch (error) {
41122
- log16.warn("rpc state sweep failed", {
41298
+ log17.warn("rpc state sweep failed", {
41123
41299
  pid: process.pid,
41124
41300
  error: error instanceof Error ? error.message : String(error)
41125
41301
  });
@@ -41127,7 +41303,7 @@ async function startRpcServer(options) {
41127
41303
  }
41128
41304
  try {
41129
41305
  await writePortFile(options.dir, { port, token, pid: process.pid }, { secureDir: options.secureDir });
41130
- log16.debug("rpc server pid", {
41306
+ log17.debug("rpc server pid", {
41131
41307
  pid: process.pid,
41132
41308
  rpcPort: port
41133
41309
  });
@@ -41152,7 +41328,7 @@ async function startRpcServer(options) {
41152
41328
  return void 0;
41153
41329
  });
41154
41330
  if (current?.port === port && current.token === token)
41155
- await unlink13(portFile).catch(() => {
41331
+ await unlink14(portFile).catch(() => {
41156
41332
  });
41157
41333
  }
41158
41334
  };
@@ -41227,6 +41403,9 @@ function parsePending(value) {
41227
41403
  };
41228
41404
  }
41229
41405
 
41406
+ // src/plugin/index.ts
41407
+ init_vault_folder();
41408
+
41230
41409
  // src/plugin/account-access.ts
41231
41410
  init_dist();
41232
41411
 
@@ -43276,10 +43455,10 @@ function toV1AuthCallbackResult(result) {
43276
43455
  };
43277
43456
  }
43278
43457
  var MAX_OAUTH_ACCOUNTS = 10;
43279
- var log8 = createLogger4("oauth-methods");
43280
- async function reportPersistenceFailure(error, client, log16) {
43458
+ var log9 = createLogger4("oauth-methods");
43459
+ async function reportPersistenceFailure(error, client, log17) {
43281
43460
  const message = error instanceof AccountStorageUnreadableError ? `Account storage at ${error.details.path} is unreadable (${error.details.reason}: ${error.details.detail}).${error.details.backupPath ? ` A backup was written to ${error.details.backupPath}. Repair or remove the existing file before retrying.` : " A backup could not be written; repair or remove the existing file before retrying."}` : error instanceof Error ? error.message : String(error);
43282
- log16.error("OAuth login persistence failed; aborting login", {
43461
+ log17.error("OAuth login persistence failed; aborting login", {
43283
43462
  error: message
43284
43463
  });
43285
43464
  try {
@@ -44116,7 +44295,7 @@ ${verifyUrl}
44116
44295
  }
44117
44296
  });
44118
44297
  } catch (storeError) {
44119
- log8.error(
44298
+ log9.error(
44120
44299
  "Failed to update stored Antigravity OAuth credentials",
44121
44300
  { error: String(storeError) }
44122
44301
  );
@@ -44141,7 +44320,7 @@ ${verifyUrl}
44141
44320
  }
44142
44321
  });
44143
44322
  } catch (storeError) {
44144
- log8.error(
44323
+ log9.error(
44145
44324
  "Failed to clear stored Antigravity OAuth credentials",
44146
44325
  { error: String(storeError) }
44147
44326
  );
@@ -44182,7 +44361,7 @@ Re-authenticating ${refreshEmail || "account"}...
44182
44361
  }
44183
44362
  });
44184
44363
  } catch (storeError) {
44185
- log8.error(
44364
+ log9.error(
44186
44365
  "Failed to clear stored Antigravity OAuth credentials",
44187
44366
  { error: String(storeError) }
44188
44367
  );
@@ -44521,7 +44700,7 @@ ${authorization2.url}
44521
44700
  return await reportPersistenceFailure(
44522
44701
  persistError,
44523
44702
  client,
44524
- log8
44703
+ log9
44525
44704
  );
44526
44705
  }
44527
44706
  const newTotal = existingCount + 1;
@@ -44565,7 +44744,7 @@ ${authorization2.url}
44565
44744
  try {
44566
44745
  await persistAccountPool2([result], false);
44567
44746
  } catch (persistError) {
44568
- return await reportPersistenceFailure(persistError, client, log8);
44747
+ return await reportPersistenceFailure(persistError, client, log9);
44569
44748
  }
44570
44749
  const newTotal = existingCount + 1;
44571
44750
  const toastMessage = existingCount > 0 ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total` : `Authenticated${result.email ? ` (${result.email})` : ""}`;
@@ -44728,7 +44907,7 @@ init_logger4();
44728
44907
 
44729
44908
  // src/plugin/refresh-queue.ts
44730
44909
  init_logger4();
44731
- var log9 = createLogger4("refresh-queue");
44910
+ var log10 = createLogger4("refresh-queue");
44732
44911
  var DEFAULT_PROACTIVE_REFRESH_CONFIG = {
44733
44912
  enabled: true,
44734
44913
  bufferSeconds: 1800,
@@ -44768,7 +44947,7 @@ var ProactiveRefreshQueue = class {
44768
44947
  "ProactiveRefreshQueue needs a host client or explicit dependencies"
44769
44948
  );
44770
44949
  }
44771
- this.log = log9;
44950
+ this.log = log10;
44772
44951
  this.refresh = (auth) => refreshAccessToken(auth, client, providerId);
44773
44952
  }
44774
44953
  this.config = {
@@ -45856,7 +46035,7 @@ function getUserConfigPath() {
45856
46035
  function getProjectConfigPath(directory) {
45857
46036
  return join33(directory, ".opencode", "antigravity.json");
45858
46037
  }
45859
- function loadConfigFile(path5, log16) {
46038
+ function loadConfigFile(path5, log17) {
45860
46039
  try {
45861
46040
  if (!existsSync11(path5)) {
45862
46041
  return null;
@@ -45865,7 +46044,7 @@ function loadConfigFile(path5, log16) {
45865
46044
  const rawConfig = JSON.parse(content);
45866
46045
  const result = AntigravityConfigSchema.partial().safeParse(rawConfig);
45867
46046
  if (!result.success) {
45868
- log16.warn("Config validation error", {
46047
+ log17.warn("Config validation error", {
45869
46048
  path: path5,
45870
46049
  issues: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ")
45871
46050
  });
@@ -45874,9 +46053,9 @@ function loadConfigFile(path5, log16) {
45874
46053
  return result.data;
45875
46054
  } catch (error) {
45876
46055
  if (error instanceof SyntaxError) {
45877
- log16.warn("Invalid JSON in config file", { path: path5, error: error.message });
46056
+ log17.warn("Invalid JSON in config file", { path: path5, error: error.message });
45878
46057
  } else {
45879
- log16.warn("Failed to load config file", { path: path5, error: String(error) });
46058
+ log17.warn("Failed to load config file", { path: path5, error: String(error) });
45880
46059
  }
45881
46060
  return null;
45882
46061
  }
@@ -45895,15 +46074,15 @@ function mergeConfigs(base, override) {
45895
46074
  function loadConfig(directory) {
45896
46075
  return loadConfigWithLogger(directory, legacyLog);
45897
46076
  }
45898
- function loadConfigWithLogger(directory, log16) {
46077
+ function loadConfigWithLogger(directory, log17) {
45899
46078
  let config = structuredClone(DEFAULT_CONFIG);
45900
46079
  const userConfigPath = getUserConfigPath();
45901
- const userConfig = loadConfigFile(userConfigPath, log16);
46080
+ const userConfig = loadConfigFile(userConfigPath, log17);
45902
46081
  if (userConfig) {
45903
46082
  config = mergeConfigs(config, userConfig);
45904
46083
  }
45905
46084
  const projectConfigPath = getProjectConfigPath(directory);
45906
- const projectConfig = loadConfigFile(projectConfigPath, log16);
46085
+ const projectConfig = loadConfigFile(projectConfigPath, log17);
45907
46086
  if (projectConfig) {
45908
46087
  config = mergeConfigs(config, projectConfig);
45909
46088
  }
@@ -47312,8 +47491,8 @@ function createSessionRecoveryHook(ctx, config) {
47312
47491
  if (!sessionID) return false;
47313
47492
  let assistantMsgID = info.id;
47314
47493
  let msgs;
47315
- const log16 = createLogger4("session-recovery");
47316
- log16.debug("Recovery attempt started", {
47494
+ const log17 = createLogger4("session-recovery");
47495
+ log17.debug("Recovery attempt started", {
47317
47496
  errorType,
47318
47497
  sessionID,
47319
47498
  providedMsgID: assistantMsgID ?? "none"
@@ -47333,7 +47512,7 @@ function createSessionRecoveryHook(ctx, config) {
47333
47512
  const m = msgs[i];
47334
47513
  if (m && m.info?.role === "assistant" && m.info?.id) {
47335
47514
  assistantMsgID = m.info.id;
47336
- log16.debug("Found assistant message ID from session messages", {
47515
+ log17.debug("Found assistant message ID from session messages", {
47337
47516
  msgID: assistantMsgID,
47338
47517
  msgIndex: i
47339
47518
  });
@@ -47342,7 +47521,7 @@ function createSessionRecoveryHook(ctx, config) {
47342
47521
  }
47343
47522
  }
47344
47523
  if (!assistantMsgID) {
47345
- log16.debug("No assistant message ID found, cannot recover");
47524
+ log17.debug("No assistant message ID found, cannot recover");
47346
47525
  return false;
47347
47526
  }
47348
47527
  if (processingErrors.has(assistantMsgID)) return false;
@@ -47386,7 +47565,7 @@ function createSessionRecoveryHook(ctx, config) {
47386
47565
  }
47387
47566
  return success;
47388
47567
  } catch (err) {
47389
- log16.error("Recovery failed", { error: String(err) });
47568
+ log17.error("Recovery failed", { error: String(err) });
47390
47569
  return false;
47391
47570
  } finally {
47392
47571
  processingErrors.delete(assistantMsgID);
@@ -47406,7 +47585,7 @@ function createSessionRecoveryHook(ctx, config) {
47406
47585
  // src/plugin/request-helpers.ts
47407
47586
  init_dist();
47408
47587
  init_logger4();
47409
- var log10 = createLogger4("request-helpers");
47588
+ var log11 = createLogger4("request-helpers");
47410
47589
  var ANTIGRAVITY_PREVIEW_LINK = "https://goo.gle/enable-preview-features";
47411
47590
  function appendDescriptionHint(schema, hint) {
47412
47591
  if (!schema || typeof schema !== "object") {
@@ -47831,7 +48010,7 @@ function filterContentArray(contentArray, sessionId, getCachedSignatureFn, isCla
47831
48010
  }
47832
48011
  const existingSignature = item.signature || item.thoughtSignature;
47833
48012
  const signatureInfo = existingSignature ? `foreign signature (${String(existingSignature).length} chars)` : "no signature";
47834
- log10.debug(
48013
+ log11.debug(
47835
48014
  `Injecting plain text sentinel for last-message thinking block with ${signatureInfo}`
47836
48015
  );
47837
48016
  const sentinel2 = { text: "." };
@@ -48343,7 +48522,7 @@ function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, curre
48343
48522
  if (lastBracket > 0) {
48344
48523
  const cleaned = stripped.slice(0, lastBracket + 1);
48345
48524
  const parsed = JSON.parse(cleaned);
48346
- log10.debug("Auto-corrected malformed JSON array", {
48525
+ log11.debug("Auto-corrected malformed JSON array", {
48347
48526
  truncatedChars: stripped.length - cleaned.length
48348
48527
  });
48349
48528
  return recursivelyParseJsonStrings(parsed);
@@ -48357,7 +48536,7 @@ function recursivelyParseJsonStrings(obj, skipParseKeys = SKIP_PARSE_KEYS, curre
48357
48536
  if (lastBrace > 0) {
48358
48537
  const cleaned = stripped.slice(0, lastBrace + 1);
48359
48538
  const parsed = JSON.parse(cleaned);
48360
- log10.debug("Auto-corrected malformed JSON object", {
48539
+ log11.debug("Auto-corrected malformed JSON object", {
48361
48540
  truncatedChars: stripped.length - cleaned.length
48362
48541
  });
48363
48542
  return recursivelyParseJsonStrings(parsed);
@@ -48457,7 +48636,7 @@ function fixToolResponseGrouping(contents) {
48457
48636
  if (orphanResp.functionResponse.name === "unknown_function" && expectedName) {
48458
48637
  orphanResp.functionResponse.name = expectedName;
48459
48638
  }
48460
- log10.debug("Auto-repaired tool ID mismatch", {
48639
+ log11.debug("Auto-repaired tool ID mismatch", {
48461
48640
  mappedFrom: matchedId,
48462
48641
  mappedTo: expectedId,
48463
48642
  functionName: expectedName
@@ -48477,7 +48656,7 @@ function fixToolResponseGrouping(contents) {
48477
48656
  id: expectedId
48478
48657
  }
48479
48658
  };
48480
- log10.debug("Created placeholder response for missing tool", {
48659
+ log11.debug("Created placeholder response for missing tool", {
48481
48660
  id: expectedId,
48482
48661
  name: expectedName
48483
48662
  });
@@ -48795,7 +48974,7 @@ function applyToolPairingFixes(payload, isClaude) {
48795
48974
  );
48796
48975
  payload.contents = fixToolResponseGrouping(contentsWithMatchedIds);
48797
48976
  contentsFixed = true;
48798
- log10.debug("Applied tool pairing fixes to contents[]", {
48977
+ log11.debug("Applied tool pairing fixes to contents[]", {
48799
48978
  originalLength: payload.contents.length
48800
48979
  });
48801
48980
  }
@@ -48804,7 +48983,7 @@ function applyToolPairingFixes(payload, isClaude) {
48804
48983
  payload.messages
48805
48984
  );
48806
48985
  messagesFixed = true;
48807
- log10.debug("Applied tool pairing fixes to messages[]", {
48986
+ log11.debug("Applied tool pairing fixes to messages[]", {
48808
48987
  originalLength: payload.messages.length
48809
48988
  });
48810
48989
  }
@@ -49043,7 +49222,7 @@ init_dist();
49043
49222
  init_dist();
49044
49223
 
49045
49224
  // src/plugin/request.ts
49046
- var log11 = createLogger4("request");
49225
+ var log12 = createLogger4("request");
49047
49226
  var PLUGIN_SESSION_ID = `-${crypto2.randomUUID()}`;
49048
49227
  var DEFAULT_AGY_REQUEST_SESSION = createAgyRequestSessionContext("");
49049
49228
  var sessionDisplayedThinkingHashes = /* @__PURE__ */ new Set();
@@ -49842,7 +50021,7 @@ var openCode1WireLocation = {
49842
50021
  logAntigravityDebugResponse: (context, response, meta) => logAntigravityDebugResponse(context, response, meta),
49843
50022
  logCacheStats: (model, cacheRead, cacheWrite, totalInput) => logCacheStats(model, cacheRead, cacheWrite, totalInput)
49844
50023
  },
49845
- logger: log11,
50024
+ logger: log12,
49846
50025
  sessionFingerprint: () => getSessionFingerprint(),
49847
50026
  displayedThinkingHashes: sessionDisplayedThinkingHashes,
49848
50027
  cacheStats: { last: null }
@@ -50994,7 +51173,7 @@ function publishResponse(dispatch) {
50994
51173
 
50995
51174
  // src/plugin/auth-loader.ts
50996
51175
  init_storage();
50997
- var log12 = createLogger4("auth-loader");
51176
+ var log13 = createLogger4("auth-loader");
50998
51177
  function refreshTokenIdentity(refreshToken) {
50999
51178
  return createHash18("sha256").update(refreshToken).digest("hex").slice(0, 16);
51000
51179
  }
@@ -51141,7 +51320,7 @@ function createAuthLoader({
51141
51320
  });
51142
51321
  refreshQueue = deps.createStoreRefreshQueue(
51143
51322
  {
51144
- logger: log12,
51323
+ logger: log13,
51145
51324
  refreshToken: (_auth, account) => credentials.refresh(account)
51146
51325
  },
51147
51326
  queueConfig
@@ -51249,7 +51428,7 @@ function createAuthLoader({
51249
51428
  }
51250
51429
  if (opening.status === "ready") {
51251
51430
  if (!isOAuthAuth(auth) && !readAuthority) {
51252
- log12.warn(
51431
+ log13.warn(
51253
51432
  "The host holds no Antigravity sign-in; the account store is left untouched"
51254
51433
  );
51255
51434
  return {};
@@ -51262,7 +51441,7 @@ function createAuthLoader({
51262
51441
  }
51263
51442
  if (!usesPoolFile(opening)) {
51264
51443
  const message = opening.status === "refused" || opening.status === "recovery-required" ? opening.message : "The Antigravity account store cannot be opened";
51265
- log12.error("Refusing to start: the account store cannot serve", {
51444
+ log13.error("Refusing to start: the account store cannot serve", {
51266
51445
  message
51267
51446
  });
51268
51447
  try {
@@ -51279,7 +51458,7 @@ function createAuthLoader({
51279
51458
  storedAccounts = await deps.loadAccounts();
51280
51459
  } catch (error) {
51281
51460
  if (error instanceof AccountStorageUnreadableError) {
51282
- log12.error("Refusing to start: account storage is unreadable", {
51461
+ log13.error("Refusing to start: account storage is unreadable", {
51283
51462
  path: error.details.path,
51284
51463
  reason: error.details.reason,
51285
51464
  backupPath: error.details.backupPath
@@ -51311,12 +51490,12 @@ function createAuthLoader({
51311
51490
  expires: auth.expires ?? 0
51312
51491
  }
51313
51492
  });
51314
- log12.info("Restored Antigravity OAuth auth from account storage", {
51493
+ log13.info("Restored Antigravity OAuth auth from account storage", {
51315
51494
  reason: drift.reason,
51316
51495
  email: drift.account.email
51317
51496
  });
51318
51497
  } catch (error) {
51319
- log12.warn(
51498
+ log13.warn(
51320
51499
  "Failed to restore Antigravity OAuth auth from account storage",
51321
51500
  { error: String(error) }
51322
51501
  );
@@ -53577,7 +53756,6 @@ var AgySessionRegistry = class {
53577
53756
  };
53578
53757
 
53579
53758
  // src/plugin/shared/vault-routing.ts
53580
- var ROUTING_GROUP_SCOPED_EXHAUSTION = false;
53581
53759
  function hasVaultRoutingAccessor() {
53582
53760
  try {
53583
53761
  return typeof Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing")) === "function";
@@ -53595,7 +53773,7 @@ function routingExhaustionFields(scope) {
53595
53773
  window: scope.limitWindow === "five_hour" ? "5h" : "7d"
53596
53774
  };
53597
53775
  }
53598
- function reportVaultExhaustion(input2, groupScopedExhaustion = ROUTING_GROUP_SCOPED_EXHAUSTION, report = reportRouting) {
53776
+ function reportVaultExhaustion(input2, report = reportRouting) {
53599
53777
  if (!hasVaultRoutingAccessor() || input2.signal?.aborted || input2.status !== 429 || input2.reason !== "QUOTA_EXHAUSTED" || !Number.isFinite(input2.observedAt) || (input2.observedAt ?? 0) <= 0 || (input2.observedAt ?? Infinity) > Date.now())
53600
53778
  return;
53601
53779
  for (const window of input2.quota?.windows ?? []) {
@@ -53603,13 +53781,12 @@ function reportVaultExhaustion(input2, groupScopedExhaustion = ROUTING_GROUP_SCO
53603
53781
  const scope = routingQuotaScope(input2.group, window.window);
53604
53782
  const resetsAt = Date.parse(window.resetTime);
53605
53783
  if (!scope || !Number.isFinite(resetsAt) || resetsAt <= Date.now()) continue;
53606
- if (groupScopedExhaustion)
53607
- report({
53608
- ...input2.identity,
53609
- outcome: "exhausted",
53610
- ...routingExhaustionFields(scope),
53611
- resetsAt
53612
- });
53784
+ report({
53785
+ ...input2.identity,
53786
+ outcome: "exhausted",
53787
+ ...routingExhaustionFields(scope),
53788
+ resetsAt
53789
+ });
53613
53790
  }
53614
53791
  }
53615
53792
  var RATE_LIMIT_HEADERS = [
@@ -53882,7 +54059,7 @@ function sleep4(ms, signal) {
53882
54059
  signal?.addEventListener("abort", onAbort, { once: true });
53883
54060
  });
53884
54061
  }
53885
- function createLocalQuotaRefresh(accountManager, quotaManager, log16) {
54062
+ function createLocalQuotaRefresh(accountManager, quotaManager, log17) {
53886
54063
  return async function refreshQuotaAfterSuccess(account, intervalMinutes, signal) {
53887
54064
  if (intervalMinutes <= 0) return;
53888
54065
  const accountIndex = accountManager.getAccounts().indexOf(account);
@@ -53913,7 +54090,7 @@ function createLocalQuotaRefresh(accountManager, quotaManager, log16) {
53913
54090
  accountManager.requestSaveToDisk();
53914
54091
  }
53915
54092
  } catch (err) {
53916
- log16.debug(
54093
+ log17.debug(
53917
54094
  `quota-refresh-failed ${singleAccount ? quotaManager.hashedLogLabel("account", singleAccount) : `idx-${accountIndex}`}`,
53918
54095
  { error: String(err) }
53919
54096
  );
@@ -53931,7 +54108,7 @@ function createRequestExecutor(deps) {
53931
54108
  wire,
53932
54109
  debug,
53933
54110
  dump,
53934
- logger: log16,
54111
+ logger: log17,
53935
54112
  trackers,
53936
54113
  classifyAccessError,
53937
54114
  notify,
@@ -53950,7 +54127,7 @@ function createRequestExecutor(deps) {
53950
54127
  const reportVault401 = (admission, status) => {
53951
54128
  if (!admission || status !== 401) return;
53952
54129
  void Promise.resolve().then(() => admission.report401(status)).catch((error) => {
53953
- log16.debug("send-admission-401-report-failed", { error: String(error) });
54130
+ log17.debug("send-admission-401-report-failed", { error: String(error) });
53954
54131
  });
53955
54132
  };
53956
54133
  const reportRouting2 = (sessionId, entry) => {
@@ -53958,7 +54135,7 @@ function createRequestExecutor(deps) {
53958
54135
  try {
53959
54136
  onRouting(sessionId, entry);
53960
54137
  } catch (error) {
53961
- log16.debug("routing-report-failed", { sessionId, error: String(error) });
54138
+ log17.debug("routing-report-failed", { sessionId, error: String(error) });
53962
54139
  }
53963
54140
  };
53964
54141
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
@@ -54089,7 +54266,7 @@ function createRequestExecutor(deps) {
54089
54266
  const quietMode = config.quiet_mode;
54090
54267
  const toastScope = config.toast_scope;
54091
54268
  const showToast = async (message, variant2) => {
54092
- log16.debug("toast", {
54269
+ log17.debug("toast", {
54093
54270
  message,
54094
54271
  variant: variant2,
54095
54272
  isChildSession: isChildRequest,
@@ -54098,7 +54275,7 @@ function createRequestExecutor(deps) {
54098
54275
  if (quietMode) return;
54099
54276
  if (abortSignal?.aborted) return;
54100
54277
  if (toastScope === "root_only" && isChildRequest) {
54101
- log16.debug("toast-suppressed-child-session", {
54278
+ log17.debug("toast-suppressed-child-session", {
54102
54279
  message,
54103
54280
  variant: variant2,
54104
54281
  parentID: requestSessionIdentity.parentSessionId
@@ -54171,7 +54348,7 @@ function createRequestExecutor(deps) {
54171
54348
  });
54172
54349
  } catch (error) {
54173
54350
  if (error instanceof AntigravityKillswitchError) {
54174
- log16.warn("killswitch-all-excluded", {
54351
+ log17.warn("killswitch-all-excluded", {
54175
54352
  family,
54176
54353
  model,
54177
54354
  threshold: error.thresholdPercent,
@@ -54196,7 +54373,7 @@ function createRequestExecutor(deps) {
54196
54373
  pushDebug(
54197
54374
  `model-unavailable: all ${candidates.length} eligible account(s) skipped`
54198
54375
  );
54199
- log16.warn("model-unavailable-all-accounts", {
54376
+ log17.warn("model-unavailable-all-accounts", {
54200
54377
  family,
54201
54378
  model,
54202
54379
  accounts: candidates.length
@@ -54278,18 +54455,32 @@ function createRequestExecutor(deps) {
54278
54455
  const blockedSince = allAccountsBlockedAt;
54279
54456
  const remainingWaitMs = () => maxWaitMs > 0 ? Math.max(0, maxWaitMs - (Date.now() - blockedSince)) : Number.POSITIVE_INFINITY;
54280
54457
  const quotaWins = remainingWaitMs() <= deadline.remainingMs();
54458
+ const eligibleCandidateIndexes = new Set(
54459
+ accountManager.getAccounts().filter(
54460
+ (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired && !excludedIndexes?.has(entry.index)
54461
+ ).map((entry) => entry.index)
54462
+ );
54463
+ if (eligibleCandidateIndexes.size === 0) {
54464
+ waitPolicy.refusal = () => createNativeGoogleErrorResponse({
54465
+ status: 412,
54466
+ reason: "pool_unavailable"
54467
+ });
54468
+ return waitPolicy.refusal();
54469
+ }
54281
54470
  if (accountManager.areAllAccountsOverSoftQuota(
54282
54471
  family,
54283
54472
  config.soft_quota_threshold_percent,
54284
54473
  softQuotaCacheTtlMs,
54285
- model
54474
+ model,
54475
+ eligibleCandidateIndexes
54286
54476
  )) {
54287
54477
  const threshold = config.soft_quota_threshold_percent;
54288
54478
  const softQuotaWaitMs = accountManager.getMinWaitTimeForSoftQuota(
54289
54479
  family,
54290
54480
  threshold,
54291
54481
  softQuotaCacheTtlMs,
54292
- model
54482
+ model,
54483
+ eligibleCandidateIndexes
54293
54484
  );
54294
54485
  waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
54295
54486
  status: 412,
@@ -54321,7 +54512,12 @@ function createRequestExecutor(deps) {
54321
54512
  await sleep4(Math.min(softQuotaWaitMs, remainingWaitMs()), abortSignal);
54322
54513
  continue;
54323
54514
  }
54324
- const minWaitMs = accountManager.getMinWaitTimeForFamily(family, model);
54515
+ const minWaitMs = accountManager.getMinWaitTimeForFamily(
54516
+ family,
54517
+ model,
54518
+ eligibleCandidateIndexes,
54519
+ true
54520
+ );
54325
54521
  const waitMs = minWaitMs || 6e4;
54326
54522
  waitPolicy.refusal = quotaWins ? () => createNativeGoogleErrorResponse({
54327
54523
  status: 412,
@@ -54435,7 +54631,7 @@ function createRequestExecutor(deps) {
54435
54631
  await deadline.wait(() => credentials.saveToDisk());
54436
54632
  } catch (error) {
54437
54633
  checkAborted();
54438
- log16.error("Failed to persist project context", {
54634
+ log17.error("Failed to persist project context", {
54439
54635
  error: String(error)
54440
54636
  });
54441
54637
  }
@@ -54492,7 +54688,7 @@ function createRequestExecutor(deps) {
54492
54688
  await deadline.wait(() => credentials.saveToDisk());
54493
54689
  } catch (error) {
54494
54690
  checkAborted();
54495
- log16.error("Failed to persist refreshed auth", {
54691
+ log17.error("Failed to persist refreshed auth", {
54496
54692
  error: String(error)
54497
54693
  });
54498
54694
  }
@@ -54501,14 +54697,14 @@ function createRequestExecutor(deps) {
54501
54697
  if (credentials.isInvalidGrant(error)) {
54502
54698
  const removed = credentials.removeAccount(account);
54503
54699
  if (removed) {
54504
- log16.warn(
54700
+ log17.warn(
54505
54701
  "Removed revoked account from pool - reauthenticate via `opencode auth login`"
54506
54702
  );
54507
54703
  try {
54508
54704
  await deadline.wait(() => credentials.saveToDiskReplace());
54509
54705
  } catch (persistError) {
54510
54706
  checkAborted();
54511
- log16.error("Failed to persist revoked account removal", {
54707
+ log17.error("Failed to persist revoked account removal", {
54512
54708
  error: String(persistError)
54513
54709
  });
54514
54710
  }
@@ -54518,7 +54714,7 @@ function createRequestExecutor(deps) {
54518
54714
  await deadline.wait(() => credentials.clearStoredAuth());
54519
54715
  } catch (storeError) {
54520
54716
  checkAborted();
54521
- log16.error(
54717
+ log17.error(
54522
54718
  "Failed to clear stored Antigravity OAuth credentials",
54523
54719
  {
54524
54720
  error: String(storeError)
@@ -54912,7 +55108,7 @@ function createRequestExecutor(deps) {
54912
55108
  );
54913
55109
  } catch (error) {
54914
55110
  checkAborted();
54915
- log16.debug("send-admission-401-report-failed", {
55111
+ log17.debug("send-admission-401-report-failed", {
54916
55112
  error: String(error)
54917
55113
  });
54918
55114
  }
@@ -55149,7 +55345,7 @@ function createRequestExecutor(deps) {
55149
55345
  debug.logAntigravityDebugResponse(debugContext, response, {
55150
55346
  note
55151
55347
  });
55152
- log16.info("model-unavailable", {
55348
+ log17.info("model-unavailable", {
55153
55349
  accountIndex: account.index,
55154
55350
  family,
55155
55351
  model,
@@ -55604,11 +55800,11 @@ function createRequestExecutor(deps) {
55604
55800
  cancellation.signal,
55605
55801
  deps.preResponseClock
55606
55802
  );
55607
- log16.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
55803
+ log17.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
55608
55804
  const handoff = createAfterHandoff(
55609
55805
  advisoryWork,
55610
55806
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
55611
- () => log16.debug("post-response-advisory-work-failed")
55807
+ () => log17.debug("post-response-advisory-work-failed")
55612
55808
  );
55613
55809
  const waitPolicy = {};
55614
55810
  const selectedCredentials = /* @__PURE__ */ new Set();
@@ -55626,7 +55822,7 @@ function createRequestExecutor(deps) {
55626
55822
  ).catch((error) => {
55627
55823
  cancellation.signal.throwIfAborted();
55628
55824
  if (error instanceof PreResponseTimeoutError) {
55629
- log16.debug("pre-response-timeout", { reason: error.reason });
55825
+ log17.debug("pre-response-timeout", { reason: error.reason });
55630
55826
  return waitPolicy.refusal?.() ?? preResponseTimeoutResponse();
55631
55827
  }
55632
55828
  throw error;
@@ -55833,7 +56029,7 @@ function parseDurationToMs(duration) {
55833
56029
 
55834
56030
  // src/plugin/fetch-interceptor.ts
55835
56031
  init_vault_request_credentials();
55836
- var log13 = createLogger4("fetch-interceptor");
56032
+ var log14 = createLogger4("fetch-interceptor");
55837
56033
  var defaultAgyTransport = (url, init, options) => fetchWithAgyCliTransport(url, init, options);
55838
56034
  var defaultFetchImpl = (input2, init) => globalThis.fetch(input2, init);
55839
56035
  function poolFileCredentials(accountManager, client, providerId) {
@@ -55886,14 +56082,14 @@ function openCode1EngineCollaborators(common) {
55886
56082
  // the engine calls.
55887
56083
  debug: debug_exports,
55888
56084
  dump: { dumpRequest: dumpGeminiRequest },
55889
- logger: log13,
56085
+ logger: log14,
55890
56086
  classifyAccessError: extractAccountAccessErrorDetails,
55891
56087
  notify: (message, variant) => client.tui.showToast({ body: { message, variant } }),
55892
56088
  onRouting: common.onRouting ?? ((sessionId, entry) => {
55893
56089
  void upsertSidebarActiveRouting(sessionId, entry, {
55894
56090
  authoritative: true
55895
56091
  }).catch((error) => {
55896
- log13.debug("sidebar-routing-upsert-failed", {
56092
+ log14.debug("sidebar-routing-upsert-failed", {
55897
56093
  sessionId,
55898
56094
  error: String(error)
55899
56095
  });
@@ -55919,7 +56115,7 @@ function createFetchInterceptor(context) {
55919
56115
  const refreshQuotaAfterSuccess = createLocalQuotaRefresh(
55920
56116
  accountManager,
55921
56117
  quotaManager,
55922
- log13
56118
+ log14
55923
56119
  );
55924
56120
  const executor = createRequestExecutor({
55925
56121
  assertAdmission: context.assertAdmission,
@@ -56065,7 +56261,7 @@ init_logger4();
56065
56261
  // src/plugin/search.ts
56066
56262
  import crypto3 from "node:crypto";
56067
56263
  init_logger4();
56068
- var log14 = createLogger4("search");
56264
+ var log15 = createLogger4("search");
56069
56265
  var sessionCounter = 0;
56070
56266
  var sessionPrefix = `search-${Date.now().toString(36)}`;
56071
56267
  function generateRequestId() {
@@ -56197,7 +56393,7 @@ ${urlList}`;
56197
56393
  requestType: "agent"
56198
56394
  };
56199
56395
  const url = `${ANTIGRAVITY_ENDPOINT}/v1internal:generateContent`;
56200
- log14.debug("Executing search", {
56396
+ log15.debug("Executing search", {
56201
56397
  query,
56202
56398
  urlCount: urls?.length ?? 0,
56203
56399
  thinking
@@ -56220,7 +56416,7 @@ ${urlList}`;
56220
56416
  );
56221
56417
  if (!response.ok) {
56222
56418
  const errorText3 = await response.text();
56223
- log14.debug("Search API error", {
56419
+ log15.debug("Search API error", {
56224
56420
  status: response.status,
56225
56421
  error: errorText3
56226
56422
  });
@@ -56233,14 +56429,14 @@ ${errorText3}
56233
56429
  Please try again with a different query.`;
56234
56430
  }
56235
56431
  const data = await response.json();
56236
- log14.debug("Search response received", { hasResponse: !!data.response });
56432
+ log15.debug("Search response received", { hasResponse: !!data.response });
56237
56433
  const result = parseSearchResponse(data);
56238
56434
  const formatted = formatSearchResult(result);
56239
- log14.debug("Search response formatted", { resultLength: formatted.length });
56435
+ log15.debug("Search response formatted", { resultLength: formatted.length });
56240
56436
  return formatted;
56241
56437
  } catch (error) {
56242
56438
  const message = error instanceof Error ? error.message : String(error);
56243
- log14.debug("Search execution error", { error: message });
56439
+ log15.debug("Search execution error", { error: message });
56244
56440
  return `## Search Error
56245
56441
 
56246
56442
  Failed to execute search: ${message}. Please try again with a different query.`;
@@ -56248,7 +56444,7 @@ Failed to execute search: ${message}. Please try again with a different query.`;
56248
56444
  }
56249
56445
 
56250
56446
  // src/plugin/google-search-tool.ts
56251
- var log15 = createLogger4("plugin");
56447
+ var log16 = createLogger4("plugin");
56252
56448
  function createGoogleSearchTool({
56253
56449
  getAuth,
56254
56450
  client,
@@ -56270,7 +56466,7 @@ function createGoogleSearchTool({
56270
56466
  if (mayStartLocalWork && !await mayStartLocalWork()) {
56271
56467
  return "Google Search is not available through local credentials while vault custody is active or unreadable.";
56272
56468
  }
56273
- log15.debug("Google Search tool called", {
56469
+ log16.debug("Google Search tool called", {
56274
56470
  query: args.query,
56275
56471
  urlCount: args.urls?.length ?? 0
56276
56472
  });