@cortexkit/opencode-antigravity-auth 3.1.8 → 3.1.9

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 (101) hide show
  1. package/dist/cli.js +111 -77
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +71 -32
  4. package/dist/index.js +5072 -4519
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +315 -256
  7. package/dist/server.js +1018 -395
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/fs/private-files.js +8 -3
  11. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  12. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  13. package/dist/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  14. package/dist/src/common-auth-embedded/opencode2/install.js +14 -4
  15. package/dist/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  16. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  17. package/dist/src/common-auth-embedded/routing-accessor/index.js +123 -17
  18. package/dist/src/common-auth-embedded/source-output.json +35 -35
  19. package/dist/src/common-auth-embedded/store/mutate.js +34 -13
  20. package/dist/src/ga/server/index.d.ts +1 -1
  21. package/dist/src/ga/server/index.d.ts.map +1 -1
  22. package/dist/src/ga/server/index.js +58 -19
  23. package/dist/src/ga/server/index.js.map +1 -1
  24. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  25. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  26. package/dist/src/plugin/auth-loader.js +102 -80
  27. package/dist/src/plugin/auth-loader.js.map +1 -1
  28. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  29. package/dist/src/plugin/fetch-interceptor.js +27 -13
  30. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  31. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  32. package/dist/src/plugin/ga-location-services.js +21 -11
  33. package/dist/src/plugin/ga-location-services.js.map +1 -1
  34. package/dist/src/plugin/index.d.ts.map +1 -1
  35. package/dist/src/plugin/index.js +13 -5
  36. package/dist/src/plugin/index.js.map +1 -1
  37. package/dist/src/plugin/request.d.ts.map +1 -1
  38. package/dist/src/plugin/request.js +2 -2
  39. package/dist/src/plugin/request.js.map +1 -1
  40. package/dist/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  41. package/dist/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  42. package/dist/src/plugin/shared/opencode-retry-hints.js +22 -0
  43. package/dist/src/plugin/shared/opencode-retry-hints.js.map +1 -0
  44. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  45. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  46. package/dist/src/plugin/shared/request-services.js +410 -112
  47. package/dist/src/plugin/shared/request-services.js.map +1 -1
  48. package/dist/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  49. package/dist/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  50. package/dist/src/plugin/shared/vault-routing-purpose.js +13 -7
  51. package/dist/src/plugin/shared/vault-routing-purpose.js.map +1 -1
  52. package/dist/src/plugin/shared/vault-routing.d.ts +8 -1
  53. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  54. package/dist/src/plugin/shared/vault-routing.js +12 -4
  55. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  56. package/dist/src/plugin/storage.d.ts +1 -0
  57. package/dist/src/plugin/storage.d.ts.map +1 -1
  58. package/dist/src/plugin/storage.js +3 -3
  59. package/dist/src/plugin/storage.js.map +1 -1
  60. package/dist/src/plugin/vault-custody.d.ts +6 -13
  61. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  62. package/dist/src/plugin/vault-custody.js +19 -16
  63. package/dist/src/plugin/vault-custody.js.map +1 -1
  64. package/dist/tui-build-map.json +5 -5
  65. package/dist/tui-ga-build-map.json +1 -1
  66. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  67. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  68. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  69. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  70. package/dist/types/src/ga/server/index.d.ts +1 -1
  71. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  72. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  73. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  74. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  75. package/dist/types/src/plugin/index.d.ts.map +1 -1
  76. package/dist/types/src/plugin/request.d.ts.map +1 -1
  77. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  78. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  79. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  80. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  81. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  82. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  83. package/dist/types/src/plugin/shared/vault-routing.d.ts +8 -1
  84. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  85. package/dist/types/src/plugin/storage.d.ts +1 -0
  86. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  87. package/dist/types/src/plugin/vault-custody.d.ts +6 -13
  88. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  89. package/package.json +2 -2
  90. package/src/common-auth-embedded/fs/private-files.js +8 -3
  91. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  92. package/src/common-auth-embedded/opencode2/index.js +1 -1
  93. package/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  94. package/src/common-auth-embedded/opencode2/install.js +14 -4
  95. package/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  96. package/src/common-auth-embedded/routing-accessor/index.d.ts +66 -16
  97. package/src/common-auth-embedded/routing-accessor/index.js +123 -17
  98. package/src/common-auth-embedded/source-output.json +35 -35
  99. package/src/common-auth-embedded/store/mutate.js +34 -13
  100. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +8 -3
  101. package/src/tui-raw/common-auth-embedded/fs/private-files.js +8 -3
package/dist/server.js CHANGED
@@ -640,8 +640,11 @@ function loadBackend() {
640
640
  });
641
641
  return backend;
642
642
  }
643
+ function isSharingIoError(detail) {
644
+ return detail?.reason === "io-error" && (detail.win32Code === 32 || detail.win32Code === 303);
645
+ }
643
646
  function isWindowsSharingViolation(error) {
644
- return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
647
+ return windowsPrivateFiles && error instanceof PrivateFileError && isSharingIoError(error);
645
648
  }
646
649
  async function privateOperation(path5, stage, operation) {
647
650
  try {
@@ -763,12 +766,12 @@ async function replaceWindowsFile(from, to, options = {}) {
763
766
  const delays = [0, 10, 20, 40, 80, 100];
764
767
  let original;
765
768
  let attempts2 = 0;
766
- for (const delay4 of delays) {
769
+ for (const delay5 of delays) {
767
770
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
768
771
  if (now2() >= deadline)
769
772
  break;
770
- if (delay4)
771
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now2())));
773
+ if (delay5)
774
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay5, Math.max(0, deadline - now2())));
772
775
  if (now2() >= deadline)
773
776
  break;
774
777
  const fenceStart = now2();
@@ -891,7 +894,7 @@ var init_private_files = __esm({
891
894
  // The reason stays on `.reason`: its word "unavailable" would make
892
895
  // OpenCode 1 retry a plain error carrying this message.
893
896
  `Private file refused at ${stage}: ${path5}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
894
- ) : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
897
+ ) : isSharingIoError(detail) ? `Private file busy at ${stage}: ${path5}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
895
898
  this.path = path5;
896
899
  this.stage = stage;
897
900
  this.name = "PrivateFileError";
@@ -4569,8 +4572,8 @@ var init_model_registry = __esm({
4569
4572
  // ../core/dist/rotation.js
4570
4573
  function unconfirmedRateLimitDelayMs(retryAfter, now2 = Date.now()) {
4571
4574
  const value = retryAfter?.trim();
4572
- const delay4 = value ? /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - now2 : Number.NaN;
4573
- return Number.isFinite(delay4) ? Math.min(UNCONFIRMED_RATE_LIMIT_MAX_MS, Math.max(UNCONFIRMED_RATE_LIMIT_MIN_MS, delay4)) : UNCONFIRMED_RATE_LIMIT_MIN_MS;
4575
+ const delay5 = value ? /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - now2 : Number.NaN;
4576
+ return Number.isFinite(delay5) ? Math.min(UNCONFIRMED_RATE_LIMIT_MAX_MS, Math.max(UNCONFIRMED_RATE_LIMIT_MIN_MS, delay5)) : UNCONFIRMED_RATE_LIMIT_MIN_MS;
4574
4577
  }
4575
4578
  function parseRateLimitReason(reason, message, status) {
4576
4579
  if (status === 529 || status === 503)
@@ -5358,6 +5361,7 @@ var init_account_selector = __esm({
5358
5361
  const state2 = {
5359
5362
  parentId: identity4.parentId ?? null,
5360
5363
  currentAccountIndexByFamily: { claude: -1, gemini: -1 },
5364
+ routedByFamily: { claude: false, gemini: false },
5361
5365
  cursorByFamily: { ...this.cursorByFamily },
5362
5366
  offsetAppliedByFamily: { claude: false, gemini: false },
5363
5367
  usedAccounts: /* @__PURE__ */ new Set(),
@@ -5391,13 +5395,14 @@ var init_account_selector = __esm({
5391
5395
  getActiveIndex(family, identity4) {
5392
5396
  return identity4 ? this.getRequestSessionState(identity4).currentAccountIndexByFamily[family] : this.currentAccountIndexByFamily[family];
5393
5397
  }
5394
- setActiveIndex(family, index, identity4) {
5398
+ setActiveIndex(family, index, identity4, routed = false) {
5395
5399
  if (!identity4) {
5396
5400
  this.setGlobalActiveIndex(family, index);
5397
5401
  return;
5398
5402
  }
5399
5403
  const state2 = this.getRequestSessionState(identity4);
5400
5404
  state2.currentAccountIndexByFamily[family] = index;
5405
+ state2.routedByFamily[family] = routed;
5401
5406
  if (!state2.parentId) {
5402
5407
  this.setGlobalActiveIndex(family, index);
5403
5408
  }
@@ -5451,6 +5456,18 @@ var init_account_selector = __esm({
5451
5456
  }
5452
5457
  return null;
5453
5458
  }
5459
+ getRoutedAccountForFamily(family, identity4) {
5460
+ return this.getRequestSessionState(identity4).routedByFamily[family] ? this.getCurrentAccountForFamily(family, identity4) : null;
5461
+ }
5462
+ /** Use a roster row already admitted by routing, without local quota or retry filters. */
5463
+ useRoutedAccount(account, family, model, identity4, pinSelection) {
5464
+ if (this.accounts[account.index] !== account || account.enabled === false || account.accountIneligible || account.verificationRequired)
5465
+ return null;
5466
+ this.markTouchedForQuota(account, getQuotaKey(family, model));
5467
+ if (pinSelection)
5468
+ this.setActiveIndex(family, account.index, identity4, true);
5469
+ return account;
5470
+ }
5454
5471
  /**
5455
5472
  * Numeric active indexes for each model family. Exposed so callers
5456
5473
  * that persist `activeIndexByFamily` (e.g. command-data's remove
@@ -5486,7 +5503,7 @@ var init_account_selector = __esm({
5486
5503
  this.lastToastAccountIndex = accountIndex;
5487
5504
  this.lastToastTime = this.now();
5488
5505
  }
5489
- getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes) {
5506
+ getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes, pinSelection = true) {
5490
5507
  const quotaKey = getQuotaKey(family, model);
5491
5508
  const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent, excludeIndexes);
5492
5509
  if (identity4) {
@@ -5495,6 +5512,8 @@ var init_account_selector = __esm({
5495
5512
  clearExpiredRateLimits(pinned, this.now);
5496
5513
  const unavailable2 = (excludeIndexes?.has(pinned.index) ?? false) || isRateLimitedForFamily(pinned, family, this.now, model) || isOverSoftQuotaThreshold(pinned, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model) || this.isAccountCoolingDown(pinned);
5497
5514
  if (!unavailable2) {
5515
+ if (pinSelection)
5516
+ this.getRequestSessionState(identity4).routedByFamily[family] = false;
5498
5517
  this.markTouchedForQuota(pinned, quotaKey);
5499
5518
  return pinned;
5500
5519
  }
@@ -5504,7 +5523,8 @@ var init_account_selector = __esm({
5504
5523
  const next2 = this.getNextForFamily(family, model, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, identity4, excludeIndexes);
5505
5524
  if (next2) {
5506
5525
  this.markTouchedForQuota(next2, quotaKey);
5507
- this.setActiveIndex(family, next2.index, identity4);
5526
+ if (pinSelection)
5527
+ this.setActiveIndex(family, next2.index, identity4);
5508
5528
  }
5509
5529
  return next2;
5510
5530
  }
@@ -5532,12 +5552,14 @@ var init_account_selector = __esm({
5532
5552
  if (selected) {
5533
5553
  this.touchLastUsed(selected);
5534
5554
  this.markTouchedForQuota(selected, quotaKey);
5535
- this.setActiveIndex(family, selected.index, identity4);
5555
+ if (pinSelection)
5556
+ this.setActiveIndex(family, selected.index, identity4);
5536
5557
  return selected;
5537
5558
  }
5538
5559
  }
5539
5560
  }
5540
5561
  const offsetApplied = identity4 ? this.getRequestSessionState(identity4).offsetAppliedByFamily : this.sessionOffsetApplied;
5562
+ let temporaryIndex;
5541
5563
  if (pidOffsetEnabled && !offsetApplied[family] && this.accounts.length > 1) {
5542
5564
  const pidOffset = this.pid % this.accounts.length;
5543
5565
  const activeIndex = this.getActiveIndex(family, identity4);
@@ -5550,10 +5572,14 @@ var init_account_selector = __esm({
5550
5572
  fromIndex: baseIndex,
5551
5573
  toIndex: newIndex
5552
5574
  });
5553
- this.setActiveIndex(family, newIndex, identity4);
5554
- offsetApplied[family] = true;
5575
+ if (pinSelection) {
5576
+ this.setActiveIndex(family, newIndex, identity4);
5577
+ offsetApplied[family] = true;
5578
+ } else {
5579
+ temporaryIndex = newIndex;
5580
+ }
5555
5581
  }
5556
- const current = this.getCurrentAccountForFamily(family, identity4);
5582
+ const current = temporaryIndex === void 0 ? this.getCurrentAccountForFamily(family, identity4) : this.accounts[temporaryIndex] ?? null;
5557
5583
  const preferred = preferArgonAccounts(this.accounts.filter((row) => row.enabled !== false && !row.accountIneligible && !row.verificationRequired && !excludeIndexes?.has(row.index) && !isRateLimitedForFamily(row, family, this.now, model) && !this.isAccountCoolingDown(row) && !isOverSoftQuotaThreshold(row, family, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, this.now, model)), model);
5558
5584
  if (current && preferred.includes(current)) {
5559
5585
  clearExpiredRateLimits(current, this.now);
@@ -5567,7 +5593,8 @@ var init_account_selector = __esm({
5567
5593
  const next = this.getNextForFamily(family, model, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, identity4, excludeIndexes);
5568
5594
  if (next) {
5569
5595
  this.markTouchedForQuota(next, quotaKey);
5570
- this.setActiveIndex(family, next.index, identity4);
5596
+ if (pinSelection)
5597
+ this.setActiveIndex(family, next.index, identity4);
5571
5598
  }
5572
5599
  return next;
5573
5600
  }
@@ -8917,9 +8944,9 @@ async function acquireWithRetry(path5, sleep5) {
8917
8944
  return lock;
8918
8945
  }
8919
8946
  if (attempt < RETRY_DELAYS_MS.length) {
8920
- const delay4 = RETRY_DELAYS_MS[attempt];
8921
- if (delay4 !== void 0) {
8922
- await sleep5(delay4);
8947
+ const delay5 = RETRY_DELAYS_MS[attempt];
8948
+ if (delay5 !== void 0) {
8949
+ await sleep5(delay5);
8923
8950
  }
8924
8951
  }
8925
8952
  }
@@ -10000,6 +10027,12 @@ var init_account_manager = __esm({
10000
10027
  getCurrentAccountForFamily(family, identity4) {
10001
10028
  return this.selection.getCurrentAccountForFamily(family, identity4);
10002
10029
  }
10030
+ getRoutedAccountForFamily(family, identity4) {
10031
+ return this.selection.getRoutedAccountForFamily(family, identity4);
10032
+ }
10033
+ useRoutedAccount(account, family, model, identity4, pinSelection) {
10034
+ return this.selection.useRoutedAccount(account, family, model, identity4, pinSelection);
10035
+ }
10003
10036
  /**
10004
10037
  * Numeric active indexes for each model family. Exposed so callers
10005
10038
  * that persist `activeIndexByFamily` (e.g. command-data's remove
@@ -10022,8 +10055,8 @@ var init_account_manager = __esm({
10022
10055
  markToastShown(accountIndex) {
10023
10056
  this.selection.markToastShown(accountIndex);
10024
10057
  }
10025
- getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes) {
10026
- return this.selection.getCurrentOrNextForFamily(family, model, strategy, pidOffsetEnabled, softQuotaThresholdPercent, softQuotaCacheTtlMs, identity4, excludeIndexes);
10058
+ getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes, pinSelection = true) {
10059
+ return this.selection.getCurrentOrNextForFamily(family, model, strategy, pidOffsetEnabled, softQuotaThresholdPercent, softQuotaCacheTtlMs, identity4, excludeIndexes, pinSelection);
10027
10060
  }
10028
10061
  getNextForFamily(family, model, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes) {
10029
10062
  return this.selection.getNextForFamily(family, model, softQuotaThresholdPercent, softQuotaCacheTtlMs, identity4, excludeIndexes);
@@ -15458,14 +15491,19 @@ var init_torn = __esm({
15458
15491
  });
15459
15492
 
15460
15493
  // ../core/dist/common-auth-embedded/store/mutate.js
15461
- import { setTimeout as snapshotDelay } from "node:timers/promises";
15494
+ import { setTimeout as delay } from "node:timers/promises";
15462
15495
  async function readText(path5) {
15463
- try {
15464
- return await readPrivateText(path5, windowsPrivateFiles);
15465
- } catch (error) {
15466
- if (error.code === "ENOENT")
15467
- return void 0;
15468
- throw error;
15496
+ for (let attempt = 0; ; attempt++) {
15497
+ try {
15498
+ return await readPrivateText(path5, windowsPrivateFiles);
15499
+ } catch (error) {
15500
+ if (error.code === "ENOENT")
15501
+ return void 0;
15502
+ const wait2 = sharingRetryDelays[attempt];
15503
+ if (wait2 === void 0 || !isWindowsSharingViolation(error))
15504
+ throw error;
15505
+ await delay(wait2);
15506
+ }
15469
15507
  }
15470
15508
  }
15471
15509
  function parseFile(text2) {
@@ -15482,12 +15520,21 @@ async function readPoolConfig(path5) {
15482
15520
  }
15483
15521
  async function readPool(ctx) {
15484
15522
  for (let attempt = 0; attempt < 3; attempt++) {
15485
- const configText = await readText(ctx.configPath);
15486
- const stateText = await readText(ctx.statePath);
15487
- const checkedConfigText = await readText(ctx.configPath);
15523
+ let configText;
15524
+ let stateText;
15525
+ let checkedConfigText;
15526
+ try {
15527
+ configText = await readText(ctx.configPath);
15528
+ stateText = await readText(ctx.statePath);
15529
+ checkedConfigText = await readText(ctx.configPath);
15530
+ } catch (error) {
15531
+ if (isWindowsSharingViolation(error))
15532
+ break;
15533
+ throw error;
15534
+ }
15488
15535
  if (configText !== checkedConfigText) {
15489
15536
  if (attempt < 2)
15490
- await snapshotDelay(2 + Math.floor(Math.random() * 4));
15537
+ await delay(2 + Math.floor(Math.random() * 4));
15491
15538
  continue;
15492
15539
  }
15493
15540
  const config = classifyConfig(parseFile(configText));
@@ -15667,7 +15714,7 @@ async function runOperation(ctx, operation, rowId2, onFailure, body) {
15667
15714
  await locks.releaseAll();
15668
15715
  }
15669
15716
  }
15670
- var Transaction;
15717
+ var sharingRetryDelays, Transaction;
15671
15718
  var init_mutate = __esm({
15672
15719
  "../core/dist/common-auth-embedded/store/mutate.js"() {
15673
15720
  "use strict";
@@ -15680,6 +15727,7 @@ var init_mutate = __esm({
15680
15727
  init_reserved();
15681
15728
  init_schema();
15682
15729
  init_torn();
15730
+ sharingRetryDelays = [5, 10, 20, 40, 80, 160, 320, 400];
15683
15731
  Transaction = class {
15684
15732
  ctx;
15685
15733
  snapshot;
@@ -17631,11 +17679,11 @@ var init_quota_writer = __esm({
17631
17679
  overlay(rows) {
17632
17680
  return rows.map((row) => this.overlayRow(row));
17633
17681
  }
17634
- schedule(delay4) {
17682
+ schedule(delay5) {
17635
17683
  if (this.running || this.timer || !this.pending.size || this.stopped)
17636
17684
  return;
17637
17685
  const remaining = this.closed ? 0 : (this.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - this.clock.now();
17638
- this.timer = this.clock.schedule(Math.max(delay4, remaining), () => {
17686
+ this.timer = this.clock.schedule(Math.max(delay5, remaining), () => {
17639
17687
  this.timer = void 0;
17640
17688
  return this.flush();
17641
17689
  });
@@ -17735,8 +17783,8 @@ var init_quota_writer = __esm({
17735
17783
  this.running = void 0;
17736
17784
  for (const wake of this.wake)
17737
17785
  wake();
17738
- const delay4 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
17739
- this.schedule(delay4);
17786
+ const delay5 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
17787
+ this.schedule(delay5);
17740
17788
  }
17741
17789
  })();
17742
17790
  return this.running;
@@ -21424,12 +21472,12 @@ var init_watch = __esm({
21424
21472
  this.#options.logger?.debug("claustrum vault watch", { mode, reason });
21425
21473
  this.#options.onMode?.(mode);
21426
21474
  }
21427
- #later(delay4, run) {
21475
+ #later(delay5, run) {
21428
21476
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
21429
21477
  this.#timer = void 0;
21430
21478
  if (!this.#stopped)
21431
21479
  run();
21432
- }, delay4);
21480
+ }, delay5);
21433
21481
  this.#timer.unref?.();
21434
21482
  }
21435
21483
  async #open(resubscribed) {
@@ -21501,10 +21549,10 @@ var init_watch = __esm({
21501
21549
  const now2 = (this.#options.now ?? Date.now)();
21502
21550
  if (watch2.acceptedAt !== void 0 && now2 - watch2.acceptedAt >= SAFETY_POLL_MS)
21503
21551
  this.#closes = 0;
21504
- const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21552
+ const delay5 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21505
21553
  this.#closes++;
21506
21554
  this.#setMode("polling", "resubscribing");
21507
- this.#later(delay4, () => void this.#open(true));
21555
+ this.#later(delay5, () => void this.#open(true));
21508
21556
  return;
21509
21557
  }
21510
21558
  this.#fallback(end.kind);
@@ -21795,12 +21843,12 @@ var init_insula = __esm({
21795
21843
  watch2?.handle?.stop();
21796
21844
  this.#mode = "polling";
21797
21845
  }
21798
- #later(delay4) {
21846
+ #later(delay5) {
21799
21847
  this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
21800
21848
  this.#timer = void 0;
21801
21849
  if (this.#watchers > 0 && !this.#watch)
21802
21850
  this.#open();
21803
- }, delay4);
21851
+ }, delay5);
21804
21852
  this.#timer.unref?.();
21805
21853
  }
21806
21854
  #open() {
@@ -21848,10 +21896,10 @@ var init_insula = __esm({
21848
21896
  return;
21849
21897
  }
21850
21898
  if (watch2.notices > 0) {
21851
- const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21899
+ const delay5 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21852
21900
  this.#closes++;
21853
21901
  this.#mode = "polling";
21854
- this.#later(delay4);
21902
+ this.#later(delay5);
21855
21903
  return;
21856
21904
  }
21857
21905
  this.#mode = "fallback";
@@ -23540,9 +23588,9 @@ var init_custody = __esm({
23540
23588
  users: 0,
23541
23589
  error,
23542
23590
  pending: Promise.resolve().then(async () => {
23543
- let delay4 = 250;
23591
+ let delay5 = 250;
23544
23592
  for (; ; ) {
23545
- await this.#receiptBackoff(delay4, controller.signal);
23593
+ await this.#receiptBackoff(delay5, controller.signal);
23546
23594
  try {
23547
23595
  return await this.#authorizeFresh(identity4, token, controller.signal);
23548
23596
  } catch (failure2) {
@@ -23550,7 +23598,7 @@ var init_custody = __esm({
23550
23598
  if (classifyVaultFailure(failure2) !== "unreachable")
23551
23599
  throw failure2;
23552
23600
  created.error = failure2;
23553
- delay4 = Math.min(delay4 * 2, 1e3);
23601
+ delay5 = Math.min(delay5 * 2, 1e3);
23554
23602
  }
23555
23603
  }
23556
23604
  })
@@ -23604,7 +23652,7 @@ var init_custody = __esm({
23604
23652
  }
23605
23653
  }
23606
23654
  }
23607
- #receiptBackoff(delay4, signal) {
23655
+ #receiptBackoff(delay5, signal) {
23608
23656
  this.#check(signal);
23609
23657
  return new Promise((resolve34, reject) => {
23610
23658
  const abort = () => {
@@ -23615,7 +23663,7 @@ var init_custody = __esm({
23615
23663
  const timer = this.#setTimeout(() => {
23616
23664
  signal.removeEventListener("abort", abort);
23617
23665
  resolve34();
23618
- }, delay4);
23666
+ }, delay5);
23619
23667
  timer.unref?.();
23620
23668
  signal.addEventListener("abort", abort, { once: true });
23621
23669
  if (signal.aborted)
@@ -24639,11 +24687,11 @@ function pendingVaultQuota(path5, roster) {
24639
24687
  function hasPendingVaultQuota(path5) {
24640
24688
  return !!writers.get(resolve11(path5))?.pending.size;
24641
24689
  }
24642
- function schedule(writer, delay4) {
24690
+ function schedule(writer, delay5) {
24643
24691
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
24644
24692
  return;
24645
24693
  const remaining = writer.draining ? 0 : (writer.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - writer.clock.now();
24646
- writer.timer = writer.clock.schedule(Math.max(delay4, remaining), () => {
24694
+ writer.timer = writer.clock.schedule(Math.max(delay5, remaining), () => {
24647
24695
  writer.timer = void 0;
24648
24696
  return flush(writer);
24649
24697
  });
@@ -25080,13 +25128,13 @@ var init_consumer = __esm({
25080
25128
  }
25081
25129
  if (this.#shutdown.signal.aborted)
25082
25130
  return;
25083
- const delay4 = this.#options.pollIntervalMs ?? 5e3;
25084
- if (delay4 <= 0)
25131
+ const delay5 = this.#options.pollIntervalMs ?? 5e3;
25132
+ if (delay5 <= 0)
25085
25133
  return;
25086
25134
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
25087
25135
  this.#timer = void 0;
25088
25136
  void this.#track(tick());
25089
- }, delay4);
25137
+ }, delay5);
25090
25138
  this.#timer.unref?.();
25091
25139
  };
25092
25140
  void this.#track(tick());
@@ -26556,13 +26604,13 @@ var init_hub = __esm({
26556
26604
  }
26557
26605
  if (this.#shutdown.signal.aborted)
26558
26606
  return;
26559
- const delay4 = this.#options.pollIntervalMs ?? 5e3;
26560
- if (delay4 <= 0)
26607
+ const delay5 = this.#options.pollIntervalMs ?? 5e3;
26608
+ if (delay5 <= 0)
26561
26609
  return;
26562
26610
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
26563
26611
  this.#timer = void 0;
26564
26612
  void this.#track(this.#tick());
26565
- }, delay4);
26613
+ }, delay5);
26566
26614
  this.#timer.unref?.();
26567
26615
  }
26568
26616
  /**
@@ -26853,12 +26901,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
26853
26901
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
26854
26902
  compromise();
26855
26903
  }
26856
- function schedule2(delay4 = UPDATE) {
26904
+ function schedule2(delay5 = UPDATE) {
26857
26905
  if (released)
26858
26906
  return;
26859
26907
  timer = setTimeout(() => {
26860
26908
  void update();
26861
- }, delay4);
26909
+ }, delay5);
26862
26910
  timer.unref();
26863
26911
  }
26864
26912
  function retry(error) {
@@ -27638,31 +27686,6 @@ var init_harness_identity = __esm({
27638
27686
  }
27639
27687
  });
27640
27688
 
27641
- // ../core/dist/model-types.js
27642
- var init_model_types = __esm({
27643
- "../core/dist/model-types.js"() {
27644
- "use strict";
27645
- }
27646
- });
27647
-
27648
- // ../core/dist/pi-paths.js
27649
- import { homedir } from "node:os";
27650
- import { dirname as dirname13, join as join10 } from "node:path";
27651
- function getPiConfigDir() {
27652
- return process.env.PI_AGENT_DIR?.trim() || join10(homedir(), ".pi", "agent");
27653
- }
27654
- function getPiAntigravityAuthFile() {
27655
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join10(getPiConfigDir(), "antigravity-accounts.json");
27656
- }
27657
- function getPiAntigravityVaultDir() {
27658
- return join10(dirname13(getPiAntigravityAuthFile()), "antigravity-auth-vault");
27659
- }
27660
- var init_pi_paths = __esm({
27661
- "../core/dist/pi-paths.js"() {
27662
- "use strict";
27663
- }
27664
- });
27665
-
27666
27689
  // ../core/dist/pre-response-deadline.js
27667
27690
  function preResponseTimeoutResponse() {
27668
27691
  return new Response(JSON.stringify({
@@ -27818,6 +27841,150 @@ var init_pre_response_deadline = __esm({
27818
27841
  }
27819
27842
  });
27820
27843
 
27844
+ // ../core/dist/vault-folder-refusal.js
27845
+ function sharedVaultTokenFolder(error) {
27846
+ if (!(error instanceof Error))
27847
+ return void 0;
27848
+ const client = CLIENT_REFUSAL.exec(error.message);
27849
+ if (client?.[1] && client[2] && SHARED_FOLDER_REASON.test(client[2]))
27850
+ return client[1];
27851
+ const embedded = EMBEDDED_REFUSAL.exec(error.message);
27852
+ if (embedded?.[1])
27853
+ return embedded[1];
27854
+ return void 0;
27855
+ }
27856
+ function sharedVaultTokenFolderText(folder) {
27857
+ return `The vault key can't be saved because the folder ${folder} can be changed by other users. Make that folder owned by you and not writable by your group or by others, then try again.`;
27858
+ }
27859
+ function sharedVaultTokenFolderOutcome(error) {
27860
+ const folder = sharedVaultTokenFolder(error);
27861
+ return folder === void 0 ? void 0 : {
27862
+ ok: false,
27863
+ text: sharedVaultTokenFolderText(folder),
27864
+ code: SHARED_VAULT_TOKEN_FOLDER_CODE
27865
+ };
27866
+ }
27867
+ var CLIENT_REFUSAL, SHARED_FOLDER_REASON, EMBEDDED_REFUSAL, SHARED_VAULT_TOKEN_FOLDER_CODE;
27868
+ var init_vault_folder_refusal = __esm({
27869
+ "../core/dist/vault-folder-refusal.js"() {
27870
+ "use strict";
27871
+ CLIENT_REFUSAL = /^enrollment token folder (.+) is not private: (.+)$/s;
27872
+ SHARED_FOLDER_REASON = /^(?:foreign owner|world-writable ancestor|group-writable ancestor|could not (?:read|parse) \S+ to establish a user-private group)/;
27873
+ EMBEDDED_REFUSAL = /^Claustrum enrollment path has a writable ancestor: (.+?)\. Another user could replace it\./s;
27874
+ SHARED_VAULT_TOKEN_FOLDER_CODE = "vault-folder-shared";
27875
+ }
27876
+ });
27877
+
27878
+ // ../core/dist/host-failure.js
27879
+ function markUpstreamFailure(error) {
27880
+ const failure2 = error instanceof Error ? error : new Error(String(error));
27881
+ upstreamFailures.add(failure2);
27882
+ return failure2;
27883
+ }
27884
+ function isUpstreamFailure(error) {
27885
+ return error instanceof Error && upstreamFailures.has(error);
27886
+ }
27887
+ function errorChain(error) {
27888
+ const chain = [];
27889
+ for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {
27890
+ chain.push(current);
27891
+ }
27892
+ return chain;
27893
+ }
27894
+ function failureMessage2(chain) {
27895
+ if (chain.some((error) => error.name === "PiSlotError"))
27896
+ return HOST_CREDENTIAL_SLOT_FAILURE;
27897
+ if (chain.some((error) => [
27898
+ "LockContentionError",
27899
+ "LockOwnershipError",
27900
+ "FileLockOwnershipError",
27901
+ "AccountStorageLockContentionError"
27902
+ ].includes(error.name) || error instanceof AccountRepositoryError && ["lock-contention", "lock-ownership"].includes(error.failure.kind)))
27903
+ return HOST_STORE_LOCK_FAILURE;
27904
+ if (chain.some((error) => sharedVaultTokenFolder(error) !== void 0))
27905
+ return HOST_VAULT_FOLDER_FAILURE;
27906
+ if (chain.some((error) => error instanceof AccountRepositoryError || [
27907
+ "PrivateFileError",
27908
+ "AccountStorageUnreadableError",
27909
+ "AccountStoreNotReadyError",
27910
+ "AccountStoreAdmissionError"
27911
+ ].includes(error.name)))
27912
+ return HOST_STORE_READ_FAILURE;
27913
+ return HOST_REQUEST_FAILURE;
27914
+ }
27915
+ function diagnostics(chain, error) {
27916
+ const messages = chain.length ? chain.map((entry) => {
27917
+ const details = entry;
27918
+ return [
27919
+ entry.name,
27920
+ details.code,
27921
+ entry.message,
27922
+ ...[
27923
+ details.path,
27924
+ details.details?.path,
27925
+ details.details?.target
27926
+ ].filter((path5) => path5 && !entry.message.includes(path5)),
27927
+ details.details?.backupPath,
27928
+ details.details?.reason
27929
+ ].filter(Boolean).join(": ");
27930
+ }) : [String(error)];
27931
+ return redactCredentialText([...new Set(messages)].join("; caused by "));
27932
+ }
27933
+ function hostFailure(error, log18) {
27934
+ if (error instanceof HostRefusalError || error instanceof AccountStoreBusyError || error instanceof PreResponseTimeoutError || isUpstreamFailure(error) || error instanceof Error && error.name === "ClaustrumUnreachableError" && error.message === "Claustrum vault could not be reached")
27935
+ return error;
27936
+ const chain = errorChain(error);
27937
+ log18(diagnostics(chain, error));
27938
+ if (error instanceof Error && error.name === "ClaustrumCredentialError" && "code" in error && error.code === "grant_denied") {
27939
+ return Object.assign(new HostRefusalError("The vault refused access to the selected account. Check the plugin log for details."), { code: "grant_denied" });
27940
+ }
27941
+ return new HostRefusalError(failureMessage2(chain));
27942
+ }
27943
+ var HOST_STORE_READ_FAILURE, HOST_STORE_LOCK_FAILURE, HOST_CREDENTIAL_SLOT_FAILURE, HOST_VAULT_FOLDER_FAILURE, HOST_REQUEST_FAILURE, HostRefusalError, upstreamFailures;
27944
+ var init_host_failure = __esm({
27945
+ "../core/dist/host-failure.js"() {
27946
+ "use strict";
27947
+ init_account_migration();
27948
+ init_account_repository();
27949
+ init_credential_redaction();
27950
+ init_pre_response_deadline();
27951
+ init_vault_folder_refusal();
27952
+ HOST_STORE_READ_FAILURE = "antigravity-auth could not read its account store. Check the plugin log for details.";
27953
+ HOST_STORE_LOCK_FAILURE = "antigravity-auth could not secure its account store. Check the plugin log for details.";
27954
+ HOST_CREDENTIAL_SLOT_FAILURE = "antigravity-auth could not update the host credential slot. Check the plugin log for details.";
27955
+ HOST_VAULT_FOLDER_FAILURE = "antigravity-auth could not use its vault folder. Check the plugin log for details.";
27956
+ HOST_REQUEST_FAILURE = "antigravity-auth could not complete the operation. Check the plugin log for details.";
27957
+ HostRefusalError = class extends Error {
27958
+ };
27959
+ upstreamFailures = /* @__PURE__ */ new WeakSet();
27960
+ }
27961
+ });
27962
+
27963
+ // ../core/dist/model-types.js
27964
+ var init_model_types = __esm({
27965
+ "../core/dist/model-types.js"() {
27966
+ "use strict";
27967
+ }
27968
+ });
27969
+
27970
+ // ../core/dist/pi-paths.js
27971
+ import { homedir } from "node:os";
27972
+ import { dirname as dirname13, join as join10 } from "node:path";
27973
+ function getPiConfigDir() {
27974
+ return process.env.PI_AGENT_DIR?.trim() || join10(homedir(), ".pi", "agent");
27975
+ }
27976
+ function getPiAntigravityAuthFile() {
27977
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join10(getPiConfigDir(), "antigravity-accounts.json");
27978
+ }
27979
+ function getPiAntigravityVaultDir() {
27980
+ return join10(dirname13(getPiAntigravityAuthFile()), "antigravity-auth-vault");
27981
+ }
27982
+ var init_pi_paths = __esm({
27983
+ "../core/dist/pi-paths.js"() {
27984
+ "use strict";
27985
+ }
27986
+ });
27987
+
27821
27988
  // ../core/dist/project.js
27822
27989
  function buildBootstrapRequestBody(extra = {}) {
27823
27990
  return {
@@ -30569,40 +30736,6 @@ var init_vault_enrollment_authority = __esm({
30569
30736
  }
30570
30737
  });
30571
30738
 
30572
- // ../core/dist/vault-folder-refusal.js
30573
- function sharedVaultTokenFolder(error) {
30574
- if (!(error instanceof Error))
30575
- return void 0;
30576
- const client = CLIENT_REFUSAL.exec(error.message);
30577
- if (client?.[1] && client[2] && SHARED_FOLDER_REASON.test(client[2]))
30578
- return client[1];
30579
- const embedded = EMBEDDED_REFUSAL.exec(error.message);
30580
- if (embedded?.[1])
30581
- return embedded[1];
30582
- return void 0;
30583
- }
30584
- function sharedVaultTokenFolderText(folder) {
30585
- return `The vault key can't be saved because the folder ${folder} can be changed by other users. Make that folder owned by you and not writable by your group or by others, then try again.`;
30586
- }
30587
- function sharedVaultTokenFolderOutcome(error) {
30588
- const folder = sharedVaultTokenFolder(error);
30589
- return folder === void 0 ? void 0 : {
30590
- ok: false,
30591
- text: sharedVaultTokenFolderText(folder),
30592
- code: SHARED_VAULT_TOKEN_FOLDER_CODE
30593
- };
30594
- }
30595
- var CLIENT_REFUSAL, SHARED_FOLDER_REASON, EMBEDDED_REFUSAL, SHARED_VAULT_TOKEN_FOLDER_CODE;
30596
- var init_vault_folder_refusal = __esm({
30597
- "../core/dist/vault-folder-refusal.js"() {
30598
- "use strict";
30599
- CLIENT_REFUSAL = /^enrollment token folder (.+) is not private: (.+)$/s;
30600
- SHARED_FOLDER_REASON = /^(?:foreign owner|world-writable ancestor|group-writable ancestor|could not (?:read|parse) \S+ to establish a user-private group)/;
30601
- EMBEDDED_REFUSAL = /^Claustrum enrollment path has a writable ancestor: (.+?)\. Another user could replace it\./s;
30602
- SHARED_VAULT_TOKEN_FOLDER_CODE = "vault-folder-shared";
30603
- }
30604
- });
30605
-
30606
30739
  // ../core/dist/version.js
30607
30740
  function parseVersion(text2) {
30608
30741
  const match = text2.match(VERSION_REGEX);
@@ -30699,6 +30832,7 @@ var init_dist = __esm({
30699
30832
  init_file_lock();
30700
30833
  init_fingerprint();
30701
30834
  init_harness_identity();
30835
+ init_host_failure();
30702
30836
  init_logger();
30703
30837
  init_model_registry();
30704
30838
  init_model_types();
@@ -30763,8 +30897,11 @@ function loadBackend2() {
30763
30897
  });
30764
30898
  return backend2;
30765
30899
  }
30900
+ function isSharingIoError2(detail) {
30901
+ return detail?.reason === "io-error" && (detail.win32Code === 32 || detail.win32Code === 303);
30902
+ }
30766
30903
  function isWindowsSharingViolation2(error) {
30767
- return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
30904
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && isSharingIoError2(error);
30768
30905
  }
30769
30906
  async function privateOperation2(path5, stage, operation) {
30770
30907
  try {
@@ -30886,12 +31023,12 @@ async function replaceWindowsFile2(from, to, options = {}) {
30886
31023
  const delays = [0, 10, 20, 40, 80, 100];
30887
31024
  let original;
30888
31025
  let attempts2 = 0;
30889
- for (const delay4 of delays) {
31026
+ for (const delay5 of delays) {
30890
31027
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
30891
31028
  if (now2() >= deadline)
30892
31029
  break;
30893
- if (delay4)
30894
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now2())));
31030
+ if (delay5)
31031
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay5, Math.max(0, deadline - now2())));
30895
31032
  if (now2() >= deadline)
30896
31033
  break;
30897
31034
  const fenceStart = now2();
@@ -31014,7 +31151,7 @@ var init_private_files2 = __esm({
31014
31151
  // The reason stays on `.reason`: its word "unavailable" would make
31015
31152
  // OpenCode 1 retry a plain error carrying this message.
31016
31153
  `Private file refused at ${stage}: ${path5}. The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
31017
- ) : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
31154
+ ) : isSharingIoError2(detail) ? `Private file busy at ${stage}: ${path5}. Another process was replacing or deleting this file at the same moment (Windows error ${detail.win32Code}).` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
31018
31155
  this.path = path5;
31019
31156
  this.stage = stage;
31020
31157
  this.name = "PrivateFileError";
@@ -32715,14 +32852,24 @@ function emptyRosterGuidance(cause, principal) {
32715
32852
  ];
32716
32853
  }
32717
32854
  }
32718
- function openCodeEmptyVaultRosterRefusal(cause, principal = OPENCODE_VAULT_ENROLLMENT_NAME) {
32719
- return cause === "unknown" ? void 0 : emptyRosterGuidance(cause, principal).join("\n");
32855
+ function openCodeEmptyVaultRosterRefusal(cause) {
32856
+ switch (cause) {
32857
+ case "no-grant":
32858
+ return "Vault access is approved, but the vault has not granted this plugin read access. Open the Vault section of the Antigravity menu for grant instructions.";
32859
+ case "grant-reaches-nothing":
32860
+ return [
32861
+ "Vault access is approved, but the read grant reaches no Antigravity login in the vault.",
32862
+ `The vault operator updates the vault's logins with: ${VAULT_RECLASSIFY_COMMAND}`,
32863
+ `Then they check them with: ${VAULT_STATUS_COMMAND}`
32864
+ ].join("\n");
32865
+ case "unknown":
32866
+ return void 0;
32867
+ }
32720
32868
  }
32721
32869
  function createOpenCodeVaultAccountPool(options) {
32722
- const { grantPrincipal: principal, ...poolOptions } = options;
32723
32870
  return createVaultAccountPool({
32724
- ...poolOptions,
32725
- emptyRosterRefusal: (cause) => openCodeEmptyVaultRosterRefusal(cause, principal?.())
32871
+ ...options,
32872
+ emptyRosterRefusal: openCodeEmptyVaultRosterRefusal
32726
32873
  });
32727
32874
  }
32728
32875
  function enrollmentGuidance(status) {
@@ -34317,8 +34464,8 @@ function isWindowsSharingError(error, platform) {
34317
34464
  }
34318
34465
  async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile15, unlink: unlink12 }) {
34319
34466
  const started = performance.now();
34320
- for (const delay4 of SHARING_RETRY_DELAYS_MS) {
34321
- if (delay4 > 0) await new Promise((done) => setTimeout(done, delay4));
34467
+ for (const delay5 of SHARING_RETRY_DELAYS_MS) {
34468
+ if (delay5 > 0) await new Promise((done) => setTimeout(done, delay5));
34322
34469
  let same;
34323
34470
  try {
34324
34471
  same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
@@ -34792,7 +34939,7 @@ async function assertLegacyPoolInUse(legacyPath) {
34792
34939
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
34793
34940
  }
34794
34941
  }
34795
- function refusalMessage2(admission) {
34942
+ function accountStoreAdmissionMessage(admission) {
34796
34943
  switch (admission.status) {
34797
34944
  case "busy":
34798
34945
  return new AccountStoreBusyError().message;
@@ -34827,7 +34974,7 @@ function unboundOpening(binding) {
34827
34974
  return {
34828
34975
  status: "refused",
34829
34976
  admission: binding,
34830
- message: refusalMessage2(binding)
34977
+ message: accountStoreAdmissionMessage(binding)
34831
34978
  };
34832
34979
  }
34833
34980
  async function openAccountStore(options) {
@@ -34869,7 +35016,7 @@ async function openAccountStore(options) {
34869
35016
  return {
34870
35017
  status: "refused",
34871
35018
  admission,
34872
- message: refusalMessage2(admission)
35019
+ message: accountStoreAdmissionMessage(admission)
34873
35020
  };
34874
35021
  }
34875
35022
  }
@@ -42562,14 +42709,14 @@ var BackgroundVaultQuotaRefresh = class {
42562
42709
  this.abortTick();
42563
42710
  await this.inFlight;
42564
42711
  }
42565
- schedule(delay4, intervalWait = null) {
42712
+ schedule(delay5, intervalWait = null) {
42566
42713
  if (this.disposed || !this.started) return;
42567
42714
  this.intervalWait = intervalWait;
42568
42715
  this.timer = setTimeout(() => {
42569
42716
  this.timer = null;
42570
42717
  this.intervalWait = null;
42571
42718
  void this.tick();
42572
- }, delay4);
42719
+ }, delay5);
42573
42720
  this.timer.unref?.();
42574
42721
  }
42575
42722
  /** One serialized tick; also used by deterministic composition tests. */
@@ -48648,7 +48795,7 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
48648
48795
  statusText: scrubbedStatusText,
48649
48796
  headers: plainHeaders
48650
48797
  });
48651
- throw freshError;
48798
+ throw markUpstreamFailure(freshError);
48652
48799
  }
48653
48800
  noteGeminiDumpResponse(dumpContext, response);
48654
48801
  appendGeminiDumpResponseText(dumpContext, text2);
@@ -49165,7 +49312,7 @@ async function retainResponseLifetime(response, cancellation) {
49165
49312
 
49166
49313
  // src/plugin/shared/request-services.ts
49167
49314
  init_dist();
49168
- import { createHash as createHash16, randomUUID as randomUUID20 } from "node:crypto";
49315
+ import { createHash as createHash17, randomUUID as randomUUID20 } from "node:crypto";
49169
49316
 
49170
49317
  // src/common-auth-embedded/claustrum/host.js
49171
49318
  import { ClaustrumCredentialError as ClaustrumCredentialError8 } from "@cortexkit/claustrum-client";
@@ -49265,6 +49412,9 @@ function hasVaultHost2() {
49265
49412
  return process.env.CORTEXKIT_VAULT_HOST === "thalamus";
49266
49413
  }
49267
49414
 
49415
+ // src/common-auth-embedded/routing-accessor/index.js
49416
+ import { createHash as createHash16 } from "node:crypto";
49417
+
49268
49418
  // src/common-auth-embedded/routing-accessor/handle.js
49269
49419
  function routingHandle(sessionId) {
49270
49420
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
@@ -49302,6 +49452,39 @@ function isObject2(value) {
49302
49452
  function isNonEmptyString(value) {
49303
49453
  return typeof value === "string" && value.length > 0;
49304
49454
  }
49455
+ function isBoundedControlFreeString(value, maxLength) {
49456
+ return isNonEmptyString(value) && value.length <= maxLength && !/\p{Cc}/u.test(value);
49457
+ }
49458
+ function isRoutingCode(value) {
49459
+ return typeof value === "string" && /^[a-z0-9._-]{1,64}$/.test(value);
49460
+ }
49461
+ function continueExhaustion(value) {
49462
+ if (!isObject2(value) || Array.isArray(value))
49463
+ return void 0;
49464
+ const { accountId, credentialId, limitWindow, observedAtMs } = value;
49465
+ if (!isBoundedControlFreeString(accountId, 256) || !isBoundedControlFreeString(credentialId, 256) || typeof observedAtMs !== "number" || !Number.isSafeInteger(observedAtMs) || observedAtMs <= 0 || limitWindow !== "five_hour" && limitWindow !== "seven_day" && limitWindow !== "signed_out")
49466
+ return void 0;
49467
+ const exhausted = {
49468
+ account: accountId,
49469
+ credential_id: credentialId,
49470
+ limit_window: limitWindow,
49471
+ observed_at_ms: observedAtMs
49472
+ };
49473
+ if (limitWindow === "signed_out") {
49474
+ if ("pool" in value || "resetsAtMs" in value || "retryAfterS" in value)
49475
+ return void 0;
49476
+ return exhausted;
49477
+ }
49478
+ const { pool, resetsAtMs, retryAfterS } = value;
49479
+ if (pool !== void 0 && !isRoutingCode(pool) || resetsAtMs !== void 0 && (typeof resetsAtMs !== "number" || !Number.isSafeInteger(resetsAtMs) || resetsAtMs <= 0) || retryAfterS !== void 0 && (typeof retryAfterS !== "number" || !Number.isFinite(retryAfterS) || retryAfterS < 0))
49480
+ return void 0;
49481
+ return {
49482
+ ...exhausted,
49483
+ ...pool !== void 0 ? { pool } : {},
49484
+ ...resetsAtMs !== void 0 ? { resets_at_ms: resetsAtMs } : {},
49485
+ ...retryAfterS !== void 0 ? { retry_after_s: Math.floor(retryAfterS) } : {}
49486
+ };
49487
+ }
49305
49488
  function billingCache(value) {
49306
49489
  if (!isObject2(value) || Array.isArray(value))
49307
49490
  return;
@@ -49349,6 +49532,22 @@ function billingUsage(value) {
49349
49532
  }
49350
49533
  return Object.keys(usage).length > 0 ? usage : void 0;
49351
49534
  }
49535
+ function candidateView(candidates) {
49536
+ const accounts = [];
49537
+ for (const { accountId, credentialId } of candidates) {
49538
+ if (isNonEmptyString(accountId) && isBoundedControlFreeString(credentialId, 256)) {
49539
+ accounts.push({ account_id: accountId, credential_id: credentialId });
49540
+ }
49541
+ }
49542
+ if (accounts.length === 0)
49543
+ return void 0;
49544
+ const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
49545
+ `, "utf8")).sort(Buffer.compare);
49546
+ const hash2 = createHash16("sha256");
49547
+ for (const line of lines)
49548
+ hash2.update(line);
49549
+ return { view_digest: hash2.digest("hex"), accounts };
49550
+ }
49352
49551
  function selectionFor(answer, candidates) {
49353
49552
  if (!isObject2(answer))
49354
49553
  return void 0;
@@ -49377,10 +49576,11 @@ function refusalFor(value) {
49377
49576
  return void 0;
49378
49577
  }
49379
49578
  const refused2 = { code: code2 };
49380
- const routingCode = value.routing_code;
49381
- if (typeof routingCode === "string" && /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
49579
+ const { routing_code: routingCode, reason } = value;
49580
+ if (isRoutingCode(routingCode))
49382
49581
  refused2.routingCode = routingCode;
49383
- }
49582
+ if (isRoutingCode(reason))
49583
+ refused2.reason = reason;
49384
49584
  const retryAfterSecs = value.retry_after_secs;
49385
49585
  if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs >= 0) {
49386
49586
  refused2.retryAfterSecs = retryAfterSecs;
@@ -49394,6 +49594,21 @@ function refusalFor(value) {
49394
49594
  async function askRouting(input2) {
49395
49595
  let timer;
49396
49596
  try {
49597
+ const request2 = {
49598
+ provider: input2.provider,
49599
+ modelId: input2.modelId
49600
+ };
49601
+ if (input2.mode === "continue") {
49602
+ const { requestId } = input2;
49603
+ if (!isBoundedControlFreeString(requestId, 128))
49604
+ return void 0;
49605
+ const exhausted = continueExhaustion(input2.exhausted);
49606
+ if (!exhausted)
49607
+ return void 0;
49608
+ request2.mode = "continue";
49609
+ request2.request_id = requestId;
49610
+ request2.exhausted = exhausted;
49611
+ }
49397
49612
  const handle = routingHandle(input2.sessionId);
49398
49613
  if (!handle)
49399
49614
  return void 0;
@@ -49406,10 +49621,6 @@ async function askRouting(input2) {
49406
49621
  timer = setTimeout(() => resolve34(void 0), deadlineMs);
49407
49622
  timer.unref();
49408
49623
  });
49409
- const request2 = {
49410
- provider: input2.provider,
49411
- modelId: input2.modelId
49412
- };
49413
49624
  const cap = input2.holdWaitMaxS;
49414
49625
  if (typeof cap === "number" && Number.isFinite(cap)) {
49415
49626
  request2.hold_wait_max_s = Math.max(0, Math.floor(cap));
@@ -49417,9 +49628,12 @@ async function askRouting(input2) {
49417
49628
  if (input2.refusals === true)
49418
49629
  request2.refusals = true;
49419
49630
  const warmCredentialId = input2.warmCredentialId;
49420
- if (isNonEmptyString(warmCredentialId) && warmCredentialId.length <= 256 && !/\p{Cc}/u.test(warmCredentialId) && input2.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
49631
+ if (isBoundedControlFreeString(warmCredentialId, 256) && input2.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
49421
49632
  request2.warm_credential = warmCredentialId;
49422
49633
  }
49634
+ const candidates = candidateView(input2.candidates);
49635
+ if (candidates)
49636
+ request2.candidates = candidates;
49423
49637
  const pending = accountFor.call(handle, request2, { deadlineMs });
49424
49638
  if (!isObject2(pending) || typeof pending.then !== "function")
49425
49639
  return void 0;
@@ -49446,6 +49660,19 @@ function reportRouting(input2) {
49446
49660
  let payload;
49447
49661
  if ("kind" in input2) {
49448
49662
  switch (input2.kind) {
49663
+ case "transient_backoff": {
49664
+ const { accountId, credentialId, retryAtMs, providerCode } = input2;
49665
+ if (!isNonEmptyString(sessionId) || !isNonEmptyString(accountId) || !Number.isSafeInteger(retryAtMs) || retryAtMs <= 0 || credentialId !== void 0 && !isBoundedControlFreeString(credentialId, 256) || providerCode !== void 0 && !isBoundedControlFreeString(providerCode, 128))
49666
+ return;
49667
+ payload = {
49668
+ kind: "transient_backoff",
49669
+ account_id: accountId,
49670
+ ...credentialId !== void 0 ? { credential_id: credentialId } : {},
49671
+ retry_at_ms: retryAtMs,
49672
+ ...providerCode !== void 0 ? { provider_code: providerCode } : {}
49673
+ };
49674
+ break;
49675
+ }
49449
49676
  case "wait": {
49450
49677
  const { phase, waitId, reason, nextMs, attempt, message, outcome } = input2;
49451
49678
  if (!isNonEmptyString(sessionId) || phase !== "start" && phase !== "end" || !isNonEmptyString(waitId) || waitId.length > 64 || /[^A-Za-z0-9._:-]/.test(waitId) || !PLUGIN_WAIT_REASONS.includes(reason))
@@ -49541,7 +49768,7 @@ function reportRouting(input2) {
49541
49768
  const { window, pool } = input2;
49542
49769
  if (window !== "5h" && window !== "7d")
49543
49770
  return;
49544
- if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
49771
+ if (pool !== void 0 && !isRoutingCode(pool))
49545
49772
  return;
49546
49773
  payload = {
49547
49774
  ...identity4,
@@ -50149,20 +50376,26 @@ function routingExhaustionFields(scope) {
50149
50376
  };
50150
50377
  }
50151
50378
  function reportVaultExhaustion(input2, report = reportRouting) {
50152
- 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())
50379
+ const observedAtMs = input2.observedAt;
50380
+ const now2 = Date.now();
50381
+ if (!hasVaultRoutingAccessor() || input2.signal?.aborted || input2.status !== 429 || input2.reason !== "QUOTA_EXHAUSTED" || observedAtMs === void 0 || !Number.isFinite(observedAtMs) || observedAtMs <= 0 || observedAtMs > now2)
50153
50382
  return;
50383
+ let proof;
50154
50384
  for (const window of input2.quota?.windows ?? []) {
50155
50385
  if (window.remainingFraction !== 0) continue;
50156
50386
  const scope = routingQuotaScope(input2.group, window.window);
50157
50387
  const resetsAt = Date.parse(window.resetTime);
50158
- if (!scope || !Number.isFinite(resetsAt) || resetsAt <= Date.now()) continue;
50388
+ if (!scope || !Number.isFinite(resetsAt) || resetsAt <= now2) continue;
50159
50389
  report({
50160
50390
  ...input2.identity,
50161
50391
  outcome: "exhausted",
50162
50392
  ...routingExhaustionFields(scope),
50163
50393
  resetsAt
50164
50394
  });
50395
+ proof ??= { ...scope, observedAtMs, resetsAtMs: resetsAt };
50396
+ if (input2.singleReport) break;
50165
50397
  }
50398
+ return proof;
50166
50399
  }
50167
50400
  var RATE_LIMIT_HEADERS = [
50168
50401
  "retry-after",
@@ -50318,17 +50551,75 @@ var VAULT_ROUTING_PURPOSE_HEADER = "x-antigravity-internal-request-purpose";
50318
50551
  function createVaultRoutingHeaders(providerId) {
50319
50552
  return async (input2, output2) => {
50320
50553
  if (input2.model.providerID !== providerId) return;
50321
- output2.headers[VAULT_ROUTING_PURPOSE_HEADER] = input2.agent === "build" || input2.agent === "plan" ? "primary" : "auxiliary";
50554
+ output2.headers[VAULT_ROUTING_PURPOSE_HEADER] = input2.agent === "title" ? "title" : input2.agent === "build" || input2.agent === "plan" ? "primary" : "auxiliary";
50322
50555
  };
50323
50556
  }
50324
- function isPrimaryVaultRequest(kind, headers) {
50325
- return kind === void 0 ? new Headers(headers).get(VAULT_ROUTING_PURPOSE_HEADER) === "primary" : kind === "primary";
50557
+ function isTitleVaultRequest(kind, headers) {
50558
+ return kind === void 0 ? new Headers(headers).get(VAULT_ROUTING_PURPOSE_HEADER) === "title" : kind === "title";
50326
50559
  }
50327
50560
 
50328
50561
  // src/plugin/shared/request-services.ts
50329
50562
  var FIRST_RETRY_DELAY_MS = 1e3;
50330
50563
  var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
50331
50564
  var ROUTING_ASK_DEADLINE_MS = 2e3;
50565
+ var REFUSAL_BODY_TIMEOUT_MS = 2e3;
50566
+ var REFUSAL_BODY_MAX_BYTES = 64 * 1024;
50567
+ async function readRefusalBody(response, deadline) {
50568
+ const reader = response.body?.getReader();
50569
+ if (!reader) return { response, text: "" };
50570
+ const buffer = new Uint8Array(REFUSAL_BODY_MAX_BYTES);
50571
+ const stopAt = performance.now() + REFUSAL_BODY_TIMEOUT_MS;
50572
+ let size = 0;
50573
+ let finished = false;
50574
+ let timer;
50575
+ try {
50576
+ finished = await deadline.wait(
50577
+ () => Promise.race([
50578
+ (async () => {
50579
+ try {
50580
+ while (true) {
50581
+ const chunk = await reader.read();
50582
+ if (performance.now() >= stopAt) return false;
50583
+ if (chunk.done) return true;
50584
+ if (size + chunk.value.byteLength > buffer.byteLength)
50585
+ return false;
50586
+ buffer.set(chunk.value, size);
50587
+ size += chunk.value.byteLength;
50588
+ }
50589
+ } catch {
50590
+ return false;
50591
+ }
50592
+ })(),
50593
+ new Promise((resolve34) => {
50594
+ timer = setTimeout(() => resolve34(false), REFUSAL_BODY_TIMEOUT_MS);
50595
+ })
50596
+ ])
50597
+ );
50598
+ } finally {
50599
+ clearTimeout(timer);
50600
+ if (!finished) void reader.cancel().catch(() => {
50601
+ });
50602
+ reader.releaseLock();
50603
+ }
50604
+ const body = finished ? buffer.subarray(0, size) : null;
50605
+ const headers = new Headers(response.headers);
50606
+ if (!finished) {
50607
+ headers.delete("content-length");
50608
+ headers.delete("content-encoding");
50609
+ }
50610
+ return {
50611
+ response: preserveResponseMetadata2(
50612
+ new Response(body, {
50613
+ status: response.status,
50614
+ statusText: response.statusText,
50615
+ headers
50616
+ }),
50617
+ response
50618
+ ),
50619
+ text: body ? new TextDecoder().decode(body) : void 0
50620
+ };
50621
+ }
50622
+ var routingIdentityKey = ({ accountId, credentialId }) => JSON.stringify([accountId, credentialId]);
50332
50623
  function routingRefusalRetryAfterSeconds(refused2, now2) {
50333
50624
  const { retryAfterSecs, resetsAtMs } = refused2;
50334
50625
  if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs > 0) {
@@ -50562,7 +50853,7 @@ function createRequestExecutor(deps) {
50562
50853
  return JSON.stringify([
50563
50854
  "pool-file",
50564
50855
  account.email?.toLowerCase(),
50565
- createHash16("sha256").update(parseRefreshParts(refresh).refreshToken).digest("hex")
50856
+ createHash17("sha256").update(parseRefreshParts(refresh).refreshToken).digest("hex")
50566
50857
  ]);
50567
50858
  };
50568
50859
  const tierOf2 = (account) => JSON.stringify([account.capturedTierId, account.capturedPaidTierId]);
@@ -50721,17 +51012,16 @@ function createRequestExecutor(deps) {
50721
51012
  ...sendOptions,
50722
51013
  signal: deadline.signal
50723
51014
  };
50724
- if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
50725
51015
  let pending;
50726
51016
  try {
50727
51017
  pending = sender(url, sendInit, optionsWithSignal);
50728
51018
  } catch (error) {
50729
- onSenderRejection(error);
50730
- throw error;
51019
+ onSenderRejection?.(error);
51020
+ throw markUpstreamFailure(error);
50731
51021
  }
50732
51022
  return pending.catch((error) => {
50733
- onSenderRejection(error);
50734
- throw error;
51023
+ onSenderRejection?.(error);
51024
+ throw markUpstreamFailure(error);
50735
51025
  });
50736
51026
  });
50737
51027
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -50866,11 +51156,80 @@ function createRequestExecutor(deps) {
50866
51156
  let allAccountsBlockedAt;
50867
51157
  const modelUnavailableIndexes = /* @__PURE__ */ new Set();
50868
51158
  let routingPlacementConsidered = false;
51159
+ let routedCandidate;
51160
+ let continueRouting;
51161
+ const refusedRoutes = /* @__PURE__ */ new Map();
51162
+ let routingTitle = false;
51163
+ let routingWaitMs = 0;
51164
+ const failedRoutedPick = () => createNativeGoogleErrorResponse({
51165
+ status: 412,
51166
+ reason: "routing_refused"
51167
+ });
51168
+ const routingWaitRemainingMs = () => Math.min(
51169
+ deadline.remainingMs(),
51170
+ maxWaitMs > 0 ? Math.max(0, maxWaitMs - routingWaitMs) : Infinity
51171
+ );
51172
+ const routingRefusalResponse = (refused2) => {
51173
+ const { code: code2, routingCode, reason } = refused2;
51174
+ log18.warn("routing-refused", {
51175
+ code: code2,
51176
+ ...routingCode === void 0 ? {} : { routingCode },
51177
+ ...reason === void 0 ? {} : { reason }
51178
+ });
51179
+ const retryAfterSeconds = routingRefusalRetryAfterSeconds(
51180
+ refused2,
51181
+ Date.now()
51182
+ );
51183
+ return createNativeGoogleErrorResponse({
51184
+ status: 412,
51185
+ reason: "routing_refused",
51186
+ ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
51187
+ });
51188
+ };
51189
+ const waitOnRoutedAccount = async (ms, reason, attempt) => {
51190
+ if (ms >= deadline.remainingMs() || maxWaitMs > 0 && routingWaitMs + ms > maxWaitMs)
51191
+ return false;
51192
+ routingWaitMs += ms;
51193
+ if (ms > 0) await routingSleep(ms, reason, attempt);
51194
+ checkAborted();
51195
+ return true;
51196
+ };
51197
+ const unconfirmedRefusal = () => new Response(
51198
+ JSON.stringify({
51199
+ error: {
51200
+ code: 412,
51201
+ status: "FAILED_PRECONDITION",
51202
+ message: UNCONFIRMED_RATE_LIMIT_MESSAGE
51203
+ }
51204
+ }),
51205
+ { status: 412, headers: { "Content-Type": "application/json" } }
51206
+ );
51207
+ const retryAfterRoutedBackoff = async (identity4, retryAtMs, response) => {
51208
+ checkAborted();
51209
+ reportRouting({ ...identity4, kind: "transient_backoff", retryAtMs });
51210
+ void response.body?.cancel().catch(() => {
51211
+ });
51212
+ if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51213
+ return unconfirmedRefusal();
51214
+ unconfirmedRetries++;
51215
+ if (!await waitOnRoutedAccount(
51216
+ Math.max(0, retryAtMs - Date.now()),
51217
+ "rate_limited",
51218
+ unconfirmedRetries
51219
+ ))
51220
+ return unconfirmedRefusal();
51221
+ };
50869
51222
  while (true) {
50870
51223
  await assertAdmission();
50871
51224
  checkAborted();
51225
+ const choice = routedCandidate;
51226
+ routedCandidate = void 0;
51227
+ const exhausted = continueRouting;
51228
+ continueRouting = void 0;
51229
+ if (exhausted) refusedRoutes.set(routingIdentityKey(exhausted), exhausted);
50872
51230
  const accountCount = accountManager.getAccountCount();
50873
51231
  if (accountCount === 0) {
51232
+ if (choice) return failedRoutedPick();
50874
51233
  return createNoAccountResponse(
50875
51234
  "No Antigravity accounts available. Run `opencode auth login`.",
50876
51235
  model ?? "unknown"
@@ -50881,7 +51240,7 @@ function createRequestExecutor(deps) {
50881
51240
  config.quota_refresh_interval_minutes
50882
51241
  );
50883
51242
  const allowlistExcluded = modelAccessExcluded(model);
50884
- if (allowlistExcluded) {
51243
+ if (allowlistExcluded && !exhausted && !choice) {
50885
51244
  const serviceable = accountManager.getAccounts().filter(
50886
51245
  (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired
50887
51246
  );
@@ -50902,9 +51261,38 @@ function createRequestExecutor(deps) {
50902
51261
  }
50903
51262
  }
50904
51263
  const permittedAccounts = allowlistExcluded ? accountManager.getAccounts().filter((entry) => !allowlistExcluded.has(entry.index)) : accountManager.getAccounts();
51264
+ const modelUnavailableForPass = () => /* @__PURE__ */ new Set([...modelUnavailableIndexes, ...rememberedIndexes(model)]);
51265
+ let routingUnavailableIndexes;
51266
+ const vaultCredentials = credentials.domain === "vault" ? credentials : void 0;
51267
+ const routingPresent = vaultCredentials !== void 0 && hasVaultRoutingAccessor();
51268
+ routingTitle ||= routingPresent && isTitleVaultRequest(kind, init?.headers);
51269
+ let account = null;
51270
+ if (routingPresent && accountSessionIdentity && vaultCredentials?.routingCandidate) {
51271
+ const candidateFor = vaultCredentials.routingCandidate;
51272
+ const row = choice ? accountManager.getAccounts().find((entry) => {
51273
+ const current = candidateFor(entry);
51274
+ return current.credentialId === choice.credentialId && current.accountId === choice.accountId;
51275
+ }) : !routingPlacementConsidered ? accountManager.getRoutedAccountForFamily(
51276
+ family,
51277
+ accountSessionIdentity
51278
+ ) : null;
51279
+ if (row && !allowlistExcluded?.has(row.index)) {
51280
+ routingUnavailableIndexes = modelUnavailableForPass();
51281
+ if (!routingUnavailableIndexes.has(row.index))
51282
+ account = accountManager.useRoutedAccount(
51283
+ row,
51284
+ family,
51285
+ model ?? void 0,
51286
+ accountSessionIdentity,
51287
+ !routingTitle
51288
+ );
51289
+ }
51290
+ }
51291
+ const routedPlacement = account !== null;
51292
+ if (choice && !routedPlacement) return failedRoutedPick();
50905
51293
  const operatorKillswitch = operatorSettings?.get().killswitch;
50906
51294
  const floorKeying = operatorSettings?.floorKeying?.();
50907
- const eligibleIndexes = operatorKillswitch?.enabled ? new Set(
51295
+ const eligibleIndexes = !routedPlacement && operatorKillswitch?.enabled ? new Set(
50908
51296
  permittedAccounts.filter((entry) => {
50909
51297
  const decision = evaluateKillswitchForAccount(
50910
51298
  entry,
@@ -50922,7 +51310,7 @@ function createRequestExecutor(deps) {
50922
51310
  return decision.allowed;
50923
51311
  }).map((entry) => entry.index)
50924
51312
  ) : null;
50925
- if (eligibleIndexes !== null && eligibleIndexes.size === 0 && permittedAccounts.length > 0) {
51313
+ if (!exhausted && eligibleIndexes !== null && eligibleIndexes.size === 0 && permittedAccounts.length > 0) {
50926
51314
  try {
50927
51315
  throwIfAllKilled({
50928
51316
  family,
@@ -50957,11 +51345,8 @@ function createRequestExecutor(deps) {
50957
51345
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
50958
51346
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
50959
51347
  );
50960
- const unavailableIndexes = /* @__PURE__ */ new Set([
50961
- ...modelUnavailableIndexes,
50962
- ...rememberedIndexes(model)
50963
- ]);
50964
- if (unavailableIndexes.size > 0) {
51348
+ const unavailableIndexes = routingUnavailableIndexes ?? modelUnavailableForPass();
51349
+ if (!exhausted && !routedPlacement && unavailableIndexes.size > 0) {
50965
51350
  const candidates = accountManager.getAccounts().filter(
50966
51351
  (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired && !allowlistExcluded?.has(entry.index) && (eligibleIndexes === null || eligibleIndexes.has(entry.index))
50967
51352
  );
@@ -50985,12 +51370,20 @@ function createRequestExecutor(deps) {
50985
51370
  ...unavailableIndexes,
50986
51371
  ...allowlistExcluded ?? []
50987
51372
  ]);
50988
- const routingPresent = credentials.domain === "vault" && hasVaultRoutingAccessor();
50989
- const firstPlacement = routingPresent && !routingPlacementConsidered && accountSessionIdentity && !accountManager.getCurrentAccountForFamily(
51373
+ const firstPlacement = routingPresent && !routedPlacement && !routingPlacementConsidered && accountSessionIdentity && !accountManager.getCurrentAccountForFamily(
50990
51374
  family,
50991
51375
  accountSessionIdentity
50992
51376
  );
50993
- let account = accountManager.getCurrentOrNextForFamily(
51377
+ const isHardEligible = (row) => row.enabled !== false && !row.accountIneligible && !row.verificationRequired && !allowlistExcluded?.has(row.index) && !unavailableIndexes.has(row.index);
51378
+ const isRoutingCandidate = (row) => isHardEligible(row) && !killedIndexes?.has(row.index) && !accountManager.isAccountOverSoftQuota(
51379
+ row,
51380
+ family,
51381
+ config.soft_quota_threshold_percent,
51382
+ softQuotaCacheTtlMs,
51383
+ model,
51384
+ excludedIndexes
51385
+ );
51386
+ const selectLocally = () => accountManager.getCurrentOrNextForFamily(
50994
51387
  family,
50995
51388
  model,
50996
51389
  config.account_selection_strategy,
@@ -50998,73 +51391,77 @@ function createRequestExecutor(deps) {
50998
51391
  config.soft_quota_threshold_percent,
50999
51392
  softQuotaCacheTtlMs,
51000
51393
  accountSessionIdentity,
51001
- excludedIndexes
51394
+ excludedIndexes,
51395
+ !routingTitle
51002
51396
  );
51003
- if (account) {
51004
- routingPlacementConsidered = true;
51005
- if (firstPlacement && credentials.domain === "vault" && credentials.routingCandidate && model && isPrimaryVaultRequest(kind, init?.headers)) {
51006
- const candidates = accountManager.getAccounts().filter(
51007
- (row) => row.enabled !== false && !row.accountIneligible && !row.verificationRequired && !excludedIndexes?.has(row.index) && !accountManager.isRateLimited(row, family, model) && !accountManager.isAccountCoolingDown(row) && !accountManager.isAccountOverSoftQuota(
51008
- row,
51009
- family,
51010
- config.soft_quota_threshold_percent,
51011
- softQuotaCacheTtlMs,
51012
- model,
51013
- excludedIndexes
51014
- )
51015
- ).map((row) => ({
51016
- ...credentials.routingCandidate(row),
51017
- index: row.index
51018
- }));
51019
- if (candidates.length > 0) {
51020
- const answer = await deadline.wait(
51021
- () => askRouting({
51022
- sessionId: accountSessionIdentity.id,
51023
- provider: "antigravity",
51024
- modelId: model,
51025
- candidates,
51026
- deadlineMs: Math.min(
51027
- ROUTING_ASK_DEADLINE_MS,
51028
- deadline.remainingMs()
51029
- ),
51030
- refusals: true
51031
- })
51397
+ if (!exhausted) account ??= selectLocally();
51398
+ if (account) routingPlacementConsidered = true;
51399
+ if ((firstPlacement || exhausted) && routingPresent && accountSessionIdentity && vaultCredentials?.routingCandidate && model) {
51400
+ const roster = accountManager.getAccounts();
51401
+ const currentKey = exhausted && routingIdentityKey(exhausted);
51402
+ const holdCandidate = exhausted?.limitWindow !== "signed_out" && currentKey;
51403
+ const candidates = roster.flatMap((row) => {
51404
+ const eligible = isRoutingCandidate(row);
51405
+ if (!eligible && (!holdCandidate || !isHardEligible(row))) return [];
51406
+ const candidate = { ...vaultCredentials.routingCandidate(row) };
51407
+ const key2 = routingIdentityKey(candidate);
51408
+ if (key2 === holdCandidate && isHardEligible(row)) return [candidate];
51409
+ const refusal3 = refusedRoutes.get(key2);
51410
+ if (refusal3 && (refusal3.limitWindow === "signed_out" || (refusal3.resetsAtMs ?? Infinity) > Date.now()))
51411
+ return [];
51412
+ return eligible ? [candidate] : [];
51413
+ });
51414
+ if (candidates.length > 0 || exhausted) {
51415
+ routingPlacementConsidered = true;
51416
+ const canHold = !!holdCandidate && candidates.some(
51417
+ (candidate) => routingIdentityKey(candidate) === holdCandidate
51418
+ );
51419
+ const answer = await deadline.wait(() => {
51420
+ const input3 = {
51421
+ sessionId: accountSessionIdentity.id,
51422
+ provider: "antigravity",
51423
+ modelId: model,
51424
+ candidates,
51425
+ deadlineMs: Math.min(
51426
+ ROUTING_ASK_DEADLINE_MS,
51427
+ deadline.remainingMs()
51428
+ ),
51429
+ refusals: true
51430
+ };
51431
+ return askRouting(
51432
+ exhausted ? {
51433
+ ...input3,
51434
+ mode: "continue",
51435
+ requestId: randomUUID20(),
51436
+ exhausted,
51437
+ holdWaitMaxS: canHold ? Math.floor(routingWaitRemainingMs() / 1e3) : 0
51438
+ } : input3
51032
51439
  );
51033
- checkAborted();
51034
- if (answer && "refused" in answer) {
51035
- const { code: code2, routingCode } = answer.refused;
51036
- log18.warn("routing-refused", {
51037
- code: code2,
51038
- ...routingCode === void 0 ? {} : { routingCode }
51039
- });
51040
- const retryAfterSeconds = routingRefusalRetryAfterSeconds(
51041
- answer.refused,
51042
- Date.now()
51043
- );
51440
+ });
51441
+ checkAborted();
51442
+ if (answer && "refused" in answer)
51443
+ return routingRefusalResponse(answer.refused);
51444
+ if (exhausted && answer?.hold) {
51445
+ if (!canHold || routingIdentityKey(answer.candidate) !== holdCandidate)
51446
+ return failedRoutedPick();
51447
+ const delay5 = answer.hold.retry_after_ms;
51448
+ if (!await waitOnRoutedAccount(delay5, "account_limit"))
51044
51449
  return createNativeGoogleErrorResponse({
51045
51450
  status: 412,
51046
- reason: "routing_refused",
51047
- ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
51451
+ reason: "pool_unavailable",
51452
+ resetAfterMs: delay5
51048
51453
  });
51049
- }
51050
- if (answer && answer.candidate.index !== account.index && !excludedIndexes?.has(answer.candidate.index)) {
51051
- account = accountManager.getCurrentOrNextForFamily(
51052
- family,
51053
- model,
51054
- config.account_selection_strategy,
51055
- config.pid_offset_enabled,
51056
- config.soft_quota_threshold_percent,
51057
- softQuotaCacheTtlMs,
51058
- accountSessionIdentity,
51059
- /* @__PURE__ */ new Set([
51060
- ...excludedIndexes ?? [],
51061
- ...accountManager.getAccounts().filter((row) => row.index !== answer.candidate.index).map((row) => row.index)
51062
- ])
51063
- ) ?? account;
51064
- }
51454
+ } else if (answer && exhausted && routingIdentityKey(answer.candidate) === holdCandidate) {
51455
+ return failedRoutedPick();
51456
+ }
51457
+ const currentRoster = accountManager.getAccounts();
51458
+ if (answer || exhausted || currentRoster.length !== roster.length || currentRoster.some((row, index) => row !== roster[index])) {
51459
+ routedCandidate = answer?.candidate;
51460
+ continue;
51065
51461
  }
51066
51462
  }
51067
51463
  }
51464
+ if (exhausted) account ??= selectLocally();
51068
51465
  if (account && allowlistExcluded?.has(account.index)) {
51069
51466
  pushDebug(`model-access-excluded idx=${account.index}`);
51070
51467
  account = null;
@@ -51224,7 +51621,8 @@ function createRequestExecutor(deps) {
51224
51621
  );
51225
51622
  }
51226
51623
  previousAccountIndex = account.index;
51227
- accountManager.recordSessionUsage(account.index, accountSessionIdentity);
51624
+ if (!routingTitle)
51625
+ accountManager.recordSessionUsage(account.index, accountSessionIdentity);
51228
51626
  if (debug.isDebugEnabled()) {
51229
51627
  debug.logAccountContext("Selected", {
51230
51628
  index: account.index,
@@ -51428,6 +51826,7 @@ function createRequestExecutor(deps) {
51428
51826
  }
51429
51827
  }
51430
51828
  const selected = account;
51829
+ const expectedRoutedCredential = routedPlacement ? choice ?? vaultCredentials?.routingCandidate?.(selected) : void 0;
51431
51830
  const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
51432
51831
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
51433
51832
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
@@ -51616,7 +52015,7 @@ function createRequestExecutor(deps) {
51616
52015
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
51617
52016
  );
51618
52017
  }
51619
- if (accountManager.isRateLimited(account, family, model)) {
52018
+ if (!routedPlacement && accountManager.isRateLimited(account, family, model)) {
51620
52019
  shouldSwitchAccount = true;
51621
52020
  }
51622
52021
  let totalCapacityRetries = 0;
@@ -51641,12 +52040,17 @@ function createRequestExecutor(deps) {
51641
52040
  let sendAccessToken;
51642
52041
  let sendProjectId;
51643
52042
  if (credentials.domain === "vault") {
51644
- sendAdmission = rotatedAdmission ?? await deadline.wait(
51645
- () => credentials.admit({
51646
- account,
51647
- signal: abortSignal
51648
- })
51649
- );
52043
+ try {
52044
+ sendAdmission = rotatedAdmission ?? await deadline.wait(
52045
+ () => credentials.admit({ account, signal: abortSignal })
52046
+ );
52047
+ } catch (error) {
52048
+ checkAborted();
52049
+ if (routedPlacement) return failedRoutedPick();
52050
+ throw error;
52051
+ }
52052
+ if (expectedRoutedCredential && (sendAdmission.credentialId !== expectedRoutedCredential.credentialId || sendAdmission.accountIdentity !== expectedRoutedCredential.accountId))
52053
+ return failedRoutedPick();
51650
52054
  rotatedAdmission = void 0;
51651
52055
  sendAccessToken = sendAdmission.accessToken;
51652
52056
  sendProjectId = sendAdmission.projectId;
@@ -51747,7 +52151,7 @@ function createRequestExecutor(deps) {
51747
52151
  `dispatching request via ${prepared.headerStyle} transport`
51748
52152
  );
51749
52153
  physicalAttemptStarted = true;
51750
- const response = await sendPhysical(
52154
+ let response = await sendPhysical(
51751
52155
  toUrlString(prepared.request),
51752
52156
  prepared.init,
51753
52157
  sendAdmission,
@@ -51755,6 +52159,12 @@ function createRequestExecutor(deps) {
51755
52159
  kind ?? "primary",
51756
52160
  retainMainTransportFailure
51757
52161
  );
52162
+ const receivedAtMs = Date.now();
52163
+ let boundedRefusal;
52164
+ if (routingPresent && (response.status === 429 || response.status === 403 || response.status === 404)) {
52165
+ boundedRefusal = await readRefusalBody(response, deadline);
52166
+ response = boundedRefusal.response;
52167
+ }
51758
52168
  if (response.ok) deadline.acceptHeaders();
51759
52169
  apiRequestCount++;
51760
52170
  accountManager.recordRequest(account.index, family);
@@ -51806,6 +52216,13 @@ function createRequestExecutor(deps) {
51806
52216
  }
51807
52217
  }
51808
52218
  const sessionKey = requestSessionIdentity.sessionId;
52219
+ const unreadableLimit = response.status === 429 && boundedRefusal !== void 0 && boundedRefusal.text === void 0;
52220
+ const routingIdentity = (routedPlacement || unreadableLimit) && sendAdmission && sessionKey && hasVaultRoutingAccessor() ? {
52221
+ sessionId: sessionKey,
52222
+ accountId: sendAdmission.accountIdentity,
52223
+ credentialId: sendAdmission.credentialId
52224
+ } : void 0;
52225
+ const routedIdentity = routedPlacement ? routingIdentity : void 0;
51809
52226
  if (sessionKey) {
51810
52227
  const routingEntry = {
51811
52228
  accountId: `acct-${account.index}`,
@@ -51825,9 +52242,7 @@ function createRequestExecutor(deps) {
51825
52242
  const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1e3;
51826
52243
  const bodyInfo = await (async () => {
51827
52244
  try {
51828
- const text2 = await deadline.wait(
51829
- () => response.clone().text()
51830
- );
52245
+ const text2 = boundedRefusal ? boundedRefusal.text ?? "" : await deadline.wait(() => response.clone().text());
51831
52246
  try {
51832
52247
  return JSON.parse(text2);
51833
52248
  } catch {
@@ -51849,28 +52264,45 @@ function createRequestExecutor(deps) {
51849
52264
  reasonInfo.message,
51850
52265
  response.status
51851
52266
  );
52267
+ const retryAtMs = Math.min(
52268
+ Number.MAX_SAFE_INTEGER,
52269
+ // Use the short unconfirmed cooldown when the response doesn't
52270
+ // contain a retry time recognized by the executor.
52271
+ receivedAtMs + (reasonInfo.retryDelayMs ?? unconfirmedRateLimitDelayMs(
52272
+ response.headers.get("retry-after"),
52273
+ receivedAtMs
52274
+ ))
52275
+ );
52276
+ const routed429 = response.status === 429 ? routedIdentity : void 0;
51852
52277
  if (response.status === 429 && rateLimitReason === "UNKNOWN") {
51853
52278
  await logResponseBody2(debugContext, response, 429);
51854
52279
  const outgoing = JSON.parse(String(prepared.init.body));
51855
52280
  const recognised = systemInstructionHasHarnessIdentity(
51856
52281
  outgoing.request?.systemInstruction
51857
52282
  );
51858
- const terminal = () => new Response(
51859
- JSON.stringify({
51860
- error: {
51861
- code: 412,
51862
- status: "FAILED_PRECONDITION",
51863
- message: UNCONFIRMED_RATE_LIMIT_MESSAGE
51864
- }
51865
- }),
51866
- {
51867
- status: 412,
51868
- headers: { "Content-Type": "application/json" }
51869
- }
51870
- );
52283
+ if (recognised) {
52284
+ void response.body?.cancel().catch(() => {
52285
+ });
52286
+ return unconfirmedRefusal();
52287
+ }
52288
+ if (routed429) {
52289
+ const refusal3 = await retryAfterRoutedBackoff(
52290
+ routed429,
52291
+ retryAtMs,
52292
+ response
52293
+ );
52294
+ if (refusal3) return refusal3;
52295
+ i -= 1;
52296
+ continue;
52297
+ }
52298
+ if (routingIdentity)
52299
+ reportRouting({
52300
+ ...routingIdentity,
52301
+ kind: "transient_backoff",
52302
+ retryAtMs
52303
+ });
51871
52304
  void response.body?.cancel().catch(() => {
51872
52305
  });
51873
- if (recognised) return terminal();
51874
52306
  const delayMs = unconfirmedRateLimitDelayMs(
51875
52307
  response.headers.get("retry-after")
51876
52308
  );
@@ -51905,7 +52337,7 @@ function createRequestExecutor(deps) {
51905
52337
  break;
51906
52338
  }
51907
52339
  if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51908
- return terminal();
52340
+ return unconfirmedRefusal();
51909
52341
  unconfirmedRetries++;
51910
52342
  const ready = accountManager.getAccounts().some((entry) => {
51911
52343
  const resets2 = entry.rateLimitResetTimes;
@@ -51925,13 +52357,14 @@ function createRequestExecutor(deps) {
51925
52357
  i -= 1;
51926
52358
  continue;
51927
52359
  }
52360
+ let exhaustion;
51928
52361
  if (credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor()) {
51929
52362
  const group = resolveQuotaGroup(
51930
52363
  family,
51931
52364
  model,
51932
52365
  account.cachedQuota
51933
52366
  );
51934
- reportVaultExhaustion({
52367
+ exhaustion = reportVaultExhaustion({
51935
52368
  identity: {
51936
52369
  sessionId: sessionKey,
51937
52370
  accountId: sendAdmission.accountIdentity,
@@ -51942,12 +52375,33 @@ function createRequestExecutor(deps) {
51942
52375
  group,
51943
52376
  quota: account.cachedQuota?.[group],
51944
52377
  observedAt: account.cachedQuotaUpdatedAt,
51945
- signal: abortSignal
52378
+ signal: abortSignal,
52379
+ singleReport: !!routed429
51946
52380
  });
51947
52381
  }
52382
+ if (routed429 && rateLimitReason === "QUOTA_EXHAUSTED" && !exhaustion) {
52383
+ const refusal3 = await retryAfterRoutedBackoff(
52384
+ routed429,
52385
+ retryAtMs,
52386
+ response
52387
+ );
52388
+ if (refusal3) return refusal3;
52389
+ i -= 1;
52390
+ continue;
52391
+ }
51948
52392
  if (rateLimitReason === "MODEL_CAPACITY_EXHAUSTED" || rateLimitReason === "SERVER_ERROR") {
51949
52393
  totalCapacityRetries++;
51950
52394
  if (isCapacityRetryBudgetExhausted(totalCapacityRetries)) {
52395
+ if (routed429) {
52396
+ const refusal3 = await retryAfterRoutedBackoff(
52397
+ routed429,
52398
+ retryAtMs,
52399
+ response
52400
+ );
52401
+ if (refusal3) return refusal3;
52402
+ i -= 1;
52403
+ continue;
52404
+ }
51951
52405
  pushDebug(
51952
52406
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
51953
52407
  );
@@ -52062,6 +52516,16 @@ function createRequestExecutor(deps) {
52062
52516
  serverRetryMs,
52063
52517
  config.failure_ttl_seconds * 1e3
52064
52518
  );
52519
+ if (routed429) {
52520
+ const refusal3 = await retryAfterRoutedBackoff(
52521
+ routed429,
52522
+ retryAtMs,
52523
+ response
52524
+ );
52525
+ if (refusal3) return refusal3;
52526
+ i -= 1;
52527
+ continue;
52528
+ }
52065
52529
  shouldSwitchAccount = true;
52066
52530
  break;
52067
52531
  }
@@ -52077,6 +52541,16 @@ function createRequestExecutor(deps) {
52077
52541
  config.failure_ttl_seconds * 1e3
52078
52542
  );
52079
52543
  accountManager.requestSaveToDisk();
52544
+ if (routed429 && !exhaustion) {
52545
+ const refusal3 = await retryAfterRoutedBackoff(
52546
+ routed429,
52547
+ retryAtMs,
52548
+ response
52549
+ );
52550
+ if (refusal3) return refusal3;
52551
+ i -= 1;
52552
+ continue;
52553
+ }
52080
52554
  const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
52081
52555
  if (accountCount > 1) {
52082
52556
  const quotaMsg = reasonInfo.quotaResetTime ? ` (quota resets ${reasonInfo.quotaResetTime})` : ``;
@@ -52102,11 +52576,15 @@ function createRequestExecutor(deps) {
52102
52576
  );
52103
52577
  }
52104
52578
  retainHttpFailure(response);
52579
+ if (routed429 && exhaustion) {
52580
+ const { accountId, credentialId } = routed429;
52581
+ continueRouting = { accountId, credentialId, ...exhaustion };
52582
+ }
52105
52583
  shouldSwitchAccount = true;
52106
52584
  break;
52107
52585
  }
52108
52586
  if (response.status === 404 && currentEndpoint === ANTIGRAVITY_ENDPOINT_DAILY) {
52109
- const notFoundBody = await deadline.wait(
52587
+ const notFoundBody = boundedRefusal ? boundedRefusal.text ?? "" : await deadline.wait(
52110
52588
  () => response.clone().text().catch(() => "")
52111
52589
  );
52112
52590
  const unavailable2 = parseModelUnavailableError(notFoundBody);
@@ -52141,11 +52619,20 @@ function createRequestExecutor(deps) {
52141
52619
  retryState.resetRateLimitState(account.index, quotaKey);
52142
52620
  retryState.resetAccountFailureState(account.index);
52143
52621
  if (response.status === 403) {
52144
- const errorBodyText = await deadline.wait(
52622
+ const errorBodyText = boundedRefusal ? boundedRefusal.text : await deadline.wait(
52145
52623
  () => response.clone().text().catch(() => "")
52146
52624
  );
52147
- const extracted = classifyAccessError(errorBodyText);
52148
- if (extracted.accountIneligible) {
52625
+ const extracted = errorBodyText === void 0 ? void 0 : classifyAccessError(errorBodyText);
52626
+ if (routedIdentity && (extracted?.accountIneligible || extracted?.validationRequired)) {
52627
+ const { accountId, credentialId } = routedIdentity;
52628
+ continueRouting = {
52629
+ accountId,
52630
+ credentialId,
52631
+ limitWindow: "signed_out",
52632
+ observedAtMs: receivedAtMs
52633
+ };
52634
+ }
52635
+ if (extracted?.accountIneligible) {
52149
52636
  const ineligibleReason = extracted.message ?? "Google marked this account as ineligible for Antigravity.";
52150
52637
  accountManager.markAccountIneligible(
52151
52638
  account.index,
@@ -52167,7 +52654,7 @@ function createRequestExecutor(deps) {
52167
52654
  shouldSwitchAccount = true;
52168
52655
  break;
52169
52656
  }
52170
- if (extracted.validationRequired) {
52657
+ if (extracted?.validationRequired) {
52171
52658
  const verificationReason = extracted.message ?? "Google requires account verification.";
52172
52659
  const cooldownMs = 10 * 60 * 1e3;
52173
52660
  accountManager.markAccountVerificationRequired(
@@ -52215,7 +52702,7 @@ function createRequestExecutor(deps) {
52215
52702
  if (!advisoryClosing)
52216
52703
  accountManager.markAccountUsed(account.index);
52217
52704
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
52218
- if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
52705
+ if (!advisoryClosing && !routingPresent && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
52219
52706
  family,
52220
52707
  model,
52221
52708
  proactiveThreshold,
@@ -52254,7 +52741,11 @@ function createRequestExecutor(deps) {
52254
52741
  await logResponseBody2(debugContext, response, response.status);
52255
52742
  if (response.status === 400) {
52256
52743
  const cloned = response.clone();
52257
- const bodyText = await deadline.wait(() => cloned.text());
52744
+ const bodyText = await deadline.wait(
52745
+ () => cloned.text().catch((error) => {
52746
+ throw markUpstreamFailure(error);
52747
+ })
52748
+ );
52258
52749
  if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
52259
52750
  await showToast(
52260
52751
  "Context too long - use /compact to reduce size",
@@ -52269,7 +52760,11 @@ function createRequestExecutor(deps) {
52269
52760
  const maxAttempts = config.empty_response_max_attempts ?? 4;
52270
52761
  const retryDelayMs = config.empty_response_retry_delay_ms ?? 2e3;
52271
52762
  const clonedForCheck = response.clone();
52272
- const bodyText = await deadline.wait(() => clonedForCheck.text());
52763
+ const bodyText = await deadline.wait(
52764
+ () => clonedForCheck.text().catch((error) => {
52765
+ throw markUpstreamFailure(error);
52766
+ })
52767
+ );
52273
52768
  if (isEmptyResponseBody(bodyText)) {
52274
52769
  const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
52275
52770
  const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
@@ -52508,7 +53003,9 @@ function createRequestExecutor(deps) {
52508
53003
  function dispose() {
52509
53004
  disposePromise ??= (async () => {
52510
53005
  retired = true;
52511
- shutdown.abort(new Error("The Antigravity request executor is disposed"));
53006
+ shutdown.abort(
53007
+ new HostRefusalError("The Antigravity request executor is disposed")
53008
+ );
52512
53009
  await drain();
52513
53010
  })();
52514
53011
  return disposePromise;
@@ -52517,11 +53014,11 @@ function createRequestExecutor(deps) {
52517
53014
  execute(input2, init, requestOptions) {
52518
53015
  if (shutdown.signal.aborted)
52519
53016
  return Promise.reject(
52520
- new Error("The Antigravity request executor is disposed")
53017
+ new HostRefusalError("The Antigravity request executor is disposed")
52521
53018
  );
52522
53019
  if (retired)
52523
53020
  return Promise.reject(
52524
- new Error("The Antigravity request executor is retired")
53021
+ new HostRefusalError("The Antigravity request executor is retired")
52525
53022
  );
52526
53023
  const requestedSignal = init?.signal ?? (input2 instanceof Request ? input2.signal : void 0);
52527
53024
  const cancellation = createRequestCancellation(
@@ -52540,6 +53037,14 @@ function createRequestExecutor(deps) {
52540
53037
  const waitPolicy = {};
52541
53038
  const selectedCredentials = /* @__PURE__ */ new Set();
52542
53039
  const selectedProjectIds = /* @__PURE__ */ new Set();
53040
+ const redactFailure = (error) => {
53041
+ const redacted = redactCredentialError(
53042
+ error,
53043
+ [...selectedCredentials],
53044
+ [...selectedProjectIds]
53045
+ );
53046
+ return isUpstreamFailure(error) ? markUpstreamFailure(redacted) : redacted;
53047
+ };
52543
53048
  const pending = withRoutingWaitReports(
52544
53049
  cancellation.signal,
52545
53050
  (waits) => deadline.wait(
@@ -52600,21 +53105,13 @@ function createRequestExecutor(deps) {
52600
53105
  handoff.cancel();
52601
53106
  deadline.dispose();
52602
53107
  cancellation.release();
52603
- throw redactCredentialError(
52604
- error,
52605
- [...selectedCredentials],
52606
- [...selectedProjectIds]
52607
- );
53108
+ throw redactFailure(error);
52608
53109
  }
52609
53110
  ).catch((error) => {
52610
53111
  handoff.cancel();
52611
53112
  deadline.dispose();
52612
53113
  cancellation.release();
52613
- throw redactCredentialError(
52614
- error,
52615
- [...selectedCredentials],
52616
- [...selectedProjectIds]
52617
- );
53114
+ throw redactFailure(error);
52618
53115
  });
52619
53116
  inFlight.add(pending);
52620
53117
  void pending.then(
@@ -53097,12 +53594,12 @@ function createSettingsRuntime(options) {
53097
53594
  void enqueue(refreshAll);
53098
53595
  });
53099
53596
  };
53100
- const scheduleAttempt = (delay4) => {
53597
+ const scheduleAttempt = (delay5) => {
53101
53598
  if (disposed) return;
53102
53599
  retryTimer = setTimeout(() => {
53103
53600
  retryTimer = void 0;
53104
53601
  void enqueue(attemptMove);
53105
- }, delay4);
53602
+ }, delay5);
53106
53603
  retryTimer.unref?.();
53107
53604
  };
53108
53605
  const attemptMove = async () => {
@@ -53281,7 +53778,7 @@ function createSettingsRuntime(options) {
53281
53778
  (item) => item.file.kind === "user" && item.file.path === file || projectFiles.has(item.file.path)
53282
53779
  );
53283
53780
  };
53284
- const diagnostics = async (entry) => {
53781
+ const diagnostics2 = async (entry) => {
53285
53782
  if (options.separateInstall) return [];
53286
53783
  if (mode === "legacy") {
53287
53784
  const reason = lastMove === "fence-closed" ? "an older antigravity-auth is still running. Restart OpenCode after updating to finish the move" : lastMove === "failed" ? "the move failed and is retried" : "the move has not finished yet";
@@ -53361,7 +53858,7 @@ function createSettingsRuntime(options) {
53361
53858
  accountModels: () => mode === "shared" ? protection?.accountModels : void 0,
53362
53859
  updateAccountModels,
53363
53860
  limitsNotices: limits,
53364
- diagnosticsNotices: () => diagnostics(entry),
53861
+ diagnosticsNotices: () => diagnostics2(entry),
53365
53862
  moveReport: {
53366
53863
  present: async () => mode === "shared" && moveReport !== void 0,
53367
53864
  async dismiss() {
@@ -53457,9 +53954,9 @@ async function openCodeSettingsPaths(project3) {
53457
53954
 
53458
53955
  // src/plugin/background-quota-refresh.ts
53459
53956
  init_file_lock();
53460
- import { createHash as createHash17 } from "node:crypto";
53957
+ import { createHash as createHash18 } from "node:crypto";
53461
53958
  function quotaAccountIdentity2(refreshToken) {
53462
- return createHash17("sha256").update(refreshToken).digest("hex").slice(0, 16);
53959
+ return createHash18("sha256").update(refreshToken).digest("hex").slice(0, 16);
53463
53960
  }
53464
53961
  var MIN_INTERVAL_MS = 6e4;
53465
53962
  var STARTUP_JITTER_MS = 3e4;
@@ -54855,8 +55352,15 @@ function tokenExchange(overrides) {
54855
55352
  }
54856
55353
  function storeRefusal(status) {
54857
55354
  if (status.status === "busy") return new AccountStoreBusyError();
54858
- return new Error(
54859
- status.status === "initialization-required" ? "The Antigravity account store is not initialized; initialize it with the antigravity-auth CLI." : status.status === "error" ? `The Antigravity account store cannot be opened: ${status.reason}` : `The Antigravity account store is ${status.status}; finish its migration or rollback with \`antigravity-auth migrate --offline\` or \`antigravity-auth rollback --offline\`.`
55355
+ if (status.status === "error") {
55356
+ const error = new Error(
55357
+ `The Antigravity account store cannot be opened: ${status.reason}`
55358
+ );
55359
+ error.name = "AccountStoreAdmissionError";
55360
+ return error;
55361
+ }
55362
+ return new HostRefusalError(
55363
+ status.status === "initialization-required" ? "The Antigravity account store is not initialized; initialize it with the antigravity-auth CLI." : `The Antigravity account store is ${status.status}; finish its migration or rollback with \`antigravity-auth migrate --offline\` or \`antigravity-auth rollback --offline\`.`
54860
55364
  );
54861
55365
  }
54862
55366
  async function openLocationRepository(directory, bindings, overrides, login) {
@@ -54896,7 +55400,7 @@ async function assertServingAdmission(location, now2) {
54896
55400
  );
54897
55401
  if (admission.status === "active") return;
54898
55402
  if (admission.status === "pending" && admission.phase === "activate")
54899
- throw new Error(
55403
+ throw new HostRefusalError(
54900
55404
  "An Antigravity account operation is still finishing; reopen the session once it completes."
54901
55405
  );
54902
55406
  throw storeRefusal(admission);
@@ -55385,8 +55889,7 @@ async function createGaVaultLocationServices(input2) {
55385
55889
  onError: (error) => vaultLogger.debug("vault-state-write-dropped", {
55386
55890
  error: error instanceof Error ? error.name : "unknown"
55387
55891
  })
55388
- },
55389
- grantPrincipal: () => custody.grantPrincipal?.()
55892
+ }
55390
55893
  });
55391
55894
  pipeline = await createGaVaultRequestPipeline({
55392
55895
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -55510,6 +56013,14 @@ function createGaLocationServicesFactory(bindings) {
55510
56013
  const nextReadSeq = () => ++readSeq;
55511
56014
  const registry = createGaSelectorRegistry(bindings.createSelector);
55512
56015
  let unavailableReason = VAULT_ACCOUNT_REMEDY;
56016
+ const sourceRefusal = () => {
56017
+ if (unavailableReason === VAULT_ACCOUNT_REMEDY)
56018
+ return new HostRefusalError(VAULT_ACCOUNT_REMEDY);
56019
+ const layout = currentVaultFolder(
56020
+ bindings.resolveAccountFile(directory)
56021
+ ).refusal;
56022
+ return layout?.message === unavailableReason ? layout : new Error(unavailableReason);
56023
+ };
55513
56024
  const authority = async () => {
55514
56025
  if (!custody) return "local";
55515
56026
  const mode = await custody.readMode();
@@ -55520,7 +56031,7 @@ function createGaLocationServicesFactory(bindings) {
55520
56031
  if (closing) throw new Error("The location services are disposed");
55521
56032
  const selected = await authority();
55522
56033
  if (closing) throw new Error("The location services are disposed");
55523
- if (selected !== "local") throw new Error(unavailableReason);
56034
+ if (selected !== "local") throw sourceRefusal();
55524
56035
  };
55525
56036
  let refreshVaultBinding;
55526
56037
  const refreshSelectedSource = async () => {
@@ -55745,7 +56256,7 @@ function createGaLocationServicesFactory(bindings) {
55745
56256
  });
55746
56257
  const recovery = {
55747
56258
  execute: async () => {
55748
- throw new Error(unavailableReason);
56259
+ throw sourceRefusal();
55749
56260
  },
55750
56261
  state: {
55751
56262
  read: async ({ signal }) => {
@@ -55975,8 +56486,7 @@ ${GA_POOL_PASTE_PROMPT}, or wait for the browser to finish.`;
55975
56486
  },
55976
56487
  assertAdmission: async () => {
55977
56488
  const selected = await authority();
55978
- if (closing || selected !== "vault")
55979
- throw new Error(unavailableReason);
56489
+ if (closing || selected !== "vault") throw sourceRefusal();
55980
56490
  }
55981
56491
  });
55982
56492
  try {
@@ -56001,7 +56511,7 @@ ${GA_POOL_PASTE_PROMPT}, or wait for the browser to finish.`;
56001
56511
  if (closing) throw new Error("The location services are disposed");
56002
56512
  if (selected === "local") return local();
56003
56513
  if (selected === "unreadable") {
56004
- if (purpose === "execute") throw new Error(unavailableReason);
56514
+ if (purpose === "execute") throw sourceRefusal();
56005
56515
  return recovery;
56006
56516
  }
56007
56517
  try {
@@ -56172,9 +56682,30 @@ var createGaLocationServices = (input2) => {
56172
56682
  return createGaLocationServicesForHost({ readHostSlot })(input2);
56173
56683
  };
56174
56684
 
56685
+ // src/plugin/shared/opencode-retry-hints.ts
56686
+ var RETRY_PATTERNS = [
56687
+ /429|500|502|503|504|524/i,
56688
+ /rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,
56689
+ /overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,
56690
+ /terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,
56691
+ /^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,
56692
+ /try your request again|retry your request|resource exhausted|resource_exhausted/i,
56693
+ /\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i,
56694
+ // Non-API errors also have a branch that checks these substrings.
56695
+ /too_many_requests|exhausted|unavailable/i
56696
+ ];
56697
+ function openCodeRetryHint(text2) {
56698
+ for (const pattern of RETRY_PATTERNS) {
56699
+ const match = pattern.exec(text2);
56700
+ if (match) return match[0];
56701
+ }
56702
+ return void 0;
56703
+ }
56704
+
56175
56705
  // src/ga/server/index.ts
56176
56706
  init_storage();
56177
56707
  init_process_heartbeat();
56708
+ init_runtime_layout();
56178
56709
  init_vault_folder();
56179
56710
 
56180
56711
  // src/ga/proxy-guard.ts
@@ -57715,7 +58246,7 @@ function isGaGoogleContentRequest(request2) {
57715
58246
  return false;
57716
58247
  }
57717
58248
  }
57718
- function gaPreHeaderFailureResponse(error) {
58249
+ function gaPreHeaderFailureResponse(error, report = (message) => stderrLogSink({ service: "bridge", level: "warn", message })) {
57719
58250
  const err = error;
57720
58251
  const rawStatusCode = typeof err?.statusCode === "number" && Number.isSafeInteger(err.statusCode) ? err.statusCode : void 0;
57721
58252
  const rawStatus = typeof err?.status === "number" && Number.isSafeInteger(err.status) ? err.status : void 0;
@@ -57761,9 +58292,11 @@ function gaPreHeaderFailureResponse(error) {
57761
58292
  }
57762
58293
  }
57763
58294
  const rawMessage = error instanceof Error && error.message ? error.message : typeof err?.message === "string" && err.message ? err.message : "Antigravity request failed before a response arrived";
57764
- const redacted = redactProjectIdText(rawMessage);
57765
- const isQuota = isQuotaError(status, rawMessage, err?.details);
57766
- const message = isQuota ? normalizeResetDuration(redacted) : redacted;
58295
+ let message = gaHostFailure(error, report).message;
58296
+ if (isUpstreamFailure(error)) {
58297
+ const redacted = redactProjectIdText(rawMessage);
58298
+ message = isQuotaError(status, rawMessage, err?.details) ? normalizeResetDuration(redacted) : redacted;
58299
+ }
57767
58300
  const headers = new Headers({ "content-type": "application/json" });
57768
58301
  const metadata = resolveRetryMetadata({
57769
58302
  details: err?.details,
@@ -57882,14 +58415,20 @@ async function startGaLoopbackBridge(options) {
57882
58415
  try {
57883
58416
  upstream = await options.execute(entry.job, {
57884
58417
  signal: controller.signal,
57885
- send: options.send,
58418
+ send: async (...args) => {
58419
+ try {
58420
+ return await options.send(...args);
58421
+ } catch (error) {
58422
+ throw markUpstreamFailure(error);
58423
+ }
58424
+ },
57886
58425
  onResponseHandoff: (callback) => {
57887
58426
  acknowledge = callback;
57888
58427
  }
57889
58428
  });
57890
58429
  } catch (error) {
57891
58430
  acknowledge = void 0;
57892
- upstream = gaPreHeaderFailureResponse(error);
58431
+ upstream = gaPreHeaderFailureResponse(error, report);
57893
58432
  }
57894
58433
  await pipeResponse(
57895
58434
  upstream,
@@ -58497,17 +59036,14 @@ async function rewriteGaHttpRequest(event, input2) {
58497
59036
  if (!owned) return;
58498
59037
  const original = event.request;
58499
59038
  if (!isGaGoogleContentRequest(original)) {
58500
- throw new Error(GA_NON_CONTENT_REQUEST_MESSAGE);
59039
+ throw new HostRefusalError(GA_NON_CONTENT_REQUEST_MESSAGE);
58501
59040
  }
58502
59041
  if (!isCanonicalGoogleOrigin(original.url)) {
58503
- throw new Error(GA_CUSTOM_GOOGLE_ORIGIN_MESSAGE);
59042
+ throw new HostRefusalError(GA_CUSTOM_GOOGLE_ORIGIN_MESSAGE);
58504
59043
  }
58505
59044
  if (event.kind !== "title" && !input2.isRegisteredModel(event.model.id) && !isRetiredAgyModel(event.model.id)) {
58506
- const modelID = event.model.id;
58507
- const antigravityModelID = modelID.startsWith("antigravity-") ? null : `antigravity-${modelID}`;
58508
- const suggestion = antigravityModelID !== null && input2.isRegisteredModel(antigravityModelID) ? `Use google/${antigravityModelID}.` : "Choose a google/antigravity- model.";
58509
- throw new Error(
58510
- `This request cannot use Antigravity: google/${modelID} is not an Antigravity model. ${suggestion}`
59045
+ throw new HostRefusalError(
59046
+ offCatalogModelRefusal(event.model.id, input2.isRegisteredModel)
58511
59047
  );
58512
59048
  }
58513
59049
  const job = {
@@ -58521,6 +59057,15 @@ async function rewriteGaHttpRequest(event, input2) {
58521
59057
  };
58522
59058
  event.request = input2.bridge.rewrite(original, job, input2.env);
58523
59059
  }
59060
+ function offCatalogModelRefusal(modelID, isRegisteredModel) {
59061
+ const safeID = (id) => /^[A-Za-z0-9._/-]{1,128}$/.test(id) && !openCodeRetryHint(id);
59062
+ if (!safeID(modelID)) {
59063
+ return "This request cannot use Antigravity. Choose a google/antigravity- model.";
59064
+ }
59065
+ const twin = modelID.startsWith("antigravity-") ? null : `antigravity-${modelID}`;
59066
+ const suggestion = twin && safeID(twin) && isRegisteredModel(twin) ? `Use google/${twin}.` : "Choose a google/antigravity- model.";
59067
+ return `This request cannot use Antigravity: google/${modelID} is not an Antigravity model. ${suggestion}`;
59068
+ }
58524
59069
  function adaptGaHttpResponse(event, bridge) {
58525
59070
  const adapted = bridge.adaptResponse(event.request, event.response);
58526
59071
  if (adapted) event.response = adapted;
@@ -58579,6 +59124,11 @@ function stderrLogSink(record5) {
58579
59124
  } catch {
58580
59125
  }
58581
59126
  }
59127
+ function gaHostFailure(error, report) {
59128
+ if (error instanceof RuntimeLayoutRefusal || error instanceof LoopbackProxyGuardError || error instanceof GaSetupContextError)
59129
+ return error;
59130
+ return hostFailure(error, report);
59131
+ }
58582
59132
  function headerValue(request2, names) {
58583
59133
  for (const name of names) {
58584
59134
  const value = request2.headers.get(name);
@@ -58587,6 +59137,16 @@ function headerValue(request2, names) {
58587
59137
  return null;
58588
59138
  }
58589
59139
  async function setupGaActivation(context, factory, overrides = {}) {
59140
+ return setupGaActivationRuntime(context, factory, overrides).catch(
59141
+ (error) => {
59142
+ throw gaHostFailure(
59143
+ error,
59144
+ (message) => stderrLogSink({ service: "setup", level: "error", message })
59145
+ );
59146
+ }
59147
+ );
59148
+ }
59149
+ async function setupGaActivationRuntime(context, factory, overrides) {
58590
59150
  if (classifyGaSetupContext(context) === "legacy") return void 0;
58591
59151
  const directory = context.location.directory;
58592
59152
  const send = createGaRawSender(overrides);
@@ -58748,6 +59308,13 @@ async function setupGaActivation(context, factory, overrides = {}) {
58748
59308
  isRegisteredModel,
58749
59309
  env: process.env,
58750
59310
  ownership
59311
+ }).catch((error) => {
59312
+ if (event.request.signal.aborted && error === event.request.signal.reason)
59313
+ throw error;
59314
+ throw gaHostFailure(
59315
+ error,
59316
+ (message) => runtime.logger.createLogger("request").warn(message)
59317
+ );
58751
59318
  }),
58752
59319
  { providerID: GA_PROVIDER_ID }
58753
59320
  );
@@ -58775,7 +59342,8 @@ function createGaAntigravityPlugin(overrides = {}) {
58775
59342
 
58776
59343
  // src/plugin/index.ts
58777
59344
  init_dist();
58778
- import { createHash as createHash23, randomUUID as randomUUID26 } from "node:crypto";
59345
+ init_runtime_layout();
59346
+ import { createHash as createHash24, randomUUID as randomUUID26 } from "node:crypto";
58779
59347
  import { join as join47, resolve as resolve33 } from "node:path";
58780
59348
 
58781
59349
  // src/cli.ts
@@ -59078,7 +59646,7 @@ async function select2(terminal, items, options) {
59078
59646
  }
59079
59647
 
59080
59648
  // src/common-auth-embedded/claustrum/enrollment.js
59081
- import { createHash as createHash18, randomBytes as randomBytes6, randomUUID as randomUUID23 } from "node:crypto";
59649
+ import { createHash as createHash19, randomBytes as randomBytes6, randomUUID as randomUUID23 } from "node:crypto";
59082
59650
  import { constants as fsConstants2 } from "node:fs";
59083
59651
  import { chmod as chmod6, mkdir as mkdir18, open as open11, readFile as readFile20, realpath as realpath6, rename as rename13, stat as stat17, unlink as unlink14 } from "node:fs/promises";
59084
59652
  import { basename as basename13, dirname as dirname29, extname as extname2, isAbsolute as isAbsolute4, join as join34, resolve as resolve27 } from "node:path";
@@ -60721,7 +61289,7 @@ var ClaustrumEnrollmentManager2 = class {
60721
61289
  }
60722
61290
  if (!state2.requestId) {
60723
61291
  try {
60724
- const requestSecretHash = createHash18("sha256").update(Buffer.from(state2.requestSecret, "hex")).digest("hex");
61292
+ const requestSecretHash = createHash19("sha256").update(Buffer.from(state2.requestSecret, "hex")).digest("hex");
60725
61293
  const proposal = {
60726
61294
  name: state2.proposedName,
60727
61295
  requestSecretHash
@@ -61368,7 +61936,7 @@ async function detectHosts(plugin2, io = {}) {
61368
61936
  }
61369
61937
 
61370
61938
  // src/common-auth-embedded/setup/enroll.js
61371
- import { setTimeout as delay } from "node:timers/promises";
61939
+ import { setTimeout as delay2 } from "node:timers/promises";
61372
61940
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexkit/claustrum-client";
61373
61941
 
61374
61942
  // src/common-auth-embedded/setup/process-fence.js
@@ -61734,7 +62302,7 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61734
62302
  throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
61735
62303
  });
61736
62304
  const now2 = io.now ?? (() => performance.now());
61737
- const wait2 = io.wait ?? delay;
62305
+ const wait2 = io.wait ?? delay2;
61738
62306
  try {
61739
62307
  const manager = new ClaustrumEnrollmentManager2({
61740
62308
  proposedName: name,
@@ -61968,7 +62536,7 @@ async function selectSetupHosts(terminal, found) {
61968
62536
 
61969
62537
  // src/common-auth-embedded/setup/register.js
61970
62538
  import { rename as rename15 } from "node:fs/promises";
61971
- import { setTimeout as delay3 } from "node:timers/promises";
62539
+ import { setTimeout as delay4 } from "node:timers/promises";
61972
62540
  import { domainToUnicode } from "node:url";
61973
62541
  import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtLocation as findNodeAtLocation2, modify as modify2, parse as parse2, parseTree as parseTree2 } from "jsonc-parser";
61974
62542
 
@@ -61976,7 +62544,7 @@ import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtL
61976
62544
  import { randomUUID as randomUUID24 } from "node:crypto";
61977
62545
  import { mkdir as mkdir19, open as open12, rename as rename14, stat as stat19, unlink as unlink15 } from "node:fs/promises";
61978
62546
  import { basename as basename14, dirname as dirname30, join as join36 } from "node:path";
61979
- import { setTimeout as delay2 } from "node:timers/promises";
62547
+ import { setTimeout as delay3 } from "node:timers/promises";
61980
62548
  async function writeHostConfigAtomic(file, content, options = {}) {
61981
62549
  const windows2 = (options.platform ?? process.platform) === "win32";
61982
62550
  const parent = dirname30(file);
@@ -62015,7 +62583,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
62015
62583
  const remaining = 2e3 - (now2() - started);
62016
62584
  if (!windows2 || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
62017
62585
  throw new Error(`Unable to replace host config ${file}. Close editors or other programs using the file, then rerun setup.`);
62018
- await (options.wait ?? delay2)(Math.min(remaining, 25 * 2 ** Math.min(attempt, 2)));
62586
+ await (options.wait ?? delay3)(Math.min(remaining, 25 * 2 ** Math.min(attempt, 2)));
62019
62587
  }
62020
62588
  }
62021
62589
  } finally {
@@ -62186,7 +62754,7 @@ async function registerOpenCode(writes, beforeWrite) {
62186
62754
  // Only the rename publishes host-readable config; recheck on every retry.
62187
62755
  beforeRename: guard ? () => guard.check({ reuse: true }) : void 0,
62188
62756
  rename: guard ? (from, to) => guard.step(() => rename15(from, to)) : void 0,
62189
- wait: guard ? (ms) => guard.step(() => delay3(ms)) : void 0
62757
+ wait: guard ? (ms) => guard.step(() => delay4(ms)) : void 0
62190
62758
  });
62191
62759
  }
62192
62760
  }
@@ -64044,7 +64612,7 @@ function isTuiConnected(sessionId) {
64044
64612
  }
64045
64613
 
64046
64614
  // src/rpc/rpc-dir.ts
64047
- import { createHash as createHash19 } from "node:crypto";
64615
+ import { createHash as createHash20 } from "node:crypto";
64048
64616
  import { homedir as homedir14, tmpdir as tmpdir6 } from "node:os";
64049
64617
  import { isAbsolute as isAbsolute5, join as join42, resolve as resolve30 } from "node:path";
64050
64618
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
@@ -64053,7 +64621,7 @@ function getRpcDir(projectDirectory) {
64053
64621
  if (override) {
64054
64622
  return isAbsolute5(override) ? override : resolve30(projectDirectory, override);
64055
64623
  }
64056
- const projectHash = createHash19("sha256").update(resolve30(projectDirectory)).digest("hex").slice(0, 16);
64624
+ const projectHash = createHash20("sha256").update(resolve30(projectDirectory)).digest("hex").slice(0, 16);
64057
64625
  const stateHome = process.env.XDG_STATE_HOME ?? join42(homedir14(), ".local", "state");
64058
64626
  return join42(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
64059
64627
  }
@@ -64065,7 +64633,7 @@ function isSessionId(value) {
64065
64633
 
64066
64634
  // src/common-auth-embedded/rpc/port-file.js
64067
64635
  init_private_files2();
64068
- import { createHash as createHash20, randomUUID as randomUUID25 } from "node:crypto";
64636
+ import { createHash as createHash21, randomUUID as randomUUID25 } from "node:crypto";
64069
64637
  import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename16, rmdir as rmdir3, stat as stat20, unlink as unlink16 } from "node:fs/promises";
64070
64638
  import { uptime as uptime2 } from "node:os";
64071
64639
  import { join as join43, resolve as resolve31 } from "node:path";
@@ -67358,13 +67926,37 @@ function createAccountCommandOAuthService(options) {
67358
67926
 
67359
67927
  // src/plugin/auth-loader.ts
67360
67928
  init_dist();
67361
- import { createHash as createHash21 } from "node:crypto";
67929
+ init_runtime_layout();
67930
+ import { createHash as createHash22 } from "node:crypto";
67362
67931
  init_debug();
67363
67932
  init_logger4();
67364
67933
  init_storage();
67365
67934
  var log14 = createLogger4("auth-loader");
67935
+ var failureLog = createLogger("auth-loader");
67936
+ function loaderFailure(error) {
67937
+ if (error instanceof RuntimeLayoutRefusal) return error;
67938
+ return hostFailure(error, (diagnostic) => failureLog.error(diagnostic));
67939
+ }
67940
+ function openingFailure(opening) {
67941
+ if (opening.status === "recovery-required") {
67942
+ return new HostRefusalError(
67943
+ "An account clear or pool replacement was interrupted; it must be finished before the accounts are used."
67944
+ );
67945
+ }
67946
+ if (opening.status === "refused") {
67947
+ const { admission } = opening;
67948
+ if (admission.status === "busy") return new AccountStoreBusyError();
67949
+ if (admission.status === "pending" || admission.status === "inactive") {
67950
+ return new HostRefusalError(accountStoreAdmissionMessage(admission));
67951
+ }
67952
+ failureLog.error("Refusing to start: the account store cannot serve", {
67953
+ message: opening.message
67954
+ });
67955
+ }
67956
+ return new HostRefusalError(HOST_STORE_READ_FAILURE);
67957
+ }
67366
67958
  function refreshTokenIdentity(refreshToken) {
67367
- return createHash21("sha256").update(refreshToken).digest("hex").slice(0, 16);
67959
+ return createHash22("sha256").update(refreshToken).digest("hex").slice(0, 16);
67368
67960
  }
67369
67961
  async function initializeDefaultFreshStore() {
67370
67962
  return initializeFreshAccountStoreFor(await loadCommonAuthStoreModules());
@@ -67449,7 +68041,7 @@ function createAuthLoader({
67449
68041
  let closed2 = false;
67450
68042
  const isClosed = () => closed2 || lifecycle.isClosing();
67451
68043
  const assertOpen = () => {
67452
- if (isClosed()) throw new Error("The account loader is disposed");
68044
+ if (isClosed()) throw new HostRefusalError("The account loader is disposed");
67453
68045
  };
67454
68046
  let fetchRuntime = null;
67455
68047
  let localUnavailable = false;
@@ -67475,7 +68067,7 @@ function createAuthLoader({
67475
68067
  const installRuntime = async (accountManager, getAuth, source) => {
67476
68068
  if (isClosed()) {
67477
68069
  await accountManager.dispose();
67478
- throw new Error("The account loader is disposed");
68070
+ throw new HostRefusalError("The account loader is disposed");
67479
68071
  }
67480
68072
  currentRequestSource = "local";
67481
68073
  localUnavailable = false;
@@ -67499,10 +68091,12 @@ function createAuthLoader({
67499
68091
  const opening2 = await openStore();
67500
68092
  if (isClosed()) {
67501
68093
  await accountManager.dispose();
67502
- throw new Error("The account loader is disposed");
68094
+ throw new HostRefusalError("The account loader is disposed");
67503
68095
  }
67504
68096
  if (opening2.status !== "ready") {
67505
- throw new Error("the account store closed while it was in use");
68097
+ throw new HostRefusalError(
68098
+ "the account store closed while it was in use"
68099
+ );
67506
68100
  }
67507
68101
  const credentials = createLocalAccountCredentials(accountManager, {
67508
68102
  repository: opening2.repository
@@ -67521,7 +68115,7 @@ function createAuthLoader({
67521
68115
  if (isClosed() || opening !== void 0 && opening.status !== "ready") {
67522
68116
  await refreshQueue?.dispose();
67523
68117
  await accountManager.dispose();
67524
- throw new Error(
68118
+ throw new HostRefusalError(
67525
68119
  isClosed() ? "The account loader is disposed" : "the account store closed while it was in use"
67526
68120
  );
67527
68121
  }
@@ -67553,7 +68147,7 @@ function createAuthLoader({
67553
68147
  await accountManager.dispose();
67554
68148
  throw error;
67555
68149
  }
67556
- if (!published) throw new Error("The account loader is disposed");
68150
+ if (!published) throw new HostRefusalError("The account loader is disposed");
67557
68151
  assertOpen();
67558
68152
  refreshQueue?.start();
67559
68153
  if (publishSidebar) await publishSidebar();
@@ -67592,11 +68186,11 @@ function createAuthLoader({
67592
68186
  assertOpen();
67593
68187
  const claustrum = await loadCommonAuthClaustrum();
67594
68188
  assertOpen();
67595
- claustrum.assertHostSlotMatchesMode({
67596
- mode: "local",
67597
- auth,
67598
- provider: providerId
67599
- });
68189
+ if (claustrum.classifyHostSlot(auth, providerId) === "placeholder") {
68190
+ throw new HostRefusalError(
68191
+ "The host holds the vault placeholder; sign in to use local accounts."
68192
+ );
68193
+ }
67600
68194
  return auth;
67601
68195
  }
67602
68196
  async function runLoader(getAuth, provider2) {
@@ -67629,33 +68223,30 @@ function createAuthLoader({
67629
68223
  return finishLoad(provider2);
67630
68224
  }
67631
68225
  if (!usesPoolFile(opening)) {
67632
- const message = opening.status === "refused" || opening.status === "recovery-required" ? opening.message : "The Antigravity account store cannot be opened";
67633
- log14.error("Refusing to start: the account store cannot serve", {
67634
- message
67635
- });
68226
+ const refusal3 = openingFailure(opening);
67636
68227
  try {
67637
68228
  await client.tui.showToast({
67638
- body: { message, variant: "error", duration: 3e4 }
68229
+ body: {
68230
+ message: refusal3.message,
68231
+ variant: "error",
68232
+ duration: 3e4
68233
+ }
67639
68234
  });
67640
68235
  } catch {
67641
68236
  }
67642
- throw new Error(message);
68237
+ throw refusal3;
67643
68238
  }
67644
68239
  if (!isOAuthAuth(auth)) {
67645
68240
  let storedAccounts;
67646
68241
  try {
67647
68242
  storedAccounts = await deps.loadAccounts();
67648
68243
  } catch (error) {
68244
+ const refusal3 = loaderFailure(error);
67649
68245
  if (error instanceof AccountStorageUnreadableError) {
67650
- log14.error("Refusing to start: account storage is unreadable", {
67651
- path: error.details.path,
67652
- reason: error.details.reason,
67653
- backupPath: error.details.backupPath
67654
- });
67655
68246
  try {
67656
68247
  await client.tui.showToast({
67657
68248
  body: {
67658
- message: `Account storage at ${error.details.path} is unreadable (${error.details.reason}). The plugin will not start until the file is repaired or removed.${error.details.backupPath ? ` A backup was written to ${error.details.backupPath}.` : ""}`,
68249
+ message: refusal3.message,
67659
68250
  variant: "error",
67660
68251
  duration: 3e4
67661
68252
  }
@@ -67663,7 +68254,7 @@ function createAuthLoader({
67663
68254
  } catch {
67664
68255
  }
67665
68256
  }
67666
- throw error;
68257
+ throw refusal3;
67667
68258
  }
67668
68259
  assertOpen();
67669
68260
  const drift = detectAuthStorageDrift(auth, storedAccounts);
@@ -67732,44 +68323,54 @@ function createAuthLoader({
67732
68323
  // matches the host's `LoaderResult.fetch` signature exactly
67733
68324
  // (no `this` binding) so behavior is preserved.
67734
68325
  fetch: (input2, init) => publishResponse(async (onResponseHandoff) => {
67735
- assertOpen();
67736
- const authority = await readAuthority2?.() ?? "local";
67737
- assertOpen();
67738
- if (authority === "unreadable") throw new Error(unavailableMessage);
67739
- if (authority === "vault" || authority === "host") {
67740
- currentRequestSource = "vault";
67741
- if (!createVaultFetch) throw new Error(unavailableMessage);
67742
- vaultFetchRuntime ??= createVaultFetch().catch((error) => {
67743
- vaultFetchRuntime = null;
67744
- throw error;
67745
- });
67746
- const vaultRuntime = await vaultFetchRuntime;
68326
+ try {
67747
68327
  assertOpen();
67748
- return vaultRuntime.fetch(input2, init, onResponseHandoff);
67749
- }
67750
- if (localUnavailable) {
67751
- return fetchWithoutLocalAccounts(input2, init, fetchImpl);
67752
- }
67753
- if (readAuthority2 && (localRequestReload || currentRequestSource !== "local" || !fetchRuntime)) {
67754
- if (!latestGetAuth)
67755
- throw new Error("The host sign-in reader is unavailable");
67756
- if (!localRequestReload) {
67757
- const started = reload(latestGetAuth).finally(() => {
67758
- if (localRequestReload === started) localRequestReload = null;
68328
+ const authority = await readAuthority2?.() ?? "local";
68329
+ assertOpen();
68330
+ if (authority === "unreadable")
68331
+ throw new HostRefusalError(unavailableMessage);
68332
+ if (authority === "vault" || authority === "host") {
68333
+ currentRequestSource = "vault";
68334
+ if (!createVaultFetch)
68335
+ throw new HostRefusalError(unavailableMessage);
68336
+ vaultFetchRuntime ??= createVaultFetch().catch((error) => {
68337
+ vaultFetchRuntime = null;
68338
+ throw error;
67759
68339
  });
67760
- localRequestReload = started;
68340
+ const vaultRuntime = await vaultFetchRuntime;
68341
+ assertOpen();
68342
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
67761
68343
  }
67762
- await localRequestReload;
67763
- assertOpen();
67764
- if (await readAuthority2() !== "local")
67765
- throw new Error(unavailableMessage);
67766
- assertOpen();
68344
+ if (localUnavailable) {
68345
+ return fetchWithoutLocalAccounts(input2, init, fetchImpl);
68346
+ }
68347
+ if (readAuthority2 && (localRequestReload || currentRequestSource !== "local" || !fetchRuntime)) {
68348
+ if (!latestGetAuth)
68349
+ throw new HostRefusalError(
68350
+ "The host sign-in reader could not be read."
68351
+ );
68352
+ if (!localRequestReload) {
68353
+ const started = reload(latestGetAuth).finally(() => {
68354
+ if (localRequestReload === started) localRequestReload = null;
68355
+ });
68356
+ localRequestReload = started;
68357
+ }
68358
+ await localRequestReload;
68359
+ assertOpen();
68360
+ if (await readAuthority2() !== "local")
68361
+ throw new HostRefusalError(unavailableMessage);
68362
+ assertOpen();
68363
+ }
68364
+ if (localUnavailable)
68365
+ return fetchWithoutLocalAccounts(input2, init, fetchImpl);
68366
+ if (currentRequestSource !== "local" || !fetchRuntime)
68367
+ throw new HostRefusalError(
68368
+ "The local account runtime is not ready."
68369
+ );
68370
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
68371
+ } catch (error) {
68372
+ throw loaderFailure(error);
67767
68373
  }
67768
- if (localUnavailable)
67769
- return fetchWithoutLocalAccounts(input2, init, fetchImpl);
67770
- if (currentRequestSource !== "local" || !fetchRuntime)
67771
- throw new Error("The local account runtime is unavailable");
67772
- return fetchRuntime.fetch(input2, init, onResponseHandoff);
67773
68374
  })
67774
68375
  };
67775
68376
  }
@@ -67800,7 +68401,9 @@ function createAuthLoader({
67800
68401
  await installRuntime(nextManager, getAuth, "pool-file");
67801
68402
  };
67802
68403
  async function authLoaderCallable(getAuth, provider2) {
67803
- return runLoader(getAuth, provider2);
68404
+ return runLoader(getAuth, provider2).catch((error) => {
68405
+ throw loaderFailure(error);
68406
+ });
67804
68407
  }
67805
68408
  async function reload(getAuth) {
67806
68409
  assertOpen();
@@ -68116,7 +68719,7 @@ function registerAntigravityCommands(config) {
68116
68719
  }
68117
68720
 
68118
68721
  // src/plugin/command-data.ts
68119
- import { createHash as createHash22 } from "node:crypto";
68722
+ import { createHash as createHash23 } from "node:crypto";
68120
68723
  var QUOTA_GROUP_LABELS = {
68121
68724
  gemini: "Gemini",
68122
68725
  "non-gemini": "Non-Gemini",
@@ -68174,7 +68777,7 @@ function toCommandAccountRow(entry) {
68174
68777
  };
68175
68778
  }
68176
68779
  function quotaAccountIdentity3(refreshToken) {
68177
- return createHash22("sha256").update(refreshToken).digest("hex").slice(0, 16);
68780
+ return createHash23("sha256").update(refreshToken).digest("hex").slice(0, 16);
68178
68781
  }
68179
68782
  function projectCommandAccountRows(storage) {
68180
68783
  if (!storage) return [];
@@ -68358,6 +68961,12 @@ init_debug();
68358
68961
  init_logger4();
68359
68962
  init_vault_request_credentials();
68360
68963
  var log15 = createLogger4("fetch-interceptor");
68964
+ var failureLog2 = createLogger("fetch-interceptor");
68965
+ function fetchFailure(error, input2, init) {
68966
+ const signal = init?.signal ?? (input2 instanceof Request ? input2.signal : void 0);
68967
+ if (signal?.aborted && error === signal.reason) return error;
68968
+ return hostFailure(error, (diagnostic) => failureLog2.error(diagnostic));
68969
+ }
68361
68970
  var defaultAgyTransport = (url, init, options) => fetchWithAgyCliTransport(url, init, options);
68362
68971
  var defaultFetchImpl = (input2, init) => globalThis.fetch(input2, init);
68363
68972
  function poolFileCredentials(accountManager, client, providerId) {
@@ -68492,14 +69101,20 @@ function createFetchInterceptor(context) {
68492
69101
  let retirePromise;
68493
69102
  const entering = /* @__PURE__ */ new Set();
68494
69103
  async function intercept(input2, init, onResponseHandoff) {
68495
- await context.assertAdmission?.();
68496
- if (disposed) throw new Error("The local request runtime is disposed");
68497
- if (accountSource.kind === "pool-file") {
68498
- const latestAuth = await getAuth();
68499
- if (disposed) throw new Error("The local request runtime is disposed");
68500
- if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
69104
+ try {
69105
+ await context.assertAdmission?.();
69106
+ if (disposed)
69107
+ throw new HostRefusalError("The local request runtime is disposed");
69108
+ if (accountSource.kind === "pool-file") {
69109
+ const latestAuth = await getAuth();
69110
+ if (disposed)
69111
+ throw new HostRefusalError("The local request runtime is disposed");
69112
+ if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
69113
+ }
69114
+ return await executor.execute(input2, init, { onResponseHandoff });
69115
+ } catch (error) {
69116
+ throw fetchFailure(error, input2, init);
68501
69117
  }
68502
- return executor.execute(input2, init, { onResponseHandoff });
68503
69118
  }
68504
69119
  async function fetch(input2, init, onResponseHandoff) {
68505
69120
  if (disposed) {
@@ -68566,7 +69181,9 @@ function createVaultFetchInterceptor(context) {
68566
69181
  async function fetch(input2, init) {
68567
69182
  if (!isGenerativeLanguageRequest(input2)) return upstreamFetch(input2, init);
68568
69183
  if (disposed) throw new Error("The vault request runtime is disposed");
68569
- return executor.execute(input2, init);
69184
+ return executor.execute(input2, init).catch((error) => {
69185
+ throw fetchFailure(error, input2, init);
69186
+ });
68570
69187
  }
68571
69188
  function dispose() {
68572
69189
  disposed = true;
@@ -69042,12 +69659,12 @@ init_storage();
69042
69659
  init_vault_custody();
69043
69660
  var logger2 = createLogger4("plugin");
69044
69661
  function quotaAccountIdentity4(refreshToken) {
69045
- return createHash23("sha256").update(refreshToken).digest("hex").slice(0, 16);
69662
+ return createHash24("sha256").update(refreshToken).digest("hex").slice(0, 16);
69046
69663
  }
69047
69664
  function registerQuotaManagerProducer(lifecycle, quotaManager) {
69048
69665
  lifecycle.register({ dispose: () => quotaManager.dispose() }, "producer");
69049
69666
  }
69050
- var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69667
+ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2) => {
69051
69668
  const dependencies = resolvePluginDependencies(
69052
69669
  options.dependencies
69053
69670
  );
@@ -69159,8 +69776,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69159
69776
  source,
69160
69777
  pool: createOpenCodeVaultAccountPool({
69161
69778
  source,
69162
- durable: { source, readState: () => vaultCustody.readState() },
69163
- grantPrincipal: () => vaultCustody.grantPrincipal()
69779
+ durable: { source, readState: () => vaultCustody.readState() }
69164
69780
  })
69165
69781
  };
69166
69782
  return vaultPool;
@@ -69636,7 +70252,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69636
70252
  return createVaultFetchInterceptor({
69637
70253
  assertAdmission: async () => {
69638
70254
  if (!["host", "vault"].includes(await readAuthority2()))
69639
- throw new Error(unavailableMessage);
70255
+ throw new HostRefusalError(unavailableMessage);
69640
70256
  },
69641
70257
  client,
69642
70258
  config,
@@ -69662,7 +70278,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69662
70278
  createFetch: ({ accountManager, getAuth, source }) => createFetchInterceptor({
69663
70279
  assertAdmission: async () => {
69664
70280
  if (await readAuthority2() !== "local")
69665
- throw new Error(unavailableMessage);
70281
+ throw new HostRefusalError(unavailableMessage);
69666
70282
  },
69667
70283
  client,
69668
70284
  directory,
@@ -69825,6 +70441,13 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69825
70441
  }
69826
70442
  };
69827
70443
  };
70444
+ var createAntigravityPlugin = (providerId, options = {}) => {
70445
+ const load = createAntigravityPluginRuntime(providerId, options);
70446
+ return (input2) => load(input2).catch((error) => {
70447
+ if (error instanceof RuntimeLayoutRefusal) throw error;
70448
+ throw hostFailure(error, (diagnostic) => logger2.error(diagnostic));
70449
+ });
70450
+ };
69828
70451
  var AntigravityCLIOAuthPlugin = createAntigravityPlugin(
69829
70452
  ANTIGRAVITY_PROVIDER_ID
69830
70453
  );